Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Volund v0.6.0
plugins/Volund/Volund.Contracts.dll
Decompiled a day agousing System; using System.Diagnostics; using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("knowitallking")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("0.6.0+54c1fc2be67e0bf387d17146f6b8e8bd12e83722")] [assembly: AssemblyProduct("Volund.Contracts")] [assembly: AssemblyTitle("Volund.Contracts")] [assembly: InternalsVisibleTo("Volund")] [assembly: InternalsVisibleTo("Volund.Testing")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [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 Volund.Contracts { public readonly struct Command { public enum Kinds { None, Walk, Drive, Finish } public const float GameFriction = -1f; public Kinds Kind { get; } public Vector3 Velocity { get; } public BodyMode Body { get; } public float Friction { get; } public FallMode Fall { get; } public MotionPose Pose { get; } private Command(Kinds kind, Vector3 velocity, BodyMode body, float friction, FallMode fall, MotionPose pose) { Kind = kind; Velocity = velocity; Body = body; Friction = friction; Fall = fall; Pose = pose; } public static Command Walk(Vector3 drift) { return new Command(Kinds.Walk, drift, BodyMode.EngineGravity, -1f, FallMode.Vanilla, MotionPose.Airborne); } public static Command Drive(Vector3 velocity, BodyMode body, float friction, FallMode fall, MotionPose pose) { return new Command(Kinds.Drive, velocity, body, friction, fall, pose); } public static Command Finish() { return new Command(Kinds.Finish, Vector3.Zero, BodyMode.EngineGravity, -1f, FallMode.Vanilla, MotionPose.Airborne); } } public static class ContractVersion { public const int Major = 1; } public struct FittedFootprintSettings { public int RayCount; public float Radius; public float MaxResidual; public float RayDegrees; public float Reach; public float Skin; public float DisplayDegreesPerSecond; public float DisplayDegreesPerMetre; public float MaxDisplayLagDegrees; public bool AllowAdjacentGround; public float RetraceStride; } public interface IFittedFootprint { Vector3 DisplayNormal { get; } SurfaceResult SampleFitted(Vector3 travel, in FittedFootprintSettings settings, float seconds, out Vector3 feet, out Vector3 normal, out float separation); } public interface IFittedRestTrail { Vector3 Retrace(Vector3 proposedTravel, in FittedFootprintSettings settings); void ClearTrail(); } public readonly struct RestWalkCommand { public readonly Vector2 Axes; public readonly Vector3 View; public readonly Vector3 Forward; public RestWalkCommand(Vector2 axes, Vector3 view, Vector3 forward) { Axes = axes; View = view; Forward = forward; } } public interface ICommandedRestTrail { RestWalkCommand LastWalk { get; } void RecordWalk(RestWalkCommand command); bool TryReturn(in FittedFootprintSettings settings, out Vector3 travel); void CancelReturn(); } public interface ICheckedCapsuleCenter { Vector3 CheckedCenter { get; } } public interface IFittedWalkOnFootprint { bool WalkableAhead { get; } IStandingRoute FindWalkOnAhead(float skin); } public interface IFittedSurfaceDiagnostics { int RaysHit { get; } float LargestResidual { get; } float WorstRayDegrees { get; } } public enum DiscRayPosition { Centre, Above, Below, Side } public readonly struct DiscRayReading { public readonly DiscRayPosition Position; public readonly bool Leading; public readonly SurfaceRefusal Contact; public readonly float PlaneOffset; public readonly float NormalDegrees; public DiscRayReading(DiscRayPosition position, bool leading, SurfaceRefusal contact, float planeOffset = float.NaN, float normalDegrees = float.NaN) { Position = position; Leading = leading; Contact = contact; PlaneOffset = planeOffset; NormalDegrees = normalDegrees; } } public interface IFittedRayDiagnostics : IFittedSurfaceDiagnostics { ReadOnlySpan<DiscRayReading> Rays { get; } bool HasMeasuredPlane { get; } SurfaceRefusal FitRefusal { get; } } public ref struct Frame { public float Dt { get; internal set; } public double Time { get; internal set; } public Vector3 Position { get; internal set; } public Vector3 Center { get; internal set; } public Vector3 Velocity { get; internal set; } public bool HasPreviousCommand { get; internal set; } public Vector3 PreviousCommand { get; internal set; } public BodyMode PreviousBody { get; internal set; } public bool PreviousCommandFresh { get; internal set; } public bool PreviousStepPending { get; internal set; } public Vector3 Gravity { get; internal set; } public bool OnGround { get; internal set; } public float GroundContactAge { get; internal set; } public Vector3 GroundNormal { get; internal set; } public Vector3 SupportVelocity { get; internal set; } public Vector3 Input { get; internal set; } public Vector3 Facing { get; internal set; } public bool Crouching { get; internal set; } public float RunSpeed { get; internal set; } public MotionBranch Branch { get; internal set; } public bool InSwimDepth { get; internal set; } public bool WaterContactKnown { get; internal set; } public bool InWater { get; internal set; } public bool Swimming { get; internal set; } public Vector3 Wind { get; internal set; } public ReadOnlySpan<Contact> Contacts { get; internal set; } public ReadOnlySpan<WindContribution> WindSources { get; internal set; } } public readonly struct Contact { public Vector3 Normal { get; } public Vector3 SurfaceVelocity { get; } public float MassRatio { get; } public bool Ground { get; } internal Contact(Vector3 normal, Vector3 surfaceVelocity, float massRatio, bool ground) { bool flag = ground; Normal = normal; SurfaceVelocity = surfaceVelocity; MassRatio = massRatio; Ground = flag; } } public readonly struct WindContribution { public string PluginGuid { get; } public string Name { get; } public int Priority { get; } public Vector3 Acceleration { get; } internal WindContribution(string pluginGuid, string name, int priority, Vector3 acceleration) { PluginGuid = pluginGuid; Name = name; Priority = priority; Acceleration = acceleration; } } public delegate Command Step(in Frame frame); public enum BodyMode { EngineGravity, ControllerGravity } public enum FallMode { Vanilla, TrackControllerImpact } public enum MotionPose { Airborne, Swimming, Sliding, Coasting, LowSlide, SupportedSlide } public enum MotionBranch { Walking, Swimming } public enum StartState { Refused, Started, EndedImmediately } public enum Refusal { None, InvalidClaim, PaymentRefused, Outranked, Duplicate, Busy, Shutdown, Blocked, ClaimGate, NotOwner, ServiceUnusable, InCallback } public readonly struct StartResult<TLease> where TLease : class { public StartState State { get; } public TLease Lease { get; } public Refusal Reason { get; } public string Detail { get; } internal StartResult(StartState state, TLease lease, Refusal reason, string detail) { State = state; Lease = lease; Reason = reason; Detail = detail; } } public enum SurfaceRefusal { None, Unavailable, OutOfReach, NoSupport, NotFixed, SupportChanged, DifferentSupportGroup, UncheckedPose, PoseMoved, InvalidDimensions, FaceAngle, LeftBootMissing, RightBootMissing, BootsNotCoplanar, FootDiscontinuity, UprightBlocked, TurnBudget, TurnBlocked, DisplayBlocked, NotWalkable, Wet, NoGroundBelow, NoInwardDirection, NoTop, TopBeyondReach, RimMissing, RimNotWalkable, RimNotCoplanar, LandingOccupied, LiftBlocked, CrossingBlocked, DescentBlocked, WalkOnBlocked, LandingBlocked, RouteStepBlocked, SettleTimedOut, NoRoute, QueryBufferFull, OutsideWallBand, SupportEndsAhead, FitResidual, FitRayAngle } public interface ISurfaceDiagnostics { SurfaceRefusal LastRefusal { get; } } public interface ISurfaceAngles { float FaceDegrees { get; } float LimitDegrees { get; } float LeftOffset { get; } float RightOffset { get; } float BootDegrees { get; } float SweepLimitDegrees { get; } } [Flags] public enum TraversalActions { None = 0, Attack = 1, Block = 2, Dodge = 4, Build = 8, Tool = 0x10, Interact = 0x20 } public enum SurfaceResult { Missing, Obstructed, Clear } public interface ISurfaceFootprint { SurfaceResult Sample(Vector3 travel, Vector3 heading, float reach, float width, float skin, out Vector3 feet, out Vector3 normal, out float separation); } public interface ITraversalInput { bool IsActive { get; } TraversalActions Blocked { get; set; } Vector2 Move { get; } bool TakeJump(); bool TakeRefusal(); float TakePushSpeed(); } public interface IOrientedPresentation { bool IsActive { get; } bool CameraClear { get; } void Place(Vector3 feet, Vector3 normal, Vector3 facing, double expiry); void Clear(); } public interface IStandingFootprint { IStandingRoute FindStandingRoute(float reach, float skin); } public interface IWalkableFootprint : IStandingFootprint { float WalkableNormalY { get; } bool LandingOccupied { get; } IStandingRoute FindWalkOnRoute(float skin); } public interface IStandingRoute { Vector3 Destination { get; } float CrossingHeight { get; } bool Measure(out Vector3 center, out bool grounded); bool ClearStep(Vector3 displacement); } } namespace Volund.Bodies { public enum BodyObstacle { None, Solid, Ward, Zone, Water, Drop, Boat, Player, Structure, Range } public interface IBodyPath { float ShapeSweep(Vector3 direction, float distance); bool Loaded(Vector3 position, float margin); bool Warded(Vector3 position, float margin); float LiquidLevel(Vector3 position); bool DrySupport(Vector3 position, float depth, out float height); BodyObstacle Clearance(Vector3 position, Vector3 landing, float footprint, float clearance, BodyDeparture departure); } public interface IBodyCorridor { void Prepare(Vector3 start, Vector3 end, float margin, float depth); bool TryLandingFloor(Vector3 start, Vector3 end, float radius, float depth, out float floor); } public interface IBodyContactClearance { bool ClearOfPlayersBoatsAndStructures(Vector3 center, Vector3 landing, float footprint, float clearance); } public interface IBodyFallPath { bool PlayerBelow(Vector3 center, float radius); } public readonly struct BodyDeparture { public readonly long Player; public readonly Vector3 PlayerPosition; public readonly Vector3 Origin; public readonly Vector3 Current; public readonly Vector3 Direction; private readonly float? _initialRadius; public BodyDeparture(long player, Vector3 playerPosition, Vector3 origin, Vector3 current, Vector3 direction) : this(player, playerPosition, origin, current, direction, null) { } public BodyDeparture(long player, Vector3 playerPosition, Vector3 origin, Vector3 current, Vector3 direction, float? initialRadius) { _initialRadius = initialRadius; Player = player; PlayerPosition = playerPosition; Origin = origin; Current = current; Direction = direction; } public bool ClearsPlayer(Vector3 closestNow, Vector3 position, Vector3 landing) { if (!_initialRadius.HasValue) { return false; } Vector3 vector = Current - closestNow; float num = vector.Length(); if (num == 0f || num < _initialRadius.Value) { return false; } float num2 = _initialRadius.Value * num; if (Vector3.Dot(position - closestNow, vector) >= num2) { return Vector3.Dot(landing - closestNow, vector) >= num2; } return false; } public bool Allows(long player, Vector3 playerPosition, Vector3 closestAtOrigin, Vector3 closestNow, Vector3 landing, float radius) { return Allows(player, playerPosition, closestAtOrigin, closestNow, landing, radius, Current, 0f); } public bool Allows(long player, Vector3 playerPosition, Vector3 closestAtOrigin, Vector3 closestNow, Vector3 landing, float radius, Vector3 closestOnColumn, float footprint) { if (Player == 0L || player != Player) { return false; } Vector3 vector = Origin - PlayerPosition - (closestAtOrigin - playerPosition); Vector3 vector2 = Current - closestNow; float num = _initialRadius ?? radius; if (!(vector.LengthSquared() < num * num) || !(Vector3.Dot(Direction, vector2) > 0f)) { return false; } if (Vector3.Dot(landing - Current, vector2) >= -0.0001f) { return true; } Vector3 vector3 = Current - closestOnColumn; vector3.Y = 0f; if (vector3.LengthSquared() > footprint * footprint && Vector3.Dot(Direction, vector3) > 0f) { return Vector3.Dot(landing - Current, vector3) >= 0f; } return false; } } public interface IFixedGroundContact { bool SupportsBody { get; } } public interface IFixedContact { bool TryError(out Vector3 displacement); bool Clear(Vector3 step); } }
plugins/Volund/Volund.dll
Decompiled a day 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.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using UnityEngine; using Volund.Bodies; using Volund.Checking; using Volund.Contracts; using Volund.Control; using Volund.Game; using Volund.Registry; using Volund.Registry.Dependencies; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("knowitallking")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.6.0.0")] [assembly: AssemblyInformationalVersion("0.6.0+54c1fc2be67e0bf387d17146f6b8e8bd12e83722")] [assembly: AssemblyProduct("Volund")] [assembly: AssemblyTitle("Volund")] [assembly: InternalsVisibleTo("Volund.Tests")] [assembly: AssemblyVersion("0.6.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [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 Volund { public static class ServiceNames { public const string Growth = "growth"; public const string SurfaceFootprints = "surface-footprints"; public const string OrientedPresentation = "oriented-presentation"; public const string TraversalInput = "traversal-input"; public const string PlayerContacts = "player-contacts"; public const string PlayerSpeed = "player-speed"; public const string PlayerPose = "player-pose"; public const string Motion = "motion"; public const string LooseBodies = "loose-bodies"; public const string Bodies = "bodies"; public const string Health = "health"; public const string Wind = "wind"; public const string TestInput = "test-input"; public const string Items = "items"; public const string EquipCompletion = "equip-completion"; public const string Diagnostics = "diagnostics"; } public enum ServiceState { Unknown, Pending, Available, Degraded, Disabled } public sealed class DependencyFailure { public string EntryId { get; } public bool Required { get; } public string Expected { get; } public string Found { get; } public string Detail { get; } public string Outcome { get; } public string DeclaredAt { get; } internal DependencyFailure(string entryId, bool required, string expected, string found, string detail, string outcome, string declaredAt) { EntryId = entryId; Required = required; Expected = expected; Found = found; Detail = detail; Outcome = outcome; DeclaredAt = declaredAt; } public override string ToString() { return EntryId + " " + Outcome + ": " + Detail; } } public sealed class ServiceStatus { public string Service { get; } public ServiceState State { get; } public bool IsUsable { get { if (State != ServiceState.Available) { return State == ServiceState.Degraded; } return true; } } public IReadOnlyList<DependencyFailure> Failures { get; } public string Summary { get; } internal ServiceStatus(string service, ServiceState state, IReadOnlyList<DependencyFailure> failures, string summary) { Service = service; State = state; Failures = failures ?? Array.Empty<DependencyFailure>(); Summary = summary; } public override string ToString() { return Summary; } } public sealed class ServiceUnavailableException : InvalidOperationException { public string Service => Status.Service; public ServiceStatus Status { get; } internal ServiceUnavailableException(ServiceStatus status) : base($"Volund service '{status.Service}' is not usable ({status.State}). {status.Summary}") { Status = status; } } public static class Api { public const string PluginGuid = "knowitallking.volund"; public const string PluginVersion = "0.6.0"; public static Version Version => typeof(Api).Assembly.GetName().Version; public static IReadOnlyList<string> Services => ServiceStates.Names; public static string ReportPath => ServiceStates.ReportPath; public static event Action<ServiceStatus> StatusChanged { add { ServiceStates.Changed += value; } remove { ServiceStates.Changed -= value; } } public static ServiceState GetState(string service) { return ServiceStates.Get(service).State; } public static ServiceStatus GetStatus(string service) { return ServiceStates.Get(service); } public static bool IsUsable(string service) { return ServiceStates.Get(service).IsUsable; } public static void Require(string service) { ServiceStatus serviceStatus = ServiceStates.Get(service); if (!serviceStatus.IsUsable) { throw new ServiceUnavailableException(serviceStatus); } } } internal static class ServiceStates { private static readonly Dictionary<string, ServiceStatus> s_states; private static readonly object s_lock; private static ConsumerAction<ServiceStatus>[] s_handlers; private static readonly Queue<ServiceStatus> s_pending; internal static Action<string> HandlerError; internal static string ReportPath { get; set; } internal static IReadOnlyList<string> Names { get { lock (s_lock) { return s_states.Keys.ToList(); } } } internal static event Action<ServiceStatus> Changed { add { if (value == null) { return; } lock (s_lock) { Delegate[] invocationList = value.GetInvocationList(); ConsumerAction<ServiceStatus>[] array = new ConsumerAction<ServiceStatus>[s_handlers.Length + invocationList.Length]; Array.Copy(s_handlers, array, s_handlers.Length); for (int i = 0; i < invocationList.Length; i++) { array[s_handlers.Length + i] = new ConsumerAction<ServiceStatus>((Action<ServiceStatus>)invocationList[i]); } s_handlers = array; } } remove { if (value == null) { return; } lock (s_lock) { Delegate[] invocationList = value.GetInvocationList(); foreach (Delegate obj in invocationList) { for (int num = s_handlers.Length - 1; num >= 0; num--) { if (s_handlers[num].Wraps((Action<ServiceStatus>)obj)) { ConsumerAction<ServiceStatus>[] destinationArray = new ConsumerAction<ServiceStatus>[s_handlers.Length - 1]; Array.Copy(s_handlers, 0, destinationArray, 0, num); Array.Copy(s_handlers, num + 1, destinationArray, num, s_handlers.Length - num - 1); s_handlers = destinationArray; break; } } } } } } static ServiceStates() { s_states = new Dictionary<string, ServiceStatus>(); s_lock = new object(); s_handlers = new ConsumerAction<ServiceStatus>[0]; s_pending = new Queue<ServiceStatus>(); Reset(ServiceCatalog.All.Select((Service s) => s.Id)); } internal static void Reset(IEnumerable<string> services) { lock (s_lock) { s_pending.Clear(); s_states.Clear(); foreach (string service in services) { s_states[service] = new ServiceStatus(service, ServiceState.Pending, null, service + ": pending; the self-check has not finished."); } } } internal static ServiceStatus Get(string service) { lock (s_lock) { if (service != null && s_states.TryGetValue(service, out var value)) { return value; } } return new ServiceStatus(service ?? "(null)", ServiceState.Unknown, null, "'" + service + "' is not a Volund service."); } internal static void Publish(IEnumerable<ServiceStatus> statuses) { Publish(statuses, queue: false); } private static void Publish(IEnumerable<ServiceStatus> statuses, bool queue) { List<ServiceStatus> list = new List<ServiceStatus>(); lock (s_lock) { foreach (ServiceStatus status in statuses) { s_states.TryGetValue(status.Service, out var value); s_states[status.Service] = status; if (value == null || value.State != status.State || value.Summary != status.Summary) { list.Add(status); } } } if (queue) { lock (s_lock) { foreach (ServiceStatus item in list) { s_pending.Enqueue(item); } return; } } using List<ServiceStatus>.Enumerator enumerator2 = list.GetEnumerator(); while (enumerator2.MoveNext() && Raise(enumerator2.Current)) { } } internal static void Deliver() { while (!Callbacks.Guard.ShutdownPending) { ServiceStatus s; lock (s_lock) { if (s_pending.Count == 0) { break; } s = s_pending.Dequeue(); } if (!Raise(s)) { break; } } } internal static void Fault(string service, string what, Exception e) { ServiceStatus serviceStatus = Get(service); if (serviceStatus.State != ServiceState.Unknown) { List<DependencyFailure> list = new List<DependencyFailure>(serviceStatus.Failures); list.Add(new DependencyFailure("fault", required: true, "no exception", e?.GetType().Name, what + " threw " + e?.GetType().Name + ": " + e?.Message, "faulted", null)); List<DependencyFailure> failures = list; Publish(new ServiceStatus[1] { new ServiceStatus(service, ServiceState.Disabled, failures, service + ": disabled after a fault in " + what + " (" + e?.GetType().Name + ": " + e?.Message + ").") }, queue: true); } } private static bool Raise(ServiceStatus s) { ConsumerAction<ServiceStatus>[] array = s_handlers; foreach (ConsumerAction<ServiceStatus> consumerAction in array) { string error; bool flag = consumerAction.Call<object>(Callbacks.Guard, s, null, null, out error); if (error != null) { try { HandlerError?.Invoke("A StatusChanged handler (" + consumerAction.Describe() + ") threw " + error); } catch { } } if (!flag) { return false; } } return true; } } public readonly struct PlayerBodyContact { public object Player { get; } public object Other { get; } public float RelativeSpeed { get; } internal PlayerBodyContact(object player, object other, float speed) { Player = player; Other = other; RelativeSpeed = speed; } } public enum HealScaling { Respect, Exact, AllowDiversion } public enum DamageStage { BeforeResistance, Final, FallBeforeShields } public readonly struct DamageCause { public readonly object Victim; public readonly object Attacker; public readonly string Kind; public readonly short ToolTier; public readonly bool HasAttacker; public readonly Guid HitId; public readonly string Marker; public readonly bool IsStatusTick; public bool IsFall => Kind == "Fall"; public bool IsEnvironmental { get { if (!HasAttacker) { return !IsStatusTick; } return false; } } public DamageCause(object victim, object attacker, string kind, short toolTier, bool hasAttacker, Guid hitId = default(Guid), string marker = null, bool statusTick = false) { Victim = victim; Attacker = attacker; Kind = kind; ToolTier = toolTier; HasAttacker = hasAttacker; HitId = hitId; Marker = marker; IsStatusTick = statusTick; } } public readonly struct DamageChange { internal readonly float Remaining; internal readonly bool Changes; internal readonly ConsumerFunc<bool> Payment; internal readonly ConsumerAction<bool> Settlement; internal readonly EquipmentEdit Equipment; public static DamageChange Keep => default(DamageChange); private DamageChange(float remaining, Func<bool> pay, Action<bool> settled = null, EquipmentEdit equipment = null) { Settlement = ((settled == null) ? null : new ConsumerAction<bool>(settled)); Equipment = equipment; Remaining = remaining; Changes = true; Payment = ((pay == null) ? null : new ConsumerFunc<bool>(pay)); } public static DamageChange PaidByEquipment(float remaining, EquipmentEdit edit) { return new DamageChange(remaining, null, null, edit ?? throw new ArgumentNullException("edit")); } public static DamageChange Replace(float amount) { return new DamageChange(amount, null); } public static DamageChange Paid(float remaining, Func<bool> pay, Action<bool> settled = null) { return new DamageChange(remaining, pay ?? throw new ArgumentNullException("pay"), settled); } } public enum ItemResult { Ok, Absent, UnknownVersion, Unusable, Stale, ForeignOwner, DifferentInventory, Equipped, InvalidCount, Full, AlreadyCommitted, Invalid, Busy, Refused } public enum UpgradePolicy { Carry, Refuse, Drop } public sealed class ItemRecord : IDisposable { internal readonly ItemSession Session; internal readonly string Key; internal readonly string Prefix; internal bool Active = true; internal UpgradePolicy Upgrade; internal readonly HashSet<string> OwnedKeys = new HashSet<string>(StringComparer.Ordinal); private readonly HashSet<string> _warnings = new HashSet<string>(); internal readonly ConsumerFunc<string, string, bool> Merge; internal readonly ConsumerFunc<string, int, bool> Split; internal readonly ConsumerFunc<string, string, bool> Equip; internal readonly ConsumerAction<ItemEvent> Events; internal bool Failed(string callback, string error) { if (error == null) { return false; } if (_warnings.Add(callback)) { Callbacks.Warn?.Invoke(Key + " " + callback + ": " + error); } return true; } internal ItemRecord(ItemSession session, string key, int version, Func<string, string, bool> merge, Func<string, int, bool> split, Func<string, string, bool> equip, Action<ItemEvent> events) { Session = session; Key = key; Prefix = version.ToString(CultureInfo.InvariantCulture) + ":"; if (merge != null) { Merge = new ConsumerFunc<string, string, bool>(merge); } if (split != null) { Split = new ConsumerFunc<string, int, bool>(split); } if (equip != null) { Equip = new ConsumerFunc<string, string, bool>(equip); } if (events != null) { Events = new ConsumerAction<ItemEvent>(events); } } internal ItemResult Decode(Dictionary<string, string> data, out string value) { value = null; if (!Session.Ready || !Active) { return ItemResult.Unusable; } if (!data.TryGetValue(Key, out var value2)) { return ItemResult.Absent; } if (value2 == null || !value2.StartsWith(Prefix, StringComparison.Ordinal)) { return ItemResult.UnknownVersion; } value = value2.Substring(Prefix.Length); return ItemResult.Ok; } public void Dispose() { Session.Guard.Defer(delegate { if (Active) { Active = false; Session.ReleaseFixedStats(this); Session.Records.Remove(Key); Session.RegistrationRevision++; } }); } } public enum ItemEventKind { Entered, Left, Equipped, Unequipped, Split, Merged } public readonly struct ItemEvent { public Guid Identity { get; } public ItemEventKind Kind { get; } public string Value { get; } public string Slot { get; } internal ItemEvent(ItemEventKind kind, Guid identity, string value, string slot) { Kind = kind; Identity = identity; Value = value; Slot = slot; } } public sealed class ItemRef { internal ItemBag Bag; internal object Item; internal object Revision; internal bool WasEquipped; internal Dictionary<string, string> Data; internal ItemRecord Schema; public Guid Identity { get; internal set; } public int Count { get; internal set; } public string Value { get; internal set; } internal ItemRef() { } } public sealed class ReturnedItem { internal ItemRecord Schema; internal object Template; public bool RequireOwnSlot { get; set; } internal ReturnedItem() { } } internal abstract class ItemBag { internal abstract bool Owned { get; } internal abstract object Identity { get; } internal static bool InBounds(int x, int y, int width, int height) { if (x >= 0 && x < width && y >= 0) { return y < height; } return false; } internal abstract bool Contains(object item); internal virtual object Revision(object item) { return null; } internal abstract int Count(object item); internal abstract bool Equipped(object item); internal abstract Dictionary<string, string> Data(object item); internal virtual void PrepareCommit(bool inserting) { } internal abstract void SetCount(object item, int count); internal abstract void Changed(); internal abstract IEnumerable<object> Candidates(object source); internal abstract int Room(object target); internal abstract object PrepareReturn(object template, object freed); internal abstract void Insert(object prepared); } public sealed class EquipmentEdit { internal readonly ItemRef[] Items; internal readonly string[] Values; internal bool Published; public EquipmentEdit(ItemRef[] items, string[] values) { if (items == null || values == null || items.Length == 0 || items.Length != values.Length) { throw new ArgumentException("Each equipment snapshot needs one replacement payload."); } Items = (ItemRef[])items.Clone(); Values = (string[])values.Clone(); } public ItemResult Commit() { return Items[0]?.Schema.Session.CommitEquipment(this) ?? ItemResult.Invalid; } } public sealed class ItemSession { private sealed class Identity { internal Guid Id = Guid.NewGuid(); } internal interface IHealth { bool Usable { get; } void Fault(Exception error); } internal int RegistrationRevision; internal readonly Dictionary<string, ItemRecord> Records = new Dictionary<string, ItemRecord>(); internal readonly CallbackGuard Guard; private readonly int _thread = Thread.CurrentThread.ManagedThreadId; private readonly HashSet<Guid> _done = new HashSet<Guid>(); private readonly ConditionalWeakTable<object, Identity> _identities = new ConditionalWeakTable<object, Identity>(); internal IHealth Health; internal bool Enabled; private readonly Dictionary<string, (ItemRecord schema, float weight, float armour)> _fixedStats = new Dictionary<string, (ItemRecord, float, float)>(StringComparer.Ordinal); internal bool FixedStatsEnabled; internal bool Ready { get { if (Thread.CurrentThread.ManagedThreadId == _thread && Enabled && (Health == null || Health.Usable)) { return !Guard.ShutdownPending; } return false; } } internal bool HasFixedStats { get { if (_fixedStats.Count != 0 && Ready) { return FixedStatsEnabled; } return false; } } internal Guid Identify(object item) { return _identities.GetOrCreateValue(item).Id; } internal void Follow(object from, object to) { _identities.GetOrCreateValue(to).Id = Identify(from); } internal ItemSession(CallbackGuard guard) { Guard = guard; } public ItemResult Register(Source source, int version, out ItemRecord schema, Func<string, string, bool> merge, Func<string, int, bool> split, Func<string, string, bool> equip, Action<ItemEvent> events) { return Register(source, version, out schema, merge, split, equip, events, null, UpgradePolicy.Carry); } public ItemResult Register(Source source, int version, out ItemRecord schema, Func<string, string, bool> merge = null, Func<string, int, bool> split = null, Func<string, string, bool> equip = null, Action<ItemEvent> events = null, string[] ownedKeys = null, UpgradePolicy upgrade = UpgradePolicy.Carry) { schema = null; if (!Ready) { return ItemResult.Unusable; } if (Guard.InCallback) { return ItemResult.Busy; } if (!source.IsValid || version < 1 || !Enum.IsDefined(typeof(UpgradePolicy), upgrade)) { return ItemResult.Invalid; } string key = "volund.item/" + Uri.EscapeDataString(source.PluginGuid) + "/" + Uri.EscapeDataString(source.Name); if (Records.ContainsKey(key)) { return ItemResult.Invalid; } schema = new ItemRecord(this, key, version, merge, split, equip, events); schema.Upgrade = upgrade; if (ownedKeys != null) { foreach (string owned in ownedKeys) { if (string.IsNullOrEmpty(owned) || owned.StartsWith("volund.item/", StringComparison.Ordinal) || Records.Values.Any((ItemRecord r) => r.OwnedKeys.Contains(owned))) { schema = null; return ItemResult.Invalid; } schema.OwnedKeys.Add(owned); } } Records.Add(key, schema); RegistrationRevision++; return ItemResult.Ok; } internal void ReleaseFixedStats(ItemRecord owner) { string[] array = (from p in _fixedStats where p.Value.schema == owner select p.Key).ToArray(); foreach (string key in array) { _fixedStats.Remove(key); } } public ItemResult SetFixedStats(ItemRecord schema, string prefab, float weight, float armour) { if (!FixedStatsEnabled || !Ready || schema?.Session != this || !schema.Active) { return ItemResult.Unusable; } if (Guard.InCallback) { return ItemResult.Busy; } if (string.IsNullOrEmpty(prefab) || !float.IsFinite(weight) || !float.IsFinite(armour) || weight < 0f || armour < 0f) { return ItemResult.Invalid; } if (_fixedStats.TryGetValue(prefab, out (ItemRecord, float, float) value) && value.Item1.Active && value.Item1 != schema) { return ItemResult.Refused; } _fixedStats[prefab] = (schema, weight, armour); return ItemResult.Ok; } internal bool TryFixedStats(string prefab, out float weight, out float armour) { weight = (armour = 0f); if (!HasFixedStats || prefab == null || !_fixedStats.TryGetValue(prefab, out (ItemRecord, float, float) value) || !value.Item1.Active) { return false; } weight = value.Item2; armour = value.Item3; return true; } internal ItemResult Capture(ItemBag bag, object item, ItemRecord schema, out ItemRef snapshot) { snapshot = null; if (!Ready || schema?.Session != this || !schema.Active) { return ItemResult.Unusable; } if (item == null || bag == null || !bag.Contains(item)) { return ItemResult.Stale; } Dictionary<string, string> data = new Dictionary<string, string>(bag.Data(item)); string value; ItemResult result = schema.Decode(data, out value); snapshot = new ItemRef { Bag = bag, Item = item, Schema = schema, Data = data, Revision = bag.Revision(item), WasEquipped = bag.Equipped(item), Identity = Identify(item), Count = bag.Count(item), Value = value }; return result; } internal ItemResult Prepare(ItemRecord schema, object detached, Dictionary<string, string> data, string value, out ReturnedItem output) { output = null; if (!Ready || schema?.Session != this || !schema.Active) { return ItemResult.Unusable; } if (schema.Decode(data, out var _) == ItemResult.UnknownVersion) { return ItemResult.UnknownVersion; } if (value == null) { data.Remove(schema.Key); } else { data[schema.Key] = schema.Prefix + value; } output = new ReturnedItem { Template = detached, Schema = schema }; return ItemResult.Ok; } private ItemResult Check(ItemRef item, bool allowEquipped = false) { if (!Ready || item?.Schema.Session != this || !item.Schema.Active) { return ItemResult.Unusable; } ItemBag bag = item.Bag; if (!bag.Owned) { return ItemResult.ForeignOwner; } if (!bag.Contains(item.Item) || bag.Count(item.Item) != item.Count || !object.Equals(bag.Revision(item.Item), item.Revision) || !Equal(bag.Data(item.Item), item.Data)) { return ItemResult.Stale; } bool flag = bag.Equipped(item.Item); if (flag && !allowEquipped) { return ItemResult.Equipped; } if (flag != item.WasEquipped) { return ItemResult.Stale; } if (item.Schema.Decode(item.Data, out var _) != ItemResult.UnknownVersion) { return ItemResult.Ok; } return ItemResult.UnknownVersion; } internal static bool Equal(Dictionary<string, string> a, Dictionary<string, string> b) { string value; if (a.Count == b.Count) { return a.All((KeyValuePair<string, string> p) => b.TryGetValue(p.Key, out value) && p.Value == value); } return false; } public ItemResult Commit(Guid operation, ItemRef first, string value, ItemRef second, string secondValue, int consume, ReturnedItem returnTemplate, bool allowEquippedDestination) { return Commit(operation, first, value, second, secondValue, consume, returnTemplate, allowEquippedDestination, null, null); } public ItemResult Commit(Guid operation, ItemRef first, string value, ItemRef second = null, string secondValue = null, int consume = 0, ReturnedItem returnTemplate = null, bool allowEquippedDestination = false, Dictionary<string, string> firstKeys = null, Dictionary<string, string> secondKeys = null) { if (!Ready) { return ItemResult.Unusable; } try { return CommitCore(operation, first, value, second, secondValue, consume, returnTemplate, allowEquippedDestination, firstKeys, secondKeys); } catch (Exception error) { Health?.Fault(error); return ItemResult.Unusable; } } private ItemResult CommitCore(Guid operation, ItemRef first, string value, ItemRef second, string secondValue, int consume, ReturnedItem returnTemplate, bool allowEquippedDestination, Dictionary<string, string> firstKeys, Dictionary<string, string> secondKeys) { if (Guard.InCallback) { return ItemResult.Busy; } if (operation == Guid.Empty || first == null) { return ItemResult.Invalid; } if (_done.Contains(operation)) { return ItemResult.AlreadyCommitted; } ItemResult itemResult = Check(first, allowEquippedDestination); if (itemResult != ItemResult.Ok) { return itemResult; } if (consume < 0 || consume > (second?.Count ?? 0)) { return ItemResult.InvalidCount; } if (second != null) { if (first.Bag.Identity != second.Bag.Identity) { return ItemResult.DifferentInventory; } if (first.Item == second.Item) { return ItemResult.Invalid; } itemResult = Check(second); if (itemResult != ItemResult.Ok) { return itemResult; } } if (consume > 0 && second.Data.Keys.Any((string key) => key != second.Schema.Key && !second.Schema.OwnedKeys.Contains(key))) { return ItemResult.Refused; } if (second != null && consume > 0 && consume < second.Count) { if (!Allow(second.Data, null, consume)) { return ItemResult.Refused; } itemResult = Check(first, allowEquippedDestination); if (itemResult != ItemResult.Ok) { return itemResult; } itemResult = Check(second); if (itemResult != ItemResult.Ok) { return itemResult; } } KeyValuePair<string, string>[] array = firstKeys?.ToArray(); KeyValuePair<string, string>[] array2 = secondKeys?.ToArray(); if ((array != null && array.Any((KeyValuePair<string, string> p) => !first.Schema.OwnedKeys.Contains(p.Key))) || (array2 != null && (second == null || array2.Any((KeyValuePair<string, string> p) => !second.Schema.OwnedKeys.Contains(p.Key))))) { return ItemResult.Refused; } object obj = null; object obj2 = null; int num = 0; Dictionary<string, string> b = null; object objB = null; if (returnTemplate != null) { if (returnTemplate.Schema.Session != this || !returnTemplate.Schema.Active) { return ItemResult.Unusable; } foreach (object item in returnTemplate.RequireOwnSlot ? Enumerable.Empty<object>() : first.Bag.Candidates(returnTemplate.Template)) { bool flag = item == second?.Item; if ((flag && consume == second.Count) || first.Bag.Room(item) + (flag ? consume : 0) < 1) { continue; } Dictionary<string, string> dictionary = new Dictionary<string, string>(first.Bag.Data(item)); int num2 = first.Bag.Count(item); object obj3 = first.Bag.Revision(item); Dictionary<string, string> dictionary2 = dictionary; if (flag || item == first.Item) { dictionary2 = new Dictionary<string, string>(dictionary); ItemRef itemRef = (flag ? second : first); string text = (flag ? secondValue : value); Publish(dictionary2, itemRef.Schema.Key, (text == null) ? null : (itemRef.Schema.Prefix + text)); KeyValuePair<string, string>[] array3 = (flag ? array2 : array); if (array3 != null) { KeyValuePair<string, string>[] array4 = array3; for (int num3 = 0; num3 < array4.Length; num3++) { KeyValuePair<string, string> keyValuePair = array4[num3]; Publish(dictionary2, keyValuePair.Key, keyValuePair.Value); } } } if (Allow(first.Bag.Data(returnTemplate.Template), dictionary2, 1)) { b = dictionary; objB = obj3; obj2 = item; num = num2; break; } } if (obj2 == null) { obj = first.Bag.PrepareReturn(returnTemplate.Template, (second != null && consume == second.Count) ? second.Item : null); } if (obj == null && obj2 == null) { return ItemResult.Full; } } Dictionary<string, string> dictionary3 = first.Bag.Data(first.Item); Dictionary<string, string> dictionary4 = ((second == null) ? null : first.Bag.Data(second.Item)); string wire; string wire2; checked { if (array != null) { dictionary3.EnsureCapacity(dictionary3.Count + array.Length + 1); } if (array2 != null) { dictionary4.EnsureCapacity(dictionary4.Count + array2.Length + 1); } wire = Encode(first, dictionary3, value); wire2 = ((second == null) ? null : Encode(second, dictionary4, secondValue)); first.Bag.PrepareCommit(obj != null); itemResult = Check(first, allowEquippedDestination); if (itemResult != ItemResult.Ok) { return itemResult; } if (second != null && (itemResult = Check(second)) != ItemResult.Ok) { return itemResult; } } if (obj2 != null && (!first.Bag.Contains(obj2) || first.Bag.Room(obj2) + ((obj2 == second?.Item) ? consume : 0) < 1 || first.Bag.Count(obj2) != num || !object.Equals(first.Bag.Revision(obj2), objB) || !Equal(first.Bag.Data(obj2), b))) { return ItemResult.Stale; } _done.Add(operation); Publish(dictionary3, first.Schema.Key, wire); if (second != null) { Publish(dictionary4, second.Schema.Key, wire2); if (consume > 0) { first.Bag.SetCount(second.Item, second.Count - consume); } } if (array != null) { KeyValuePair<string, string>[] array4 = array; for (int num3 = 0; num3 < array4.Length; num3++) { KeyValuePair<string, string> keyValuePair2 = array4[num3]; Publish(dictionary3, keyValuePair2.Key, keyValuePair2.Value); } } if (array2 != null) { KeyValuePair<string, string>[] array4 = array2; for (int num3 = 0; num3 < array4.Length; num3++) { KeyValuePair<string, string> keyValuePair3 = array4[num3]; Publish(dictionary4, keyValuePair3.Key, keyValuePair3.Value); } } if (obj2 != null) { first.Bag.SetCount(obj2, num - ((obj2 == second?.Item) ? consume : 0) + 1); } if (obj != null) { first.Bag.Insert(obj); } try { first.Bag.Changed(); } catch (Exception error) { Health?.Fault(error); } return ItemResult.Ok; } internal ItemResult CommitEquipment(EquipmentEdit edit) { if (!Ready) { return ItemResult.Unusable; } if (Guard.InCallback) { return ItemResult.Busy; } if (edit.Published) { return ItemResult.AlreadyCommitted; } try { ItemBag bag = edit.Items[0].Bag; Dictionary<string, string>[] array = new Dictionary<string, string>[edit.Items.Length]; string[] array2 = new string[array.Length]; for (int i = 0; i < array.Length; i++) { ItemRef itemRef = edit.Items[i]; if (itemRef == null || itemRef.Schema.Session != this || !itemRef.WasEquipped) { return ItemResult.Invalid; } if (itemRef.Bag.Identity != bag.Identity) { return ItemResult.DifferentInventory; } for (int j = 0; j < i; j++) { if (edit.Items[j].Item == itemRef.Item) { return ItemResult.Invalid; } } ItemResult itemResult = Check(itemRef, allowEquipped: true); if (itemResult != ItemResult.Ok) { return itemResult; } array[i] = bag.Data(itemRef.Item); array2[i] = Encode(itemRef, array[i], edit.Values[i]); } bag.PrepareCommit(inserting: false); ItemRef[] items = edit.Items; foreach (ItemRef item in items) { ItemResult itemResult2 = Check(item, allowEquipped: true); if (itemResult2 != ItemResult.Ok) { return itemResult2; } } for (int l = 0; l < array.Length; l++) { Publish(array[l], edit.Items[l].Schema.Key, array2[l]); } edit.Published = true; try { bag.Changed(); } catch (Exception error) { Health?.Fault(error); } return ItemResult.Ok; } catch (Exception error2) { Health?.Fault(error2); return ItemResult.Unusable; } } private static string Encode(ItemRef item, Dictionary<string, string> data, string value) { if (value == null) { return null; } if (!data.ContainsKey(item.Schema.Key)) { data.EnsureCapacity(checked(data.Count + 1)); } return item.Schema.Prefix + value; } private static void Publish(Dictionary<string, string> data, string key, string wire) { if (wire == null) { data.Remove(key); } else { data[key] = wire; } } internal bool MayEquip(Dictionary<string, string> data, string slot, Func<ItemRecord, bool> stillOwned) { if (!Ready) { return false; } ItemRecord[] array = Records.Values.ToArray(); foreach (ItemRecord itemRecord in array) { if (itemRecord.Equip != null && itemRecord.Decode(data, out var value) == ItemResult.Ok) { if (Guard.InCallback) { return false; } bool result; string error; bool flag = itemRecord.Equip.Call(Guard, value, slot, stillOwned, itemRecord, out result, out error); if (itemRecord.Failed("equip", error)) { return false; } if (!flag || !itemRecord.Active || !result) { return false; } } } return true; } internal void Notify(ItemEventKind kind, object item, Dictionary<string, string> data, string slot) { if (!Ready || Guard.InCallback) { return; } ItemRecord[] array = Records.Values.ToArray(); foreach (ItemRecord itemRecord in array) { if (itemRecord.Events != null && itemRecord.Decode(data, out var value) == ItemResult.Ok) { ItemEvent arg = new ItemEvent(kind, Identify(item), value, slot); string error; bool num = itemRecord.Events.Call(Guard, arg, (ItemRecord s) => s.Active && s.Session.Ready, itemRecord, out error); itemRecord.Failed("event", error); if (!num) { break; } } } } internal bool UpgradeData(Dictionary<string, string> source, out Dictionary<string, string> carried) { carried = new Dictionary<string, string>(); foreach (KeyValuePair<string, string> item in source) { if (!item.Key.StartsWith("volund.item/", StringComparison.Ordinal)) { continue; } if (Records.TryGetValue(item.Key, out var value)) { if (value.Upgrade == UpgradePolicy.Refuse) { return false; } if (value.Upgrade == UpgradePolicy.Drop && value.Decode(source, out var _) == ItemResult.Ok) { continue; } foreach (string ownedKey in value.OwnedKeys) { if (source.TryGetValue(ownedKey, out var value3)) { carried[ownedKey] = value3; } } } carried[item.Key] = item.Value; } return true; } internal static bool WorldMerge(Dictionary<string, string> from, Dictionary<string, string> to) { if (from.Keys.Any(ManagedKey) || to.Keys.Any(ManagedKey)) { return Equal(from, to); } return true; } private static bool ManagedKey(string key) { return key.StartsWith("volund.item/", StringComparison.Ordinal); } internal bool Allow(Dictionary<string, string> from, Dictionary<string, string> to, int count) { if (!Ready) { return false; } Dictionary<string, string>.KeyCollection keys = from.Keys; IEnumerable<string> enumerable = to?.Keys; string[] source = keys.Concat(enumerable ?? Enumerable.Empty<string>()).Distinct().ToArray(); if (!source.Any(ManagedKey)) { return true; } if (to != null && source.Any((string k) => !ManagedKey(k) && (!from.TryGetValue(k, out var value6) || !to.TryGetValue(k, out var value7) || value6 != value7))) { return false; } foreach (string item in source.Where(ManagedKey)) { if (Guard.InCallback) { return false; } from.TryGetValue(item, out var value); string value2 = null; to?.TryGetValue(item, out value2); Records.TryGetValue(item, out var value3); if (to != null && value == value2 && value3?.Merge == null) { continue; } if (value3 == null || value3.Decode(from, out var value4) == ItemResult.UnknownVersion) { if (to != null && value != value2) { return false; } continue; } bool flag; bool result; string error; if (to == null) { if (value3.Split == null) { continue; } flag = value3.Split.Call(Guard, value4, count, (ItemRecord s) => s.Active, value3, out result, out error); } else { if (value3.Decode(to, out var value5) == ItemResult.UnknownVersion || value3.Merge == null) { return false; } flag = value3.Merge.Call(Guard, value4, value5, (ItemRecord s) => s.Active, value3, out result, out error); } if (value3.Failed((to == null) ? "split" : "merge", error) || !flag || !result) { return false; } } return true; } } public readonly struct LethalHit { public Guid HitId { get; } public string Kind { get; } public string AttackerId { get; } public short ToolTier { get; } public string Marker { get; } private LethalHit(Guid id, string kind, string attacker, short tier, string marker) { HitId = id; Kind = kind; AttackerId = attacker; ToolTier = tier; Marker = marker; } internal static bool TryRead(string value, out LethalHit hit) { hit = default(LethalHit); if (string.IsNullOrEmpty(value)) { return false; } string[] array = value.Split(new char[1] { '|' }, 5); if (array.Length != 5 || !Guid.TryParseExact(array[0], "N", out var result) || !short.TryParse(array[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2)) { return false; } hit = new LethalHit(result, array[1], array[2], result2, array[4]); return true; } } public enum MotionEnd { Released, Preempted, Blocked, OwnershipLost, WorldLeft, Faulted } public enum BodyMode { EngineGravity, ControllerGravity } public enum FallMode { Vanilla, TrackControllerImpact } public enum MotionPose { Airborne, Swimming, Sliding, Coasting, LowSlide, SupportedSlide } public enum MotionBranch { Walking, Swimming } internal sealed class PickupPlan<T> where T : class { private readonly Queue<(T Target, int Units)> _allocations = new Queue<(T, int)>(); private T _current; private int _left; internal bool Fits { get; private set; } internal PickupPlan(int count, IEnumerable<T> candidates, Func<T, int> space, Func<T, bool> accepts, int emptyRoom) { foreach (T candidate in candidates) { int num = Math.Min(count, space(candidate)); if (num > 0 && accepts(candidate)) { _allocations.Enqueue((candidate, num)); count -= num; if (count == 0) { break; } } } Fits = count <= emptyRoom; } internal T Next() { if (_left == 0) { if (_allocations.Count == 0) { return null; } (_current, _left) = _allocations.Dequeue(); } _left--; return _current; } } public enum HoldEnd { Released, PlayerChanged, ServiceFault, Shutdown } public readonly struct Source : IEquatable<Source> { public string PluginGuid { get; } public string Name { get; } public int Priority { get; } public bool IsValid { get { if (!string.IsNullOrEmpty(PluginGuid)) { return !string.IsNullOrEmpty(Name); } return false; } } public Source(string pluginGuid, string name, int priority = 0) { if (string.IsNullOrEmpty(pluginGuid)) { throw new ArgumentException("A source needs the registering plugin's GUID.", "pluginGuid"); } if (string.IsNullOrEmpty(name)) { throw new ArgumentException("A source needs a local name.", "name"); } PluginGuid = pluginGuid; Name = name; Priority = priority; } public static int CompareRank(Source a, Source b) { if (a.SameKey(b)) { return 0; } if (a.Priority != b.Priority) { if (a.Priority <= b.Priority) { return 1; } return -1; } int num = string.CompareOrdinal(a.PluginGuid, b.PluginGuid); if (num != 0) { return num; } return string.CompareOrdinal(a.Name, b.Name); } public bool SameKey(Source other) { if (string.Equals(PluginGuid, other.PluginGuid, StringComparison.Ordinal)) { return string.Equals(Name, other.Name, StringComparison.Ordinal); } return false; } public bool Equals(Source other) { if (SameKey(other)) { return Priority == other.Priority; } return false; } public override bool Equals(object obj) { if (obj is Source other) { return Equals(other); } return false; } public override int GetHashCode() { return ((PluginGuid?.GetHashCode() ?? 0) * 397) ^ (Name?.GetHashCode() ?? 0) ^ Priority; } public override string ToString() { return $"{PluginGuid}/{Name} (priority {Priority})"; } } public enum HealthSubmission { Unavailable, Refused, Submitted } public static class Health { private delegate string FormatId(ref ZDOID id); private delegate float TypedTotal(ref DamageTypes damage); private delegate void Scale(ref DamageTypes damage, float factor); private sealed class HealRequest { internal Character Target; internal Source Cause; internal float Amount; internal HealScaling Scaling; internal bool Used; internal ConsumerFunc<float, Source, bool> Payment; } private delegate bool IsCinematicPlaying(); private static bool _installed; private const string DeathKey = "volund.health.death.v1"; private static readonly DamageRules Rules = new DamageRules(Callbacks.Guard, VolundPlugin.Warn); private static readonly GameField<Character, ZNetView> View = Bind.Field<Character, ZNetView>(MotionDependencies.NView); private static readonly GameMethod<Func<ZNetView, bool>> Valid = Bind.Method<Func<ZNetView, bool>>(MotionDependencies.ZNetViewIsValid); private static readonly GameMethod<Func<ZNetView, bool>> Owner = Bind.Method<Func<ZNetView, bool>>(MotionDependencies.ZNetViewIsOwner); private static readonly GameMethod<Func<Character, bool>> Dead = Bind.Method<Func<Character, bool>>(MotionDependencies.IsDead); private static readonly GameMethod<Func<Character, float>> Hp = Bind.Method<Func<Character, float>>(HealthDependencies.HealthValue); private static readonly GameMethod<Action<Character, float, bool>> Heal = Bind.Method<Action<Character, float, bool>>(HealthDependencies.Heal); private static readonly GameMethod<Action<Character, HitData, bool, bool, DamageModifier>> Apply = Bind.Method<Action<Character, HitData, bool, bool, DamageModifier>>(HealthDependencies.Apply); private static readonly GameField<HitData, HitType> Kind = Bind.Field<HitData, HitType>(HealthDependencies.Kind); private static readonly GameField<HitData, short> Tier = Bind.Field<HitData, short>(HealthDependencies.Tier); private static readonly GameField<HitData, ZDOID> AttackerId = Bind.Field<HitData, ZDOID>(HealthDependencies.AttackerId); private static readonly GameMethod<Func<HitData, Character>> Attacker = Bind.Method<Func<HitData, Character>>(HealthDependencies.Attacker); private static readonly GameMethod<Func<HitData, bool>> HaveAttacker = Bind.Method<Func<HitData, bool>>(HealthDependencies.HaveAttacker); private static readonly GameField<HitData, DamageTypes> Channels = Bind.Field<HitData, DamageTypes>(HealthDependencies.Channels); private static readonly GameMethod<FormatId> IdText = Bind.Method<FormatId>(HealthDependencies.FormatId); private static readonly GameMethod<TypedTotal> Total = Bind.Method<TypedTotal>(HealthDependencies.TypedTotal); private static readonly GameMethod<Scale> Multiply = Bind.Method<Scale>(HealthDependencies.Scale); private static readonly GameMethod<Func<ZNetView, ZDO>> Zdo = Bind.Method<Func<ZNetView, ZDO>>(HealthDependencies.GetZdo); private static readonly GameMethod<Action<ZDO, string, string>> Write = Bind.Method<Action<ZDO, string, string>>(HealthDependencies.Write); private static readonly GameMethod<Func<ZDO, string, string, string>> Read = Bind.Method<Func<ZDO, string, string, string>>(HealthDependencies.Read); private static readonly ConditionalWeakTable<Character, ConditionalWeakTable<HitData, DamageDelivery>> Deliveries = new ConditionalWeakTable<Character, ConditionalWeakTable<HitData, DamageDelivery>>(); private static readonly GameMethod<Action<Character, HitData>> RoutedHit = Bind.Method<Action<Character, HitData>>(HealthDependencies.Damage); [ThreadStatic] private static HealRequest pendingHeal; [ThreadStatic] private static HealRequest currentHeal; private static readonly GameMethod<Func<Character, float>> MaxHp = Bind.Method<Func<Character, float>>(HealthDependencies.MaxHp); private static readonly GameMethod<Func<Character, bool>> DebugFlying = Bind.Method<Func<Character, bool>>(MotionDependencies.IsDebugFlying); private static readonly GameMethod<Func<Character, bool>> Teleporting = Bind.Method<Func<Character, bool>>(MotionDependencies.IsTeleporting); private static readonly GameMethod<Func<Character, bool>> Cutscene = Bind.Method<Func<Character, bool>>(MotionDependencies.InCutscene); private static readonly GameMethod<IsCinematicPlaying> Cinematic = Bind.Method<IsCinematicPlaying>(HealthDependencies.Cinematic); [ThreadStatic] private static Character routedStatusVictim; private static readonly GameMethod<Action<TombStone, string, long>> TombSetup = Bind.Method<Action<TombStone, string, long>>(HealthDependencies.SetupTomb); public static bool Installed { get { if (_installed) { return Api.IsUsable("health"); } return false; } } public static Source HealingCause => currentHeal?.Cause ?? default(Source); private static bool Owned(ZNetView view) { if (Object.op_Implicit((Object)(object)view) && Valid.Call(view)) { return Owner.Call(view); } return false; } private static bool Owned(object subject) { Character val = (Character)((subject is Character) ? subject : null); if (val != null && Object.op_Implicit((Object)(object)val)) { return Owned(View.Get(val)); } return false; } private static bool Ready(object subject) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown if (Owned(subject) && !Dead.Call((Character)subject)) { return Hp.Call((Character)subject) > 0f; } return false; } private static DamageDelivery Delivery(Character c, HitData hit) { return Deliveries.GetOrCreateValue(c).GetValue(hit, (HitData _) => new DamageDelivery()); } private static DamageCause Cause(Character c, HitData hit, DamageDelivery delivery) { //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) return new DamageCause(c, Attacker.Call(hit), ((object)Kind.Get(hit)/*cast due to .constrained prefix*/).ToString(), Tier.Get(hit), HaveAttacker.Call(hit), delivery.Id, delivery.Marker, delivery.StatusTick); } public static IDisposable Intercept(Source source, DamageStage stage, Func<DamageCause, float, DamageChange> rule) { return Rules.Add(source, stage, rule); } public static bool TryHit(Character target, HitData hit) { HealthSubmission status; return TryHit(target, hit, out status); } public static bool TryHit(Character target, HitData hit, out HealthSubmission status) { return Submit(target, hit, null, routed: true, out status); } public static bool TryDamage(Character target, HitData hit, string marker = null) { HealthSubmission status; return TryDamage(target, hit, marker, out status); } public static bool TryDamage(Character target, HitData hit, string marker, out HealthSubmission status) { return Submit(target, hit, marker, routed: false, out status); } private static bool Submit(Character target, HitData hit, string marker, bool routed, out HealthSubmission status) { HealthSubmission outcome = HealthSubmission.Unavailable; bool result = Installed && ServiceGate.Run("health", "submitting owned damage", delegate { if (hit == null || Callbacks.Guard.InCallback || Callbacks.Guard.ShutdownPending || !Ready(target)) { outcome = HealthSubmission.Refused; return false; } if (routed) { Action<Character, HitData> call = RoutedHit.Call; outcome = HealthSubmission.Submitted; call(target, hit); } else { Action<Character, HitData, bool, bool, DamageModifier> call2 = Apply.Call; Delivery(target, hit).Marker = marker; outcome = HealthSubmission.Submitted; call2(target, hit, arg3: false, arg4: false, (DamageModifier)0); } return true; }, fallback: false); status = outcome; return result; } public static float TryHeal(Character target, float amount, Source cause, HealScaling scaling = HealScaling.Respect, bool showText = false, Func<float, bool> tryPay = null) { HealthSubmission status; return TryHeal(target, amount, cause, out status, scaling, showText, tryPay); } public static float TryHeal(Character target, float amount, Source cause, out HealthSubmission status, HealScaling scaling = HealScaling.Respect, bool showText = false, Func<float, bool> tryPay = null) { status = HealthSubmission.Unavailable; if (!Installed) { return 0f; } HealthSubmission outcome = HealthSubmission.Unavailable; ConsumerFunc<float, Source, bool> payment = ((tryPay == null) ? null : ConsumerFunc<float, Source, bool>.Narrowed(tryPay)); float result = ServiceGate.Run("health", "healing an owned character", delegate { if (!cause.IsValid || !(amount > 0f) || float.IsInfinity(amount) || Callbacks.Guard.InCallback || Callbacks.Guard.ShutdownPending || !Ready(target)) { outcome = HealthSubmission.Refused; return 0f; } Action<Character, float, bool> call = Heal.Call; float num = Hp.Call(target); HealRequest healRequest = pendingHeal; pendingHeal = new HealRequest { Target = target, Cause = cause, Amount = amount, Scaling = scaling, Payment = payment }; try { outcome = HealthSubmission.Submitted; call(target, amount, showText); } finally { pendingHeal = healRequest; } return (!Owned((object)target)) ? 0f : Math.Max(0f, Hp.Call(target) - num); }, 0f); status = outcome; return result; } private static void BeginHeal(Character __instance, out HealRequest __state) { __state = currentHeal; currentHeal = (((Object)(object)pendingHeal?.Target == (Object)(object)__instance) ? pendingHeal : null); pendingHeal = null; } private static void EndHeal(HealRequest __state) { currentHeal = __state; } private static void BeforeDiversion(Character __instance, ref float hp) { if (Installed && currentHeal != null && currentHeal.Target == __instance) { hp = HealAdmission.BeforeDiversion(currentHeal.Scaling, currentHeal.Amount, hp); } } private static float AdmitHeal(float scaled, Character target, float before) { HealRequest request = currentHeal; if (request == null || request.Target != target) { return scaled; } if (request.Used || Callbacks.Guard.InCallback) { return 0f; } request.Used = true; return HealthBoundary.AdmitHeal(scaled, () => HealAdmission.Admit(before, MaxHp.Call(target), HealAdmission.Amount(request.Scaling, request.Amount, scaled), request.Payment, request.Cause, Callbacks.Guard, (object c) => Ready(c) && Hp.Call((Character)c) == before, target, VolundPlugin.Warn)); } private static IEnumerable<CodeInstruction> HealIL(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { return Rewrite(instructions, HealthDependencies.RpcHeal, (List<CodeInstruction> code) => RewriteHeal(code, generator)); } private static List<CodeInstruction> RewriteHeal(List<CodeInstruction> code, ILGenerator generator) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Expected O, but got Unknown //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected O, but got Unknown //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected O, but got Unknown int num = Anchor(code, HealthDependencies.MaxHp) - 4; if (code[num].opcode != OpCodes.Ldloc_0 || code[num + 1].opcode != OpCodes.Ldarg_2 || code[num + 2].opcode != OpCodes.Add) { throw new InvalidOperationException("health.rpcheal: expected current health plus the heal amount."); } CodeInstruction val = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_2, (object)null), code[num]); Label label = generator.DefineLabel(); AddLabel(code[num], label); code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[9] { val, new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldloc_0, (object)null), CodeInstruction.Call(typeof(Health), "AdmitHeal", (Type[])null, (Type[])null), new CodeInstruction(OpCodes.Dup, (object)null), new CodeInstruction(OpCodes.Starg_S, (object)(byte)2), new CodeInstruction(OpCodes.Ldc_R4, (object)0f), new CodeInstruction(OpCodes.Bgt, (object)label), new CodeInstruction(OpCodes.Ret, (object)null) }); return code; } private static MethodInfo Patch(string name) { return typeof(Health).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic); } internal static void Install() { _ = RoutedHit.Call; _ = Apply.Call; if (!Application.isBatchMode) { _ = TombSetup.Call; } Service health = ServiceCatalog.Health; MethodDependency[] array = new MethodDependency[2] { HealthDependencies.Stats, HealthDependencies.Wet }; foreach (MethodDependency target in array) { Hooks.Transpiler(health, target, Patch("RoutedStatusIL")); } array = new MethodDependency[3] { HealthDependencies.Poison, HealthDependencies.Burning, HealthDependencies.Smoke }; foreach (MethodDependency target2 in array) { Hooks.Transpiler(health, target2, Patch("DirectStatusIL")); } Hooks.Prefix(health, HealthDependencies.RpcDamage, Patch("DecodeStatus"), 800); Hooks.Transpiler(health, HealthDependencies.RpcDamage, Patch("EarlyIL")); Hooks.Prefix(health, HealthDependencies.Apply, Patch("BeginApply"), 800); Hooks.Prefix(health, HealthDependencies.Apply, Patch("FallPrefix")); Hooks.Transpiler(health, HealthDependencies.Apply, Patch("FinalIL")); Hooks.Finalizer(health, HealthDependencies.Apply, Patch("EndApply")); Hooks.Postfix(health, HealthDependencies.SetHealth, Patch("ClearOnRecovery")); Hooks.Postfix(health, HealthDependencies.CharacterRagdoll, Patch("RagdollCreated")); Hooks.Postfix(health, HealthDependencies.HumanoidRagdoll, Patch("RagdollCreated")); if (!Application.isBatchMode) { Hooks.Transpiler(health, HealthDependencies.Tomb, Patch("TombIL")); } Hooks.Prefix(health, HealthDependencies.Heal, Patch("BeginHeal"), 800); Hooks.Finalizer(health, HealthDependencies.Heal, Patch("EndHeal")); Hooks.Prefix(health, HealthDependencies.RpcHeal, Patch("BeforeDiversion"), 599); Hooks.Transpiler(health, HealthDependencies.RpcHeal, Patch("HealIL")); _installed = Api.IsUsable("health"); } internal static void Shutdown() { _installed = false; Rules.Clear(); } private static bool BeginApply(Character __instance, HitData hit, out DamageDelivery __state) { __state = null; if (!Installed || hit == null) { return true; } DamageDelivery damageDelivery = Delivery(__instance, hit); if (!damageDelivery.BeginApply()) { return false; } __state = damageDelivery; return true; } private static void EndApply(DamageDelivery __state) { __state?.Settle(Callbacks.Guard, VolundPlugin.Warn); } private static bool FallPrefix(Character __instance, HitData hit, bool __runOriginal) { if (__runOriginal && Installed && Rules.HasFallRules) { return ServiceGate.Run("health", "applying fall protection before shields", delegate { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_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) if (hit == null || (int)Kind.Get(hit) != 3) { return true; } if (!Ready(__instance)) { return false; } if (DebugFlying.Call(__instance) || Teleporting.Call(__instance) || Cutscene.Call(__instance) || Cinematic.Call()) { return true; } DamageDelivery delivery = Delivery(__instance, hit); ref DamageTypes reference = ref Channels.Ref(hit); FieldInfo fieldInfo = Bind.Resolved<FieldInfo>(HealthDependencies.GenericDamage); object obj = reference; float num = (float)fieldInfo.GetValue(obj); if (!(num > 0f)) { return true; } float num2 = Rules.Run(DamageStage.FallBeforeShields, Cause(__instance, hit, delivery), num, Ready, delivery); if (!Ready(__instance)) { return false; } if (num2 != num) { obj = reference; fieldInfo.SetValue(obj, num2); reference = (DamageTypes)obj; } return true; }, fallback: true); } return true; } private static bool Early(Character c, HitData hit) { return HealthBoundary.BeforeResistance(delegate { if (!Ready(c)) { return false; } DamageDelivery delivery = Delivery(c, hit); ref DamageTypes damage = ref Channels.Ref(hit); float num = Total.Call(ref damage); if (num > 0f) { float num2 = Rules.Run(DamageStage.BeforeResistance, Cause(c, hit, delivery), num, Ready, delivery); if (!(num2 > 0f) || !Ready(c)) { return false; } if (num != num2) { Multiply.Call(ref damage, num2 / num); } } return true; }); } private static float Final(float amount, Character c, HitData hit) { return HealthBoundary.Final(amount, delegate { if (Ready(c)) { DamageDelivery damageDelivery = Delivery(c, hit); float num = Rules.Run(DamageStage.Final, Cause(c, hit, damageDelivery), amount, Ready, damageDelivery); if (num == 0f && Ready(c) && damageDelivery.PaymentAccepted) { damageDelivery.Applied = true; } return num; } return 0f; }); } private static int Anchor(List<CodeInstruction> code, MethodDependency method, int count = 1) { var array = (from x in code.Select((CodeInstruction instruction, int index) => new { instruction, index }) where CodeInstructionExtensions.Calls(x.instruction, Bind.Resolved<MethodInfo>(method)) select x).ToArray(); if (array.Length != count) { throw new InvalidOperationException($"Expected {count} calls to {method.Id}, found {array.Length}."); } return array[count - 1].index; } private static void DecodeStatus(Character __instance, HitData hit) { if (routedStatusVictim == __instance && hit != null) { routedStatusVictim = null; Delivery(__instance, hit).StatusTick = true; } } private static void RoutedStatus(Character victim, HitData hit) { Character val = routedStatusVictim; routedStatusVictim = victim; try { RoutedHit.Call(victim, hit); } finally { routedStatusVictim = val; } } private static void DirectStatus(Character victim, HitData hit, bool text, bool effects, DamageModifier mod) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) Delivery(victim, hit).StatusTick = true; Apply.Call(victim, hit, text, effects, mod); } private static IEnumerable<CodeInstruction> RoutedStatusIL(IEnumerable<CodeInstruction> instructions) { return ReplaceCall(instructions, HealthDependencies.Damage, "RoutedStatus"); } private static IEnumerable<CodeInstruction> DirectStatusIL(IEnumerable<CodeInstruction> instructions) { return ReplaceCall(instructions, HealthDependencies.Apply, "DirectStatus"); } private static IEnumerable<CodeInstruction> ReplaceCall(IEnumerable<CodeInstruction> instructions, MethodDependency target, string replacement) { return Rewrite(instructions, target, delegate(List<CodeInstruction> code) { int index = Anchor(code, target); code[index] = CodeInstructionExtensions.MoveLabelsFrom(CodeInstruction.Call(typeof(Health), replacement, (Type[])null, (Type[])null), code[index]); return code; }); } private static void AddLabel(CodeInstruction instruction, Label label) { ((IList)typeof(CodeInstruction).GetField("labels").GetValue(instruction)).Add(label); } private static bool ContinueRouted(Character target) { if (Api.IsUsable("health")) { return ServiceGate.Run("health", "returning to routed damage", () => Owned((object)target), fallback: true); } return true; } private static IEnumerable<CodeInstruction> EarlyIL(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { return Rewrite(instructions, HealthDependencies.RpcDamage, (List<CodeInstruction> code) => RewriteRouted(code, generator)); } private static List<CodeInstruction> RewriteRouted(List<CodeInstruction> code, ILGenerator generator) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Expected O, but got Unknown //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Expected O, but got Unknown int index = Anchor(code, HealthDependencies.Apply) + 1; Label label = generator.DefineLabel(); CodeInstruction val = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), code[index]); AddLabel(code[index], label); code.InsertRange(index, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4] { val, CodeInstruction.Call(typeof(Health), "ContinueRouted", (Type[])null, (Type[])null), new CodeInstruction(OpCodes.Brtrue, (object)label), new CodeInstruction(OpCodes.Ret, (object)null) }); int num = Anchor(code, HealthDependencies.Modifiers) - 2; if (code[num].opcode != OpCodes.Ldarg_0 || code[num + 1].opcode != OpCodes.Ldloc_2) { throw new InvalidOperationException("health.rpcdamage: unexpected resistance operands."); } Label label2 = generator.DefineLabel(); CodeInstruction val2 = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), code[num]); AddLabel(code[num], label2); code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[5] { val2, new CodeInstruction(OpCodes.Ldarg_2, (object)null), CodeInstruction.Call(typeof(Health), "Early", (Type[])null, (Type[])null), new CodeInstruction(OpCodes.Brtrue, (object)label2), new CodeInstruction(OpCodes.Ret, (object)null) }); return code; } private static IEnumerable<CodeInstruction> FinalIL(IEnumerable<CodeInstruction> instructions, ILGenerator generator) { return Rewrite(instructions, HealthDependencies.Apply, (List<CodeInstruction> code) => RewriteApply(code, generator)); } private static IEnumerable<CodeInstruction> Rewrite(IEnumerable<CodeInstruction> instructions, MethodDependency target, Func<List<CodeInstruction>, List<CodeInstruction>> rewrite) { List<CodeInstruction> list = instructions.ToList(); if (!Api.IsUsable("health")) { return list; } try { return rewrite(((IEnumerable<CodeInstruction>)list).Select((Func<CodeInstruction, CodeInstruction>)((CodeInstruction i) => new CodeInstruction(i))).ToList()); } catch (Exception e) { ServiceStates.Fault("health", "matching " + target.Id + " IL", e); return list; } } private static List<CodeInstruction> RewriteApply(List<CodeInstruction> code, ILGenerator generator) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Expected O, but got Unknown //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Expected O, but got Unknown //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Expected O, but got Unknown //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Expected O, but got Unknown //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Expected O, but got Unknown //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Expected O, but got Unknown //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Expected O, but got Unknown //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Expected O, but got Unknown //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Expected O, but got Unknown //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Expected O, but got Unknown //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Expected O, but got Unknown //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02fa: Expected O, but got Unknown //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Expected O, but got Unknown //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Expected O, but got Unknown //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Expected O, but got Unknown //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Expected O, but got Unknown //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Expected O, but got Unknown int num = Anchor(code, HealthDependencies.SetHealth); LocalBuilder localBuilder = generator.DeclareLocal(typeof(bool)); code.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), CodeInstruction.Call(typeof(Health), "RecordDeath", (Type[])null, (Type[])null) }); code.InsertRange(num, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Dup, (object)null), new CodeInstruction(OpCodes.Ldarg_0, (object)null), CodeInstruction.Call(typeof(Health), "CouldKill", (Type[])null, (Type[])null), new CodeInstruction(OpCodes.Stloc, (object)localBuilder) }); MethodInfo totalMethod = Bind.Resolved<MethodInfo>(HealthDependencies.Total); int num2 = HealthAnchors.ScaledTotal(code.Count, (int i) => CodeInstructionExtensions.Calls(code[i], totalMethod), (int i) => code[i].opcode == OpCodes.Stloc_1); int num3 = Anchor(code, HealthDependencies.HealthValue) - 1; if (num2 < 0 || num3 <= num2 || code[num3].opcode != OpCodes.Ldarg_0) { throw new InvalidOperationException("health.apply: unexpected scaled damage or current-health operand."); } int num4 = code.FindIndex(num2 + 2, num3 - num2 - 2, (CodeInstruction i) => i.opcode == OpCodes.Ldarg_2); if (num4 < 1 || code[num4 - 1].opcode != OpCodes.Ret) { throw new InvalidOperationException("health.apply: missing post-threshold damage text gate."); } CodeInstruction val = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldloc_1, (object)null), code[num4]); LocalBuilder localBuilder2 = generator.DeclareLocal(typeof(float)); Label label = generator.DefineLabel(); AddLabel(code[num4], label); code.InsertRange(num4, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[16] { val, new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), CodeInstruction.Call(typeof(Health), "Final", (Type[])null, (Type[])null), new CodeInstruction(OpCodes.Stloc, (object)localBuilder2), new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2), new CodeInstruction(OpCodes.Ldloc_1, (object)null), new CodeInstruction(OpCodes.Beq, (object)label), new CodeInstruction(OpCodes.Ldloc, (object)localBuilder2), new CodeInstruction(OpCodes.Dup, (object)null), new CodeInstruction(OpCodes.Stloc_1, (object)null), new CodeInstruction(OpCodes.Stloc_0, (object)null), new CodeInstruction(OpCodes.Ldloc_1, (object)null), new CodeInstruction(OpCodes.Ldc_R4, (object)0f), new CodeInstruction(OpCodes.Bgt, (object)label), new CodeInstruction(OpCodes.Ret, (object)null) }); code.InsertRange(num2 + 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[4] { new CodeInstruction(OpCodes.Ldloc_1, (object)null), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldarg_1, (object)null), CodeInstruction.Call(typeof(Health), "Scaled", (Type[])null, (Type[])null) }); return code; } private static void Scaled(float amount, Character c, HitData hit) { if (!(amount <= 0.1f) || !Installed) { return; } ServiceGate.TryRun("health", "settling absorbed fall damage", delegate { if (Ready(c)) { Delivery(c, hit).Scaled(amount); } }); } private static bool CouldKill(float proposed, Character target) { if (proposed <= 0f) { return ServiceGate.Run("health", "checking lethal damage", () => Ready(target), fallback: false); } return false; } private static void RecordDeath(bool alive, Character c, HitData hit) { Delivery(c, hit).Applied = true; if (!alive) { return; } ServiceGate.TryRun("health", "recording lethal damage", delegate { //IL_0047: 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_0073: Unknown result type (might be due to invalid IL or missing references) if (Owned((object)c) && !(Hp.Call(c) > 0f)) { DamageDelivery damageDelivery = Delivery(c, hit); ZDOID id = AttackerId.Get(hit); string arg = FormattableString.Invariant($"{damageDelivery.Id:N}|{Kind.Get(hit)}|{IdText.Call(ref id)}|{Tier.Get(hit)}|{damageDelivery.Marker}"); Write.Call(Zdo.Call(View.Get(c)), "volund.health.death.v1", arg); } }); } private static string DeathRecord(ZNetView view) { return ServiceGate.Run("health", "reading lethal damage", () => (!Object.op_Implicit((Object)(object)view) || !Valid.Call(view)) ? "" : Read.Call(Zdo.Call(view), "volund.health.death.v1", ""), ""); } public static bool TryReadDeath(ZNetView view, out LethalHit hit) { return LethalHit.TryRead(DeathRecord(view), out hit); } public static bool TryReadDeath(Character target, out LethalHit hit) { return TryReadDeath(ServiceGate.Run("health", "reading the victim view", () => (!Object.op_Implicit((Object)(object)target)) ? null : View.Get(target), null), out hit); } private static void ClearOnRecovery(Character __instance, float health) { if (!(health > 0f)) { return; } ServiceGate.TryRun("health", "clearing an earlier death", delegate { if (Owned((object)__instance) && !(Hp.Call(__instance) <= 0f)) { ZNetView val = View.Get(__instance); if (DeathRecord(val).Length != 0) { Write.Call(Zdo.Call(val), "volund.health.death.v1", ""); } } }); } private static void CopyCorpse(Component corpse, Character victim) { ServiceGate.TryRun("health", "copying lethal damage", delegate { if (Object.op_Implicit((Object)(object)corpse) && Owned((object)victim)) { ZNetView component = corpse.GetComponent<ZNetView>(); if (Owned(component)) { Write.Call(Zdo.Call(component), "volund.health.death.v1", DeathRecord(View.Get(victim))); } } }); } private static void RagdollCreated(Character __instance, Ragdoll ragdoll) { CopyCorpse((Component)(object)ragdoll, __instance); } private static IEnumerable<CodeInstruction> TombIL(IEnumerable<CodeInstruction> instructions) { return Rewrite(instructions, HealthDependencies.Tomb, delegate(List<CodeInstruction> code) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown int index = Anchor(code, HealthDependencies.SetupTomb); CodeInstruction item = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), code[index]); code[index] = CodeInstruction.Call(typeof(Health), "SetupTomb", (Type[])null, (Type[])null); code.Insert(index, item); return code; }); } private static void SetupTomb(TombStone tomb, string name, long id, Player player) { TombSetup.Call(tomb, name, id); CopyCorpse((Component)(object)tomb, (Character)(object)player); } } public static class Items { private sealed class Follow { internal ItemData Next; } private sealed class Bag : ItemBag { private readonly Player _player; private readonly Container _container; private readonly Inventory _bag; private List<ItemData> _publish; internal override object Identity => _bag; internal override bool Owned { get { if (_container == null) { if (Object.op_Implicit((Object)(object)_player) && (Object)(object)_player == (Object)(object)Player && ItemBindings.PlayerOwner.Call((Character)(object)_player)) { return ItemBindings.PlayerBag.Call((Humanoid)(object)_player) == _bag; } return false; } if (Object.op_Implicit((Object)(object)_container) && ItemBindings.ContainerOwner.Call(_container)) { return ItemBindings.ContainerBag.Call(_container) == _bag; } return false; } } internal Bag(Player player, Container container) { _player = player; _container = container; _bag = (Object.op_Implicit((Object)(object)container) ? ItemBindings.ContainerBag.Call(container) : ItemBindings.PlayerBag.Call((Humanoid)(object)player)); } internal override bool Contains(object item) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown return ItemBindings.List.Call(_bag).Contains((ItemData)item); } internal override object Revision(object item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) return (ItemBindings.Quality.Get((ItemData)item), ItemBindings.World.Get((ItemData)item), ItemBindings.Prefab.Get((ItemData)item), ItemBindings.Position.Get((ItemData)item)); } internal override int Count(object item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown return ItemBindings.Stack.Get((ItemData)item); } internal override bool Equipped(object item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown return ItemBindings.Equipped.Get((ItemData)item); } internal override Dictionary<string, string> Data(object item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown return ItemBindings.Custom.Get((ItemData)item); } internal override void PrepareCommit(bool inserting) { _ = ItemBindings.Changed.Call; _publish = ItemBindings.List.Call(_bag); if (inserting && _publish.Capacity == _publish.Count) { _publish.Capacity = checked(_publish.Count + 1); } } internal override void SetCount(object item, int count) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown ItemBindings.Stack.Set((ItemData)item, count); if (count == 0) { _publish.Remove((ItemData)item); } } internal override IEnumerable<object> Candidates(object item) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown ItemData[] array = Matches(_bag, (ItemData)item).ToArray(); if (!CustomFinder()) { return array; } return Confirmed(_bag, (ItemData)item, array); } internal override int Room(object target) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown return Space((ItemData)target); } internal override object PrepareReturn(object template, object freed) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0087: Unknown result type (might be due to invalid IL or missing references) if (freed == null && ItemBindings.Empty.Call(_bag) <= 0) { return null; } ItemData val = ItemBindings.Clone.Call((ItemData)template); ItemBindings.Stack.Set(val, 1); Vector2i val2 = ((freed != null) ? ItemBindings.Position.Get((ItemData)freed) : ItemBindings.Slot.Call(_bag, arg2: false)); if (!ValidCell(_bag, val2, (ItemData)freed)) { return null; } ItemBindings.Position.Set(val, val2); return val; } internal override void Insert(object prepared) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown _publish.Add((ItemData)prepared); } internal override void Changed() { ItemBindings.Changed.Call(_bag, arg2: false, arg3: false); } } private sealed class Health : ItemSession.IHealth { public bool Usable => Api.IsUsable("items"); public void Fault(Exception error) { ServiceStates.Fault("items", "inventory operation", error); } } private sealed class Placement { internal ItemData Target; internal int Count; } private sealed class Craft { internal Inventory Bag; internal ItemData Original; internal Dictionary<string, string> Data; internal Player Owner; internal bool Reserved; internal bool Creating; internal Vector2i Position; internal Dictionary<string, string> Expected; } private sealed class Addition { internal Addition Previous; internal Inventory Bag; internal ItemData Source; internal PickupPlan<ItemData> Plan; internal Vector2i Cell; internal readonly Dictionary<ItemData, int> Counts = new Dictionary<ItemData, int>(); } private sealed class Observed { internal ItemData Item; internal string Slot; internal string Grid; internal Dictionary<string, string> Data; } private static readonly GameStaticField<Player> Local = Bind.StaticField<Player>(MotionDependencies.LocalPlayer); private static readonly ConditionalWeakTable<ItemData, Follow> Moves = new ConditionalWeakTable<ItemData, Follow>(); private static readonly (string name, GameField<Humanoid, ItemData> field)[] Slots = new(string, GameField<Humanoid, ItemData>)[11] { ("right", ItemBindings.Right), ("left", ItemBindings.Left), ("right", ItemBindings.HiddenRight), ("left", ItemBindings.HiddenLeft), ("chest", ItemBindings.Chest), ("legs", ItemBindings.Leg), ("helmet", ItemBindings.Helmet), ("shoulder", ItemBindings.Shoulder), ("utility", ItemBindings.Utility), ("ammo", ItemBindings.Ammo), ("trinket", ItemBindings.Trinket) }; private static readonly ConditionalWeakTable<GameObject, string> PrefabNames = new ConditionalWeakTable<GameObject, string>(); private static readonly GameMethod<Func<Humanoid, ItemData, bool, bool>> Equip = Bind.Method<Func<Humanoid, ItemData, bool, bool>>(ItemDependencies.Equip); private static Humanoid completingOwner; private static ItemData completingItem; private static object completingAction; private static Craft _craft; private static Addition _addition; private static Dictionary<Guid, Observed> _previous = new Dictionary<Guid, Observed>(); private static bool _dirty = true; private static Player _observedPlayer; private static int _observedRevision; public static ItemSession Session { get; private set; } = new ItemSession(Callbacks.Guard); private static Player Player => Local.Get(); private static ItemResult Fault(string operation, Exception error) { ServiceStates.Fault("items", operation, error); return ItemResult.Unusable; } public static ItemResult Read(ItemRecord schema, ItemData item, out string value) { try { return ReadCore(schema, item, out value); } catch (Exception error) { value = null; return Fault("Read", error); } } private static ItemResult ReadCore(ItemRecord schema, ItemData item, out string value) { value = null; if (!Session.Ready || schema?.Session != Session) { return ItemResult.Unusable; } if (item != null) { return schema.Decode(ItemBindings.Custom.Get(item), out value); } return ItemResult.Absent; } public static ItemResult Read(ItemRecord schema, ItemDrop drop, out string value) { try { return ReadCore(schema, drop, out value); } catch (Exception error) { value = null; return Fault("Read", error); } } private static ItemResult ReadCore(ItemRecord schema, ItemDrop drop, out string value) { value = null; if (!Session.Ready) { return ItemResult.Unusable; } if (!Object.op_Implicit((Object)(object)drop)) { return ItemResult.Absent; } return Read(schema, ItemBindings.Drop.Get(drop), out value); } public static ItemResult Read(ItemRecord schema, ZDO zdo, ItemData template, int slot, out string value) { try { return ReadCore(schema, zdo, template, slot, out value); } catch (Exception error) { value = null; return Fault("Read", error); } } private static ItemResult ReadCore(ItemRecord schema, ZDO zdo, ItemData template, int slot, out string value) { value = null; if (!Session.Ready) { return ItemResult.Unusable; } if (zdo == null || template == null) { return ItemResult.Absent; } ItemData val = ItemBindings.Clone.Call(template); ItemBindings.Custom.Get(val).Clear(); try { ItemBindings.Load.Call(val, zdo, slot); } catch (EndOfStreamException) { return ItemResult.Invalid; } return Read(schema, val, out value); } public static ItemResult Read(ItemRecord schema, ItemStand stand, ItemData template, out string value) { try { return ReadCore(schema, stand, template, out value); } catch (Exception error) { value = null; return Fault("Read", error); } } private static ItemResult ReadCore(ItemRecord schema, ItemStand stand, ItemData template, out string value) { value = null; if (!Session.Ready) { return ItemResult.Unusable; } if (!Object.op_Implicit((Object)(object)stand) || !Object.op_Implicit((Object)(object)ItemBindings.StandView.Get(stand)) || !ItemBindings.StandOccupied.Call(stand)) { return ItemResult.Absent; } return Read(schema, ItemBindings.Zdo.Call(ItemBindings.StandView.Get(stand)), template, -1, out value); } public static ItemResult Read(ItemRecord schema, ArmorStand stand, int slot, ItemData template, out string value) { try { return ReadCore(schema, stand, slot, template, out value); } catch (Exception error) { value = null; return Fault("Read", error); } } private static ItemResult ReadCore(ItemRecord schema, ArmorStand stand, int slot, ItemData template, out string value) { value = null; if (!Session.Ready) { return ItemResult.Unusable; } if (slot >= 0) { int[] array = ItemBindings.ArmorKeys.Get(); if (slot < ((array != null) ? array.Length : 0)) { if (!Object.op_Implicit((Object)(object)stand) || !Object.op_Implicit((Object)(object)ItemBindings.ArmorView.Get(stand)) || !ItemBindings.ArmorOccupied.Call(stand, slot)) { return ItemResult.Absent; } return Read(schema, ItemBindings.Zdo.Call(ItemBindings.ArmorView.Get(stand)), template, slot, out value); } } return ItemResult.Invalid; } public static ItemResult Resolve(ItemData item, out ItemData current) { current = null; if (!Session.Ready) { return ItemResult.Unusable; } Follow value; while (item != null && Moves.TryGetValue(item, out value)) { item = value.Next; } current = item; if (item != null) { return ItemResult.Ok; } return ItemResult.Absent; } public static ItemResult Capture(ItemRecord schema, ItemData item, out ItemRef snapshot, Container container = null) { try { return CaptureCore(schema, item, out snapshot, container); } catch (Exception error) { snapshot = null; return Fault("Capture", error); } } private static ItemResult CaptureCore(ItemRecord schema, ItemData item, out ItemRef snapshot, Container container) { snapshot = null; if (!Session.Ready) { return ItemResult.Unusable; } Player player = Player; if (container != null && !Object.op_Implicit((Object)(object)container)) { return ItemResult.Stale; } if (!Object.op_Implicit((Object)(object)container) && !Object.op_Implicit((Object)(object)player)) { return ItemResult.Absent; } Bag bag = new Bag(player, container); return Session.Capture(bag, item, schema, out snapshot); } public static ItemResult PrepareReturn(ItemRecord schema, ItemData template, string value, out ReturnedItem output) { try { return PrepareReturnCore(schema, template, value, out output); } catch (Exception error) { output = null; return Fault("PrepareReturn", error); } } public static ItemResult PrepareReturn(ItemRecord schema, ItemDrop prefab, string value, out ReturnedItem output) { output = null; if (!Session.Ready) { return ItemResult.Unusable; } if (!Object.op_Implicit((Object)(object)prefab)) { return ItemResult.Invalid; } try { ItemData val = ItemBindings.Clone.Call(ItemBindings.Drop.Get(prefab)); ItemBindings.Prefab.Set(val, ((Component)prefab).gameObject); return PrepareReturnCore(schema, val, value, out output); } catch (Exception error) { return Fault("PrepareReturn", error); } } private static ItemResult PrepareReturnCore(ItemRecord schema, ItemData template, string value, out ReturnedItem output) { output = null; if (!Session.Ready) { return ItemResult.Unusable; } if (template == null || !Object.op_Implicit((Object)(object)ItemBindings.Prefab.Get(template))) { return ItemResult.Invalid; } ItemData val = ItemBindings.Clone.Call(template); ItemBindings.Equipped.Set(val, value: false); return Session.Prepare(schema, val, ItemBindings.Custom.Get(val), value, out output); } private static bool Fixed(ItemData item, out float weight, out float armour) { weight = (armour = 0f); if (!Session.HasFixedStats || item == null) { return false; } GameObject val = ItemBindings.Prefab.Get(item); if (Object.op_Implicit((Object)(object)val)) { return Session.TryFixedStats(PrefabNames.GetValue(val, (GameObject p) => ((Object)p).name), out weight, out armour); } return false; } private static void Armour(ItemData __instance, ref float __result) { if (Fixed(__instance, out var _, out var armour)) { __result = armour; } } private static void Weight(ItemData __instance, int stackOverride, ref float __result) { if (Fixed(__instance, out var weight, out var _)) { __result = weight * (float)((stackOverride < 0) ? ItemBindings.Stack.Get(__instance) : stackOverride); } } private static void UnitWeight(ItemData __instance, ref float __result) { if (Fixed(__instance, out var weight, out var _)) { __result = weight; } } private static string GridSlot(ItemData item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) Vector2i val = ItemBindings.Position.Get(item); return Bind.Resolved<FieldInfo>(ItemDependencies.GridX).GetValue(val)?.ToString() + "," + Bind.Resolved<FieldInfo>(ItemDependencies.GridY).GetValue(val); } private static string Slot(Player player, ItemData item) { (string, GameField<Humanoid, ItemData>)[] slots = Slots; for (int i = 0; i < slots.Length; i++) { (string, GameField<Humanoid, ItemData>) tuple = slots[i]; if (tuple.Item2.Get((Humanoid)(object)player) == item) { return tuple.Item1; } } return null; } internal static void Install() { Session = new ItemSession(Callbacks.Guard) { Health = new Health() }; if (!Api.IsUsable("items")) { return; } Hook[] array = new Hook[3] { Hooks.Postfix(ServiceCatalog.Items, ItemDependencies.Weight, PatchMethod("Weight")), Hooks.Postfix(ServiceCatalog.Items, ItemDependencies.UnitWeight, PatchMethod("UnitWeight")), Hooks.Postfix(ServiceCatalog.Items, ItemDependencies.Armour, PatchMethod("Armour")) }; Session.FixedStatsEnabled = array.All((Hook h) => h != null); if (!Session.FixedStatsEnabled) { Hook[] array2 = array; for (int num = 0; num < array2.Length; num++) { array2[num]?.Dispose(); } VolundPlugin.Warn("Volund: fixed item stats unavailable. Item records remain active."); } Hook(ItemDependencies.Equip, "OnEquip", prefix: true); Hook(ItemDependencies.Equip, "AfterEquipment", prefix: false); Hook(ItemDependencies.Unequip, "AfterEquipment", prefix: false); Hook(ItemDependencies.Changed, "AfterInventory", prefix: false); Hook(ItemDependencies.Place, "OnPlace", prefix: true); Hook(ItemDependencies.Place, "AfterPlace", prefix: false); Hook(ItemDependencies.Move, "BeforeMove", prefix: true); Hook(ItemDependencies.Move, "AfterMove", prefix: false); if (Hooks.Transpiler(ServiceCatalog.Items, ItemDependencies.AutoStack, typeof(Items).GetMethod("WorldStack", BindingFlags.Static | BindingFlags.NonPublic)) == null) { throw new InvalidOperationException("World merge hook failed"); } Hook(ItemDependencies.CanAdd, "CanAdd", prefix: false); Hook(ItemDependencies.GroundSplit, "GroundSplit", prefix: true); if (Hooks.Transpiler(ServiceCatalog.Items, ItemDependencies.Craft, typeof(Items).GetMethod("CraftEdges", BindingFlags.Static | BindingFlags.NonPublic)) == null) { throw new InvalidOperationException("Upgrade hook failed"); } Hook(ItemDependencies.Slot, "FactoryCell", prefix: true); Hook(ItemDependencies.Craft, "BeginCraft", prefix: true); Hook(ItemDependencies.Craft, "EndCraft", prefix: false, finalizer: true); Hook(ItemDependencies.Add, "BeginAdd", prefix: true); Hook(ItemDependencies.Add, "EndAdd", prefix: false, finalizer: true); Hook(ItemDependencies.AddAt, "BeginAddAt", prefix: true); Hook(ItemDependencies.AddAt, "EndAdd", prefix: false, finalizer: true); MethodDependency[] array3 = new MethodDependency[2] { ItemDependencies.Add, ItemDependencies.AddAt }; foreach (MethodDependency target in array3) { if (Hooks.Transpiler(ServiceCatalog.Items, target, PatchMethod("AddEdges")) == null) { throw new InvalidOperationException("Inventory allocation hook failed"); } } Session.Enabled = true; static void Hook(MethodDependency methodDependency, string name, bool prefix, bool finalizer = false) { MethodInfo method = typeof(Items).GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic); if ((finalizer ? Hooks.Finalizer(ServiceCatalog.Items, methodDependency, method, 0) : (prefix ? Hooks.Prefix(ServiceCatalog.Items, methodDependency, method) : Hooks.Postfix(ServiceCatalog.Items, methodDependency, method))) == null) { throw new InvalidOperationException("Could not install " + methodDependency.Id); } } } internal static void InstallEquipCompletion() { if (Hooks.Transpiler(ServiceCatalog.EquipCompletion, ItemDependencies.AdvanceQueue, PatchMethod("QueueEquipEdge")) == null) { throw new InvalidOperationException("Equip completion hook failed"); } } private static IEnumerable<CodeInstruction> QueueEquipEdge(IEnumerable<CodeInstruction> instructions) { List<CodeInstruction> body = instructions.ToList(); int count = 0; for (int i = 0; i < body.Count; i++) { CodeInstruction code = body[i]; if (CodeInstructionExtensions.Calls(code, (MethodInfo)ItemDependencies.Equip.Resolved)) { string text = ((i >= 3) ? body[i - 3].opcode.Name : ""); if ((text != "ldloc" && !text.StartsWith("ldloc.", StringComparison.Ordinal)) || !CodeInstructionExtensions.LoadsField(body[i - 2], (FieldInfo)ItemDependencies.ActionItem.Resolved, false) || body[i - 1].opcode != OpCodes.Ldc_I4_1) { throw new InvalidOperationException("Queued equip item source changed."); } yield return CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(body[i - 3].opcode, body[i - 3].operand), code); code.opcode = OpCodes.Call; code.operand = PatchMethod("FinishQueuedEquip"); count++; } yield return code; } if (count != 1) { throw new InvalidOperationException("Expected one queued EquipItem call."); } } private static bool FinishQueuedEquip(Humanoid owner, ItemData item, bool effects, object action) { completingAction = action; completingOwner = owner; completingItem = item; try { return Equip.Call(owner, item, effects); } finally { completingOwner = null; completingItem = null; completingAction = null; } } public static bool TakeEquipCompletion(Humanoid owner, ItemData item, object action) { if (action == null || item == null || completingOwner != owner || completingItem != item || completingAction != action) { return false; } completingItem = null; return true; } private static void AfterEquipment(Humanoid __instance) { if (Session.Ready && (Object)(object)__instance == (Object)(object)Player) { _dirty = true; } } private static void AfterInventory(Inventory __instance) { if (Session.Ready && Object.op_Implicit((Object)(object)Player) && ItemBindings.PlayerBag.Call((Humanoid)(object)Player) == __instance) { _dirty = true; } } private static bool OnEquip(Humanoid __instance, ItemData item) { if (!Session.Ready || item == null || !Object.op_Implicit((Object)(object)Player) || (Object)(object)__instance != (Object)(object)Player || !ItemBindings.PlayerOwner.Call((Character)(object)Player)) { return true; } Player player = Player; Inventory bag = ItemBindings.PlayerBag.Call((Humanoid)(object)player); return Session.MayEquip(ItemBindings.Custom.Get(item), "equip", (ItemRecord schema) =>