using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BaseProtection.Core; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using SoftReferenceableAssets; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyCompany("BaseProtection")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.1.2.0")] [assembly: AssemblyInformationalVersion("1.1.2")] [assembly: AssemblyProduct("Runestone Base Protection")] [assembly: AssemblyTitle("Runestone Base Protection")] [assembly: AssemblyVersion("1.1.2.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [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 BaseProtection.Core { public static class CreatorConsent { public const int MaxCreators = 32; private const int MaxEncodedLength = 672; public static bool TryParse(string? encoded, out HashSet creators) { creators = new HashSet(); if (string.IsNullOrEmpty(encoded)) { return true; } if (encoded.Length > 672) { return false; } string[] array = encoded.Split(new char[1] { ';' }); if (array.Length > 32) { return false; } string[] array2 = array; for (int i = 0; i < array2.Length; i++) { if (!long.TryParse(array2[i], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result) || result == 0L || !creators.Add(result)) { return false; } } return true; } public static string Format(IEnumerable creators) { SortedSet sortedSet = new SortedSet(); foreach (long creator in creators) { if (creator == 0L || !sortedSet.Add(creator) || sortedSet.Count > 32) { throw new ArgumentException("Invalid or duplicate structure creator.", "creators"); } } return string.Join(";", sortedSet.Select((long value) => value.ToString(CultureInfo.InvariantCulture))); } } public sealed class CreatureOverrideParseResult { public Dictionary Blocked { get; } = new Dictionary(StringComparer.Ordinal); public List Warnings { get; } = new List(); } public static class CreatureOverrideParser { public static CreatureOverrideParseResult Parse(string? raw) { CreatureOverrideParseResult creatureOverrideParseResult = new CreatureOverrideParseResult(); if (string.IsNullOrWhiteSpace(raw)) { return creatureOverrideParseResult; } string[] array = raw.Split(new char[3] { ';', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length == 0) { continue; } int num = text.IndexOf('='); if (num <= 0 || num == text.Length - 1 || text.IndexOf('=', num + 1) >= 0) { creatureOverrideParseResult.Warnings.Add("'" + text + "' must be prefab=Allow or prefab=Block."); continue; } string text2 = text.Substring(0, num).Trim(); string text3 = text.Substring(num + 1).Trim(); if (text2.Length == 0 || (!text3.Equals("Allow", StringComparison.OrdinalIgnoreCase) && !text3.Equals("Block", StringComparison.OrdinalIgnoreCase))) { creatureOverrideParseResult.Warnings.Add("'" + text + "' must be prefab=Allow or prefab=Block."); continue; } if (creatureOverrideParseResult.Blocked.ContainsKey(text2)) { creatureOverrideParseResult.Warnings.Add("'" + text2 + "' appears more than once; the last value wins."); } creatureOverrideParseResult.Blocked[text2] = text3.Equals("Block", StringComparison.OrdinalIgnoreCase); } return creatureOverrideParseResult; } } public readonly struct Point2 { public double X { get; } public double Z { get; } public Point2(double x, double z) { X = x; Z = z; } } public sealed class FieldGeometry { private const double Epsilon = 1E-08; private readonly Point2[] _stones; private readonly double _minX; private readonly double _maxX; private readonly double _minZ; private readonly double _maxZ; public IReadOnlyList Stones => _stones; public bool IsCircle => _stones.Length == 2; public double MinX => _minX; public double MaxX => _maxX; public double MinZ => _minZ; public double MaxZ => _maxZ; public double Area { get { if (!IsCircle) { return Math.Abs(SignedArea(_stones)); } return Math.PI * DistanceSquared(_stones[0], _stones[1]) / 4.0; } } private FieldGeometry(Point2[] stones) { _stones = stones; if (stones.Length == 2) { Point2 point = Midpoint(stones[0], stones[1]); double num = Math.Sqrt(DistanceSquared(stones[0], stones[1])) / 2.0; _minX = point.X - num; _maxX = point.X + num; _minZ = point.Z - num; _maxZ = point.Z + num; return; } _minX = (_maxX = stones[0].X); _minZ = (_maxZ = stones[0].Z); for (int i = 1; i < stones.Length; i++) { _minX = Math.Min(_minX, stones[i].X); _maxX = Math.Max(_maxX, stones[i].X); _minZ = Math.Min(_minZ, stones[i].Z); _maxZ = Math.Max(_maxZ, stones[i].Z); } } public static bool TryCreate(IReadOnlyList stones, double maxSpan, double maxArea, out FieldGeometry? field, out string error) { field = null; error = string.Empty; if (stones == null || stones.Count < 2 || stones.Count > 8) { error = "A field requires two to eight stones."; return false; } if (maxSpan <= 0.0 || maxArea <= 0.0) { error = "Field limits must be positive."; return false; } Point2[] array = new Point2[stones.Count]; for (int i = 0; i < array.Length; i++) { array[i] = stones[i]; if (!IsFinite(array[i].X) || !IsFinite(array[i].Z)) { error = "Stone positions must be finite."; return false; } for (int j = 0; j < i; j++) { if (DistanceSquared(array[i], array[j]) <= 1E-08) { error = "Stones cannot occupy the same position."; return false; } } } for (int k = 0; k < array.Length; k++) { int num = ((array.Length == 2) ? 1 : ((k + 1) % array.Length)); if (DistanceSquared(array[k], array[num]) > maxSpan * maxSpan) { error = ((array.Length == 2) ? "The two stones exceed the maximum diameter." : "A polygon edge exceeds the maximum length."); return false; } } if (array.Length > 2) { if (CountCrossings(array) != 0) { error = "The polygon crosses itself."; return false; } if (Math.Abs(SignedArea(array)) <= 1E-08) { error = "The polygon has no area."; return false; } } FieldGeometry fieldGeometry = new FieldGeometry(array); if (fieldGeometry.Area > maxArea) { error = "The field exceeds the maximum area."; return false; } field = fieldGeometry; return true; } public bool Contains(Point2 point) { double num = Math.Sqrt(1E-08); if (point.X < _minX - num || point.X > _maxX + num || point.Z < _minZ - num || point.Z > _maxZ + num) { return false; } if (IsCircle) { return DistanceSquared(Midpoint(_stones[0], _stones[1]), point) <= DistanceSquared(_stones[0], _stones[1]) / 4.0 + 1E-08; } bool flag = false; int num2 = 0; int num3 = _stones.Length - 1; while (num2 < _stones.Length) { Point2 a = _stones[num3]; Point2 b = _stones[num2]; if (PointOnSegment(point, a, b)) { return true; } if (a.Z > point.Z != b.Z > point.Z && point.X < (b.X - a.X) * (point.Z - a.Z) / (b.Z - a.Z) + a.X) { flag = !flag; } num3 = num2++; } return flag; } public bool TrySteerOutside(Point2 position, Point2 requestedDirection, double detectionRange, int preferredSide, out Point2 direction, out double boundaryDistance) { direction = requestedDirection; boundaryDistance = double.PositiveInfinity; if (!TryGetOutwardNormal(position, detectionRange, out var outward, out boundaryDistance)) { return false; } double num = Math.Sqrt(requestedDirection.X * requestedDirection.X + requestedDirection.Z * requestedDirection.Z); if (num <= 1E-08) { return false; } double num2 = requestedDirection.X / num; double num3 = requestedDirection.Z / num; if (num2 * outward.X + num3 * outward.Z >= 0.0) { return false; } double num4 = 0.0 - outward.Z; double x = outward.X; int num5 = ((preferredSide >= 0) ? 1 : (-1)); double num6 = detectionRange * 0.75; double num7 = Math.Max(-0.4, Math.Min(0.4, (num6 - boundaryDistance) / num6)); double num8 = Math.Sqrt(1.0 + num7 * num7); direction = new Point2((outward.X * num7 + num4 * (double)num5) / num8, (outward.Z * num7 + x * (double)num5) / num8); return true; } private bool TryGetOutwardNormal(Point2 position, double detectionRange, out Point2 outward, out double distance) { outward = new Point2(0.0, 0.0); distance = double.PositiveInfinity; if (!IsFinite(position.X) || !IsFinite(position.Z) || !IsFinite(detectionRange) || detectionRange <= 0.0) { return false; } if (position.X < _minX - detectionRange || position.X > _maxX + detectionRange || position.Z < _minZ - detectionRange || position.Z > _maxZ + detectionRange) { return false; } if (IsCircle) { Point2 point = Midpoint(_stones[0], _stones[1]); double num = position.X - point.X; double num2 = position.Z - point.Z; double num3 = Math.Sqrt(num * num + num2 * num2); double num4 = Math.Sqrt(DistanceSquared(_stones[0], _stones[1])) / 2.0; distance = num3 - num4; if (distance <= 1E-08 || distance > detectionRange) { return false; } outward = new Point2(num / num3, num2 / num3); return true; } if (Contains(position)) { return false; } double num5 = detectionRange * detectionRange; bool flag = false; double num6 = 0.0; double num7 = 0.0; for (int i = 0; i < _stones.Length; i++) { Point2 point2 = ClosestPointOnSegment(position, _stones[i], _stones[(i + 1) % _stones.Length]); double num8 = position.X - point2.X; double num9 = position.Z - point2.Z; double num10 = num8 * num8 + num9 * num9; if (!(num10 > num5)) { num5 = num10; num6 = num8; num7 = num9; flag = true; } } if (!flag) { return false; } distance = Math.Sqrt(num5); if (distance <= 1E-08) { return false; } outward = new Point2(num6 / distance, num7 / distance); return true; } public double DistanceTo(Point2 point) { if (Contains(point)) { return 0.0; } if (IsCircle) { Point2 a = Midpoint(_stones[0], _stones[1]); double num = Math.Sqrt(DistanceSquared(_stones[0], _stones[1])) / 2.0; return Math.Max(0.0, Math.Sqrt(DistanceSquared(a, point)) - num); } double num2 = double.PositiveInfinity; for (int i = 0; i < _stones.Length; i++) { num2 = Math.Min(num2, DistanceToSegmentSquared(point, _stones[i], _stones[(i + 1) % _stones.Length])); } return Math.Sqrt(num2); } public double DistanceTo(FieldGeometry other) { if (Overlaps(other)) { return 0.0; } if (IsCircle && other.IsCircle) { Point2 a = Midpoint(_stones[0], _stones[1]); Point2 b = Midpoint(other._stones[0], other._stones[1]); double num = Math.Sqrt(DistanceSquared(_stones[0], _stones[1])) / 2.0; double num2 = Math.Sqrt(DistanceSquared(other._stones[0], other._stones[1])) / 2.0; return Math.Max(0.0, Math.Sqrt(DistanceSquared(a, b)) - num - num2); } if (IsCircle) { return CirclePolygonDistance(this, other); } if (other.IsCircle) { return CirclePolygonDistance(other, this); } double num3 = double.PositiveInfinity; Point2[] stones = _stones; foreach (Point2 point in stones) { num3 = Math.Min(num3, other.DistanceTo(point)); } stones = other._stones; foreach (Point2 point2 in stones) { num3 = Math.Min(num3, DistanceTo(point2)); } return num3; } private static double CirclePolygonDistance(FieldGeometry circle, FieldGeometry polygon) { Point2 p = Midpoint(circle._stones[0], circle._stones[1]); double num = Math.Sqrt(DistanceSquared(circle._stones[0], circle._stones[1])) / 2.0; double num2 = double.PositiveInfinity; for (int i = 0; i < polygon._stones.Length; i++) { num2 = Math.Min(num2, DistanceToSegmentSquared(p, polygon._stones[i], polygon._stones[(i + 1) % polygon._stones.Length])); } return Math.Max(0.0, Math.Sqrt(num2) - num); } public bool Overlaps(FieldGeometry other) { if (IsCircle && other.IsCircle) { double num = Math.Sqrt(DistanceSquared(_stones[0], _stones[1])) / 2.0; double num2 = Math.Sqrt(DistanceSquared(other._stones[0], other._stones[1])) / 2.0; double num3 = num + num2; return DistanceSquared(Midpoint(_stones[0], _stones[1]), Midpoint(other._stones[0], other._stones[1])) <= num3 * num3 + 1E-08; } if (IsCircle) { return CircleOverlapsPolygon(this, other); } if (other.IsCircle) { return CircleOverlapsPolygon(other, this); } Point2[] stones = _stones; foreach (Point2 point in stones) { if (other.Contains(point)) { return true; } } stones = other._stones; foreach (Point2 point2 in stones) { if (Contains(point2)) { return true; } } for (int j = 0; j < _stones.Length; j++) { for (int k = 0; k < other._stones.Length; k++) { if (SegmentsIntersect(_stones[j], _stones[(j + 1) % _stones.Length], other._stones[k], other._stones[(k + 1) % other._stones.Length])) { return true; } } } return false; } private static bool CircleOverlapsPolygon(FieldGeometry circle, FieldGeometry polygon) { Point2 point = Midpoint(circle._stones[0], circle._stones[1]); double num = DistanceSquared(circle._stones[0], circle._stones[1]) / 4.0; if (polygon.Contains(point)) { return true; } Point2[] stones = polygon._stones; foreach (Point2 point2 in stones) { if (circle.Contains(point2)) { return true; } } for (int j = 0; j < polygon._stones.Length; j++) { if (DistanceToSegmentSquared(point, polygon._stones[j], polygon._stones[(j + 1) % polygon._stones.Length]) <= num + 1E-08) { return true; } } return false; } private static double SignedArea(IReadOnlyList points) { double num = 0.0; for (int i = 0; i < points.Count; i++) { Point2 point = points[(i + 1) % points.Count]; num += points[i].X * point.Z - point.X * points[i].Z; } return num / 2.0; } internal static int CountCrossings(IReadOnlyList points) { int num = 0; for (int i = 0; i < points.Count; i++) { for (int j = i + 2; j < points.Count; j++) { if ((i != 0 || j != points.Count - 1) && SegmentsIntersect(points[i], points[(i + 1) % points.Count], points[j], points[(j + 1) % points.Count])) { num++; } } } return num; } private static Point2 Midpoint(Point2 a, Point2 b) { return new Point2((a.X + b.X) / 2.0, (a.Z + b.Z) / 2.0); } private static double DistanceSquared(Point2 a, Point2 b) { return (a.X - b.X) * (a.X - b.X) + (a.Z - b.Z) * (a.Z - b.Z); } private static bool IsFinite(double x) { if (!double.IsNaN(x)) { return !double.IsInfinity(x); } return false; } private static double Cross(Point2 a, Point2 b, Point2 c) { return (b.X - a.X) * (c.Z - a.Z) - (b.Z - a.Z) * (c.X - a.X); } private static bool PointOnSegment(Point2 p, Point2 a, Point2 b) { if (Math.Abs(Cross(a, b, p)) <= 1E-08 && p.X >= Math.Min(a.X, b.X) - 1E-08 && p.X <= Math.Max(a.X, b.X) + 1E-08 && p.Z >= Math.Min(a.Z, b.Z) - 1E-08) { return p.Z <= Math.Max(a.Z, b.Z) + 1E-08; } return false; } private static bool SegmentsIntersect(Point2 a, Point2 b, Point2 c, Point2 d) { double num = Cross(a, b, c); double num2 = Cross(a, b, d); double num3 = Cross(c, d, a); double num4 = Cross(c, d, b); if (num * num2 < -1E-08 && num3 * num4 < -1E-08) { return true; } if (!PointOnSegment(c, a, b) && !PointOnSegment(d, a, b) && !PointOnSegment(a, c, d)) { return PointOnSegment(b, c, d); } return true; } private static double DistanceToSegmentSquared(Point2 p, Point2 a, Point2 b) { return DistanceSquared(p, ClosestPointOnSegment(p, a, b)); } private static Point2 ClosestPointOnSegment(Point2 p, Point2 a, Point2 b) { double num = b.X - a.X; double num2 = b.Z - a.Z; double num3 = num * num + num2 * num2; if (num3 <= 1E-08) { return a; } double num4 = Math.Max(0.0, Math.Min(1.0, ((p.X - a.X) * num + (p.Z - a.Z) * num2) / num3)); return new Point2(a.X + num4 * num, a.Z + num4 * num2); } } public static class PolygonOrdering { public static int[] Untangle(IReadOnlyList stones) { if (stones == null) { throw new ArgumentNullException("stones"); } int[] array = new int[stones.Count]; for (int i = 0; i < array.Length; i++) { array[i] = i; } if (array.Length < 4) { return array; } for (int j = 0; j < array.Length * array.Length; j++) { int num = FieldGeometry.CountCrossings(Points(stones, array)); if (num == 0) { break; } int[] array2 = null; int num2 = num; for (int k = 0; k < array.Length; k++) { for (int l = k + 2; l < array.Length; l++) { if (k != 0 || l != array.Length - 1) { int[] array3 = (int[])array.Clone(); Array.Reverse((Array)array3, k + 1, l - k); int num3 = FieldGeometry.CountCrossings(Points(stones, array3)); if (num3 < num2) { array2 = array3; num2 = num3; } } } } if (array2 == null) { break; } array = array2; } return array; } private static Point2[] Points(IReadOnlyList stones, int[] order) { Point2[] array = new Point2[order.Length]; for (int i = 0; i < order.Length; i++) { array[i] = stones[order[i]]; } return array; } public static IReadOnlyList FourthStoneInsertions(IReadOnlyList stones) { if (stones == null || stones.Count != 4) { throw new ArgumentException("Exactly four stone positions are required.", "stones"); } List<(int[], double)> list = new List<(int[], double)>(); for (int i = 0; i < 4; i++) { int[] array = new int[4]; int num = 0; for (int j = 0; j < 4; j++) { array[j] = ((j == i) ? 3 : num++); } Point2 a = stones[(i + 2) % 3]; Point2 b = stones[i % 3]; double item = Distance(a, stones[3]) + Distance(stones[3], b) - Distance(a, b); list.Add((array, item)); } list.Sort(((int[] Order, double AddedPerimeter) left, (int[] Order, double AddedPerimeter) right) => left.AddedPerimeter.CompareTo(right.AddedPerimeter)); int[][] array2 = new int[4][]; for (int num2 = 0; num2 < array2.Length; num2++) { array2[num2] = list[num2].Item1; } return array2; } private static double Distance(Point2 a, Point2 b) { double num = a.X - b.X; double num2 = a.Z - b.Z; return Math.Sqrt(num * num + num2 * num2); } } public enum SpawnSource { Biome, Raid, LocationPoint, PhysicalSpawner, BossSummon } public enum LocationPointRule { MatchWorkbench, Block, Allow } public enum PhysicalSpawnerRule { Allow, Block } public sealed class SpawnPolicy { private readonly Dictionary _biomeCreatureBlocked = new Dictionary(StringComparer.Ordinal); public LocationPointRule LocationPoints { get; set; } public PhysicalSpawnerRule PhysicalSpawners { get; set; } public void SetBiomeCreatureBlocked(string prefabName, bool blocked) { if (string.IsNullOrWhiteSpace(prefabName)) { throw new ArgumentException("A prefab name is required.", "prefabName"); } _biomeCreatureBlocked[prefabName] = blocked; } public bool ShouldBlock(SpawnSource source, string? prefabName = null, bool locationAllowsPlayerBase = false) { switch (source) { case SpawnSource.Biome: { bool value = default(bool); return prefabName == null || !_biomeCreatureBlocked.TryGetValue(prefabName, out value) || value; } case SpawnSource.Raid: return true; case SpawnSource.LocationPoint: if (LocationPoints != LocationPointRule.Block) { if (LocationPoints == LocationPointRule.MatchWorkbench) { return !locationAllowsPlayerBase; } return false; } return true; case SpawnSource.PhysicalSpawner: return PhysicalSpawners == PhysicalSpawnerRule.Block; case SpawnSource.BossSummon: return false; default: throw new ArgumentOutOfRangeException("source"); } } } public static class StoneAlignment { public const int Directions = 16; public static bool TrySnap(Point2 origin, Point2 candidate, out Point2 snapped) { snapped = candidate; double num = candidate.X - origin.X; double num2 = candidate.Z - origin.Z; if (num * num + num2 * num2 < 1E-06) { return false; } double num3 = Math.PI / 8.0; double num4 = Math.Round(Math.Atan2(num2, num) / num3) * num3; double num5 = Math.Cos(num4); double num6 = Math.Sin(num4); double num7 = num * num5 + num2 * num6; snapped = new Point2(origin.X + num7 * num5, origin.Z + num7 * num6); return true; } public static bool TrySnapCorner(Point2 selected, Point2 last, Point2 candidate, double maxSpan, out Point2 snapped) { snapped = candidate; if (maxSpan <= 0.0 || Math.Abs(selected.X - last.X) + Math.Abs(selected.Z - last.Z) < 1E-06) { return false; } double num = last.X - selected.X; double num2 = last.Z - selected.Z; double num3 = Math.Min(5.0, Math.Max(2.0, maxSpan * 0.1)); double num4 = num3 * num3 + 1E-09; bool result = false; double num5 = Math.PI / 8.0; for (int i = 0; i < 16; i++) { double num6 = Math.Cos((double)i * num5); double num7 = Math.Sin((double)i * num5); for (int j = 0; j < 16; j++) { double num8 = Math.Cos((double)j * num5); double num9 = Math.Sin((double)j * num5); double num10 = num6 * num9 - num7 * num8; if (Math.Abs(num10) < 1E-06) { continue; } double num11 = (num * num9 - num2 * num8) / num10; double num12 = (num * num7 - num2 * num6) / num10; if (!(num11 < 0.5) && !(num12 < 0.5) && !(num11 > maxSpan + 1E-06)) { Point2 point = new Point2(selected.X + num11 * num6, selected.Z + num11 * num7); double num13 = point.X - candidate.X; double num14 = point.Z - candidate.Z; double num15 = num13 * num13 + num14 * num14; if (!(num15 >= num4)) { num4 = num15; snapped = point; result = true; } } } } return result; } public static bool TrySnapCorner(Point2 selected, IReadOnlyList draftStones, Point2 candidate, double maxSpan, out Point2 snapped) { snapped = candidate; bool result = false; double num = double.PositiveInfinity; foreach (Point2 draftStone in draftStones) { if (TrySnapCorner(selected, draftStone, candidate, maxSpan, out var snapped2)) { double num2 = snapped2.X - candidate.X; double num3 = snapped2.Z - candidate.Z; double num4 = num2 * num2 + num3 * num3; if (!(num4 >= num)) { num = num4; snapped = snapped2; result = true; } } } return result; } } } namespace BaseProtection.Plugin { public enum BoundaryDisplayMode { AlwaysShow, ShowWithHammer, NeverShow } [BepInPlugin("valheim.runestone.baseprotection", "Runestone Base Protection", "1.1.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public sealed class BaseProtectionPlugin : BaseUnityPlugin { public const string ModGuid = "valheim.runestone.baseprotection"; public const string ModName = "Runestone Base Protection"; public const string ModVersion = "1.1.2"; public const string StonePrefabName = "piece_baseprotection_runestone"; public const int StoneCost = 10; internal static BaseProtectionPlugin Instance; private Harmony? _harmony; private SoftReference? _traderRuneReference; private Piece? _stonePiece; private bool _featuresWereAvailable; private float _nextRefresh; private string _lastLimitWarning = ""; internal ConfigEntry MaxEdge; internal ConfigEntry MaxArea; internal ConfigEntry FieldGap; internal ConfigEntry ForeignStructureBuffer; internal ConfigEntry MaxFieldsPerPlayer; internal ConfigEntry MaxTotalAreaPerPlayer; internal ConfigEntry LocationPoints; internal ConfigEntry PhysicalSpawners; internal ConfigEntry BiomeCreatureOverrides; internal ConfigEntry FieldProvidesWorkbenchBuilding; internal ConfigEntry FieldProvidesForgeBuilding; internal ConfigEntry FieldProvidesStonecutterBuilding; internal ConfigEntry FieldProvidesArtisanTableBuilding; internal ConfigEntry FieldProvidesBlackForgeBuilding; internal ConfigEntry PreventRainWearInFields; internal ConfigEntry RepelHostileMobs; internal ConfigEntry BoundaryVisibility; internal static bool FeaturesAvailable { get { if ((Object)(object)ZNet.instance != (Object)null) { if (!ZNet.instance.IsServer()) { return ModCompatibility.IsModuleOnServer("valheim.runestone.baseprotection"); } return true; } return false; } } internal void LogInfo(string message) { ((BaseUnityPlugin)this).Logger.LogInfo((object)message); } internal void LogError(Exception error) { ((BaseUnityPlugin)this).Logger.LogError((object)error); } internal void LogWarning(string message) { ((BaseUnityPlugin)this).Logger.LogWarning((object)message); } private void Awake() { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown Instance = this; MigratePreviousConfiguration(); BindConfiguration(); ((BaseUnityPlugin)this).Config.SettingChanged += delegate { ValidateConfigRelationships(); }; ValidateConfigRelationships(); PrefabManager.OnVanillaPrefabsAvailable += RegisterStone; _harmony = new Harmony("valheim.runestone.baseprotection"); _harmony.PatchAll(typeof(BaseProtectionPlugin).Assembly); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Runestone Base Protection 1.1.2 loaded"); } private void MigratePreviousConfiguration() { string text = Path.Combine(Paths.ConfigPath, "fearl.valheim.baseprotection.cfg"); string configFilePath = ((BaseUnityPlugin)this).Config.ConfigFilePath; if (File.Exists(configFilePath) || !File.Exists(text)) { return; } try { File.Move(text, configFilePath); try { ((BaseUnityPlugin)this).Config.Reload(); } catch { File.Move(configFilePath, text); throw; } ((BaseUnityPlugin)this).Logger.LogInfo((object)("Renamed existing settings to " + Path.GetFileName(configFilePath) + ".")); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not rename the existing settings file: " + ex.Message)); } } private void Update() { NetworkCommands.CheckPendingLink(); NetworkCommands.CheckPendingRemove(); StoneRepairCommands.CheckPending(); bool featuresAvailable = FeaturesAvailable; if ((Object)(object)_stonePiece != (Object)null) { _stonePiece.m_enabled = featuresAvailable; } if (!featuresAvailable) { if (_featuresWereAvailable) { FieldVisuals.Clear(); FieldRegistry.ClearCachedFields(); RunestoneInteraction.ClearSelection(); } _featuresWereAvailable = false; return; } _featuresWereAvailable = true; RunestoneInteraction.UpdateSelectionCache(); NetworkCommands.TryRegister(); StoneRepairCommands.TryRegister(); bool flag = BoundaryVisibility.Value switch { BoundaryDisplayMode.AlwaysShow => true, BoundaryDisplayMode.NeverShow => false, _ => ShouldShowBoundary(), }; FieldVisuals.SetVisibility(flag); if (!(Time.time < _nextRefresh)) { _nextRefresh = Time.time + 1f; StoneAccess.AdoptServerOwnership(); FieldRegistry.Refresh(); FieldVisuals.Refresh(FieldRegistry.VisibleOutlines, flag); } } private static bool ShouldShowBoundary() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || !((Character)localPlayer).InPlaceMode()) { return false; } ItemData rightItem = ((Humanoid)localPlayer).RightItem; object obj; if (rightItem == null) { obj = null; } else { GameObject dropPrefab = rightItem.m_dropPrefab; obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null); } return (string?)obj == "Hammer"; } private void OnDestroy() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) PrefabManager.OnVanillaPrefabsAvailable -= RegisterStone; Harmony? harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } FieldVisuals.Clear(); _traderRuneReference?.Release(); } private void BindConfiguration() { MaxEdge = ((BaseUnityPlugin)this).Config.Bind("Fields", "Maximum edge length (m)", 200f, Description("Maximum length of a finalized polygon edge, or the diameter of a two-stone circle.", (AcceptableValueBase?)(object)new SafeFloatRange(1f, 10000f, 200f))); MaxArea = ((BaseUnityPlugin)this).Config.Bind("Fields", "Maximum area (m2)", 40000f, Description("Largest area one finalized field may cover.", (AcceptableValueBase?)(object)new SafeFloatRange(1f, 100000000f, 40000f))); FieldGap = ((BaseUnityPlugin)this).Config.Bind("Fields", "Minimum field gap (m)", 5f, Description("Minimum separation between active fields; 0 removes extra clearance, but touching boundaries still count as overlap.", (AcceptableValueBase?)(object)new SafeFloatRange(0f, 10000f, 5f))); ForeignStructureBuffer = ((BaseUnityPlugin)this).Config.Bind("Anti-grief", "Foreign structure buffer (m)", 20f, Description("A field cannot approach another player's structures closer than this; 0 disables the buffer.", (AcceptableValueBase?)(object)new SafeFloatRange(0f, 10000f, 20f))); MaxFieldsPerPlayer = ((BaseUnityPlugin)this).Config.Bind("Anti-grief", "Maximum fields per player", 4, Description("Maximum active fields owned by one player; 0 prevents activation.", (AcceptableValueBase?)(object)new SafeIntegerRange(0, 1000))); MaxTotalAreaPerPlayer = ((BaseUnityPlugin)this).Config.Bind("Anti-grief", "Maximum total area per player (m2)", 160000f, Description("Maximum combined area of one player's active fields; 0 prevents activation.", (AcceptableValueBase?)(object)new SafeFloatRange(0f, 1E+09f, 160000f))); LocationPoints = ((BaseUnityPlugin)this).Config.Bind("Spawning", "Location spawn points", LocationPointRule.MatchWorkbench, Description("MatchWorkbench honors each location point's spawnInPlayerBase flag. Does not control physical spawner objects.")); PhysicalSpawners = ((BaseUnityPlugin)this).Config.Bind("Spawning", "Physical spawner objects", PhysicalSpawnerRule.Allow, Description("Controls destructible spawners such as nests and bone piles; Allow matches workbench behavior.")); BiomeCreatureOverrides = ((BaseUnityPlugin)this).Config.Bind("Spawning", "Biome creature overrides", "", Description("Optional semicolon-separated prefab=Allow or prefab=Block entries, e.g. Boar=Allow;Goblin=Allow. Use exact internal prefab names. Unlisted biome creatures are blocked; raids are unaffected by this list.")); FieldProvidesWorkbenchBuilding = ((BaseUnityPlugin)this).Config.Bind("Building", "Field provides workbench building range", false, Description("If true, standing inside an active field provides workbench range for hammer placement, removal, and structure repair, including targets just outside the field. Item crafting, item repair, and placing station upgrades still require a real station.")); FieldProvidesForgeBuilding = BindBuildStation("forge"); FieldProvidesStonecutterBuilding = BindBuildStation("stonecutter"); FieldProvidesArtisanTableBuilding = BindBuildStation("artisan table"); FieldProvidesBlackForgeBuilding = BindBuildStation("black forge"); PreventRainWearInFields = ((BaseUnityPlugin)this).Config.Bind("Building", "Prevent rain and water wear inside active fields", false, Description("If true, exposed structures inside an active field do not weather from rain or water. This does not repair existing damage or prevent attacks, support failure, snow, ash, or lava damage.")); RepelHostileMobs = ((BaseUnityPlugin)this).Config.Bind("Defense", "Repel ordinary hostile creatures", false, Description("If true, ordinary hostile creatures approaching an active field turn away at its boundary. Bosses, raid creatures, tamed creatures, and creatures already inside a field are unaffected. This changes AI movement; it is not a physical barrier.")); BoundaryVisibility = ((BaseUnityPlugin)this).Config.Bind("Visuals", "Boundary visibility", BoundaryDisplayMode.ShowWithHammer, "Client-only display preference: always show field outlines, show them only with the build hammer, or never show them."); ConfigEntry BindBuildStation(string stationName) { return ((BaseUnityPlugin)this).Config.Bind("Building", "Field provides " + stationName + " building range", false, Description("If true, standing inside an active field satisfies the " + stationName + " range requirement for hammer placement, removal, and structure repair. Item crafting, item repair, and placing station upgrades still require a real station.")); } static ConfigDescription Description(string text, AcceptableValueBase? accepted = null) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown return new ConfigDescription(text, accepted, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true, IsAdvanced = false } }); } } private void ValidateConfigRelationships() { string text = ((MaxTotalAreaPerPlayer.Value < MaxArea.Value) ? "Maximum total area per player is smaller than maximum area per field; the per-player limit will be the effective cap." : ""); if (!(text == _lastLimitWarning)) { _lastLimitWarning = text; if (text.Length != 0) { ((BaseUnityPlugin)this).Logger.LogWarning((object)text); } } } private static void RegisterStone() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_015d: Unknown result type (might be due to invalid IL or missing references) PieceConfig val = new PieceConfig { Name = "Linked Runestone", Description = "Select a stone, then hold Ctrl while placing to align or snap a corner. Link two to eight stones; Shift+E to finish.", PieceTable = PieceTables.Hammer, CraftingStation = CraftingStations.Workbench, Category = PieceCategories.Misc }; val.AddRequirement("Stone", 10, true); CustomPiece val2 = new CustomPiece("piece_baseprotection_runestone", "guard_stone_test", val); GameObject piecePrefab = val2.PiecePrefab; PrivateArea[] componentsInChildren = piecePrefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } EffectArea[] componentsInChildren2 = piecePrefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren2.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren2[i]); } CircleProjector[] componentsInChildren3 = piecePrefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren3.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren3[i]); } WearNTear component = piecePrefab.GetComponent(); if ((Object)(object)component != (Object)null) { component.m_noRoofWear = false; component.m_autoCreateFragments = true; component.m_fragmentRoots = Array.Empty(); } Instance.UseTraderRuneVisual(piecePrefab); StaticTarget[] componentsInChildren4 = piecePrefab.GetComponentsInChildren(true); foreach (StaticTarget obj in componentsInChildren4) { obj.m_primaryTarget = false; obj.m_randomTarget = false; } piecePrefab.AddComponent(); AddSnapPoints(piecePrefab); val2.Piece.m_targetNonPlayerBuilt = false; if (!Application.isBatchMode) { try { Sprite val3 = RenderManager.Instance.Render(piecePrefab, RenderManager.IsometricRotation); if ((Object)(object)val3 != (Object)null) { val2.Piece.m_icon = val3; } else { ((BaseUnityPlugin)Instance).Logger.LogWarning((object)"Could not render the runestone icon; using the prefab icon."); } } catch (Exception arg) { ((BaseUnityPlugin)Instance).Logger.LogWarning((object)$"Could not render the runestone icon: {arg}"); } } PieceManager.Instance.AddPiece(val2); Instance._stonePiece = val2.Piece; PrefabManager.OnVanillaPrefabsAvailable -= RegisterStone; ((BaseUnityPlugin)Instance).Logger.LogInfo((object)"Registered linked runestone piece"); } private void UseTraderRuneVisual(GameObject prefab) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) try { if (!AssetManager.Instance.IsReady()) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"TraderRune assets are not ready; retaining the original stone visual."); return; } SoftReference softReference = AssetManager.Instance.GetSoftReference("TraderRune"); if (!softReference.IsValid) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"TraderRune prefab was not found; retaining the original stone visual."); return; } softReference.Load(); softReference.HoldReference(); _traderRuneReference = softReference; GameObject asset = softReference.Asset; if ((Object)(object)asset == (Object)null || asset.GetComponentsInChildren(true).Length == 0) { ((BaseUnityPlugin)this).Logger.LogWarning((object)"TraderRune has no visible mesh; retaining the original stone visual."); return; } Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].enabled = false; } ParticleSystem[] componentsInChildren2 = prefab.GetComponentsInChildren(true); foreach (ParticleSystem obj in componentsInChildren2) { obj.Stop(true, (ParticleSystemStopBehavior)0); EmissionModule emission = obj.emission; ((EmissionModule)(ref emission)).enabled = false; } GameObject val = CopyTraderVisual(asset.transform, prefab.transform); WearNTear component = prefab.GetComponent(); if ((Object)(object)component != (Object)null) { component.m_fragmentRoots = (GameObject[])(object)new GameObject[1] { val }; } ((BaseUnityPlugin)this).Logger.LogInfo((object)"Using the trader barrier runestone visual."); } catch (Exception arg) { ((BaseUnityPlugin)this).Logger.LogError((object)$"Could not use the TraderRune visual: {arg}"); } } private static GameObject CopyTraderVisual(Transform source, Transform destination) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown GameObject val = new GameObject("TraderRuneVisual_" + ((Object)source).name); val.transform.SetParent(destination, false); val.transform.localPosition = (((Object)(object)source.parent == (Object)null) ? Vector3.zero : source.localPosition); val.transform.localRotation = (((Object)(object)source.parent == (Object)null) ? Quaternion.identity : source.localRotation); val.transform.localScale = (((Object)(object)source.parent == (Object)null) ? Vector3.one : source.localScale); MeshFilter component = ((Component)source).GetComponent(); MeshRenderer component2 = ((Component)source).GetComponent(); if ((Object)(object)component != (Object)null && (Object)(object)component2 != (Object)null) { val.AddComponent().sharedMesh = component.sharedMesh; MeshRenderer obj = val.AddComponent(); ((Renderer)obj).sharedMaterials = ((Renderer)component2).sharedMaterials; ((Renderer)obj).shadowCastingMode = ((Renderer)component2).shadowCastingMode; ((Renderer)obj).receiveShadows = ((Renderer)component2).receiveShadows; } foreach (Transform item in source) { CopyTraderVisual(item, val.transform); } return val; } private static void AddSnapPoints(GameObject prefab) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) int num = LayerMask.NameToLayer("piece_nonsolid"); if (num >= 0) { GameObject val = new GameObject("BaseProtectionSnapDetector"); val.transform.SetParent(prefab.transform, false); val.layer = num; BoxCollider obj = val.AddComponent(); obj.center = new Vector3(0f, 0.7f, 0f); obj.size = new Vector3(1.5f, 1.4f, 1.5f); } else { ((BaseUnityPlugin)Instance).Logger.LogWarning((object)"piece_nonsolid layer unavailable; nearby piece snapping may fail."); } Vector3[] array = (Vector3[])(object)new Vector3[4] { new Vector3(-0.75f, 0f, -0.75f), new Vector3(0.75f, 0f, -0.75f), new Vector3(0.75f, 0f, 0.75f), new Vector3(-0.75f, 0f, 0.75f) }; for (int i = 0; i <= array.Length; i++) { GameObject val2 = new GameObject((i == 0) ? "Center" : $"Corner {i}") { tag = "snappoint" }; val2.transform.SetParent(prefab.transform, false); val2.transform.localPosition = ((i == 0) ? Vector3.zero : array[i - 1]); } } } internal static class VirtualBuildStationContext { [ThreadStatic] internal static CraftingStation? Station; [ThreadStatic] internal static bool RemovingPiece; [ThreadStatic] internal static bool RepairingPiece; private static bool MatchesEnabledStation(CraftingStation required, string prefabName, ConfigEntry enabled) { if (!enabled.Value) { return false; } GameObject prefab = PrefabManager.Instance.GetPrefab(prefabName); CraftingStation val = ((prefab != null) ? prefab.GetComponent() : null); if ((Object)(object)val != (Object)null) { return required.m_name == val.m_name; } return false; } private static bool HasEnabledRequirement(Piece piece) { CraftingStation val = piece?.m_craftingStation; if ((Object)(object)val == (Object)null) { return false; } BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; if (!MatchesEnabledStation(val, CraftingStations.Workbench, instance.FieldProvidesWorkbenchBuilding) && !MatchesEnabledStation(val, CraftingStations.Forge, instance.FieldProvidesForgeBuilding) && !MatchesEnabledStation(val, CraftingStations.Stonecutter, instance.FieldProvidesStonecutterBuilding) && !MatchesEnabledStation(val, CraftingStations.ArtisanTable, instance.FieldProvidesArtisanTableBuilding)) { return MatchesEnabledStation(val, CraftingStations.BlackForge, instance.FieldProvidesBlackForgeBuilding); } return true; } internal static CraftingStation? For(Player player, Piece piece, RequirementMode mode) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0033: Unknown result type (might be due to invalid IL or missing references) if ((int)mode == 1 || (Object)(object)piece == (Object)null || piece.m_isUpgrade || (Object)(object)((Component)piece).GetComponent() != (Object)null || !HasEnabledRequirement(piece)) { return null; } if (!FieldRegistry.Contains(((Component)player).transform.position)) { return null; } return piece.m_craftingStation; } internal static bool CanMaintain(Player player, Piece piece) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) if ((RemovingPiece || RepairingPiece) && HasEnabledRequirement(piece)) { return FieldRegistry.Contains(((Component)player).transform.position); } return false; } } [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Piece), typeof(RequirementMode) })] internal static class BuildingRequirementPatch { private static void Prefix(Player __instance, Piece piece, RequirementMode mode, out CraftingStation? __state) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) __state = VirtualBuildStationContext.Station; VirtualBuildStationContext.Station = VirtualBuildStationContext.For(__instance, piece, mode); } private static void Postfix(CraftingStation? __state) { VirtualBuildStationContext.Station = __state; } private static Exception? Finalizer(Exception? __exception, CraftingStation? __state) { VirtualBuildStationContext.Station = __state; return __exception; } } [HarmonyPatch(typeof(CraftingStation), "HaveBuildStationInRange")] internal static class VirtualBuildStationPatch { private static void Postfix(string name, ref CraftingStation __result) { CraftingStation station = VirtualBuildStationContext.Station; if ((Object)(object)__result == (Object)null && (Object)(object)station != (Object)null && station.m_name == name) { __result = station; } } } [HarmonyPatch(typeof(Player), "RemovePiece")] internal static class VirtualBuildStationRemoveContextPatch { private static void Prefix(out bool __state) { __state = VirtualBuildStationContext.RemovingPiece; VirtualBuildStationContext.RemovingPiece = true; RunestoneRemoveRoutingPatch.RequestRejected = false; } private static void Postfix(bool __state, ref bool __result) { if (RunestoneRemoveRoutingPatch.RequestRejected) { __result = false; } RunestoneRemoveRoutingPatch.RequestRejected = false; VirtualBuildStationContext.RemovingPiece = __state; } private static Exception? Finalizer(Exception? __exception, bool __state) { RunestoneRemoveRoutingPatch.RequestRejected = false; VirtualBuildStationContext.RemovingPiece = __state; return __exception; } } [HarmonyPatch(typeof(Player), "Repair", new Type[] { typeof(ItemData), typeof(Piece) })] internal static class VirtualBuildStationRepairContextPatch { private static void Prefix(out bool __state) { __state = VirtualBuildStationContext.RepairingPiece; VirtualBuildStationContext.RepairingPiece = true; } private static void Postfix(bool __state) { VirtualBuildStationContext.RepairingPiece = __state; } private static Exception? Finalizer(Exception? __exception, bool __state) { VirtualBuildStationContext.RepairingPiece = __state; return __exception; } } [HarmonyPatch(typeof(Player), "CheckCanRemovePiece", new Type[] { typeof(Piece) })] internal static class VirtualBuildStationMaintainCheckPatch { private static bool Prefix(Player __instance, Piece piece, ref bool __result) { if (VirtualBuildStationContext.RemovingPiece && StoneAccess.IsStone((Component)(object)piece) && !StoneAccess.CanLocalEdit(__instance, piece)) { __result = false; RunestoneInteraction.Notify("Only the stone owner or a server admin can remove it."); return false; } if (VirtualBuildStationContext.RemovingPiece && StoneAccess.IsStone((Component)(object)piece) && !NetworkCommands.CanRequestRemove()) { __result = false; RunestoneInteraction.Notify("Cannot reach the server to remove this runestone yet."); return false; } if (VirtualBuildStationContext.RemovingPiece && StoneAccess.IsStone((Component)(object)piece) && NetworkCommands.IsRemovePending(piece)) { __result = false; RunestoneInteraction.Notify("Runestone removal is already being processed."); return false; } if (!VirtualBuildStationContext.CanMaintain(__instance, piece)) { return true; } __result = true; return false; } } [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] internal static class BuildingRequirementHudPatch { private static void Postfix(Hud __instance, Piece piece) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)piece == (Object)null || (Object)(object)VirtualBuildStationContext.For(localPlayer, piece, (RequirementMode)2) == (Object)null) { return; } int num = piece.m_resources.Length; GameObject[] requirementItems = __instance.m_requirementItems; if (num >= requirementItems.Length || (Object)(object)requirementItems[num] == (Object)null) { return; } Transform transform = requirementItems[num].transform; Transform obj = transform.Find("res_amount"); TMP_Text val = ((obj != null) ? ((Component)obj).GetComponent() : null); if (!((Object)(object)val == (Object)null) && !(val.text != Localization.instance.Localize("$menu_none"))) { val.text = "Runestone"; ((Graphic)val).color = Color.white; Transform obj2 = transform.Find("res_icon"); Image val2 = ((obj2 != null) ? ((Component)obj2).GetComponent() : null); if ((Object)(object)val2 != (Object)null) { ((Graphic)val2).color = Color.white; } } } } internal sealed class ActiveField { internal string GroupId = ""; internal long OwnerId; internal FieldGeometry Geometry; internal Vector3[] Vertices; } internal sealed class FieldOutline { internal string GroupId = ""; internal Point2[] Stones; internal bool IsDraft; } internal static class FieldRegistry { internal const string GroupKey = "baseprotection_group"; internal const string OrderKey = "baseprotection_order"; internal const string ActiveKey = "baseprotection_active"; internal const string ShapeKey = "baseprotection_shape"; internal const string ConsentKey = "baseprotection_consents"; private static readonly HashSet LoadedStones = new HashSet(); private static readonly List Fields = new List(); private static readonly List Outlines = new List(); private static readonly List ServerFields = new List(); private static bool _hasServerSnapshot; internal static IReadOnlyList ActiveFields => Fields; internal static IReadOnlyList VisibleOutlines => Outlines; internal static bool HasServerSnapshot => _hasServerSnapshot; internal static void ClearCachedFields() { Fields.Clear(); Outlines.Clear(); ClearServerSnapshot(); } internal static void ClearServerSnapshot() { ServerFields.Clear(); _hasServerSnapshot = false; Fields.Clear(); } internal static void ApplyServerSnapshot(IReadOnlyList fields) { ServerFields.Clear(); ServerFields.AddRange(fields); _hasServerSnapshot = true; if (!((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsServer()) { Fields.Clear(); Fields.AddRange(ServerFields); } } internal static bool TryGetGroupOutline(string group, out Point2[] points) { foreach (FieldOutline outline in Outlines) { if (outline.GroupId == group) { points = outline.Stones; return true; } } points = Array.Empty(); return false; } internal static void Add(RunestoneInteraction stone) { LoadedStones.Add(stone); } internal static void Remove(RunestoneInteraction stone) { LoadedStones.Remove(stone); } internal static void Refresh() { //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0357: Unknown result type (might be due to invalid IL or missing references) Fields.Clear(); Outlines.Clear(); if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null) { return; } Dictionary> dictionary = new Dictionary>(StringComparer.Ordinal); RunestoneInteraction[] array = LoadedStones.ToArray(); foreach (RunestoneInteraction runestoneInteraction in array) { if ((Object)(object)runestoneInteraction == (Object)null) { continue; } ZNetView component = ((Component)runestoneInteraction).GetComponent(); ZDO val = ((component != null) ? component.GetZDO() : null); if (val == null) { continue; } string text = val.GetString("baseprotection_group", ""); if (!string.IsNullOrEmpty(text)) { if (!dictionary.TryGetValue(text, out var value)) { value = (dictionary[text] = new List()); } value.Add(val); } } foreach (KeyValuePair> item in dictionary) { Point2[] points2; ZDO val2 = ((IEnumerable)item.Value).FirstOrDefault((Func)((ZDO z) => TryDecodeShape(z.GetString("baseprotection_shape", ""), out points2))); if (val2 != null && TryDecodeShape(val2.GetString("baseprotection_shape", ""), out Point2[] points)) { bool flag = val2.GetInt("baseprotection_active", 1) == 0; Outlines.Add(new FieldOutline { GroupId = item.Key, Stones = points, IsDraft = flag }); if (!flag && FieldGeometry.TryCreate(points, BaseProtectionPlugin.Instance.MaxEdge.Value, BaseProtectionPlugin.Instance.MaxArea.Value, out FieldGeometry field, out string _)) { Fields.Add(new ActiveField { GroupId = item.Key, OwnerId = val2.GetLong(ZDOVars.s_creator, 0L), Geometry = field, Vertices = item.Value.Select((ZDO z) => z.GetPosition()).ToArray() }); } } else { ActiveField activeField = Build(item.Key, item.Value); if (activeField != null) { Fields.Add(activeField); Outlines.Add(new FieldOutline { GroupId = item.Key, Stones = activeField.Geometry.Stones.ToArray(), IsDraft = false }); } } } if (ZNet.instance.IsServer()) { Fields.Clear(); Fields.AddRange(BuildAll(GetAllStoneZdos())); NetworkCommands.PublishFieldSnapshot(Fields); } else { if (!_hasServerSnapshot) { return; } Fields.Clear(); Fields.AddRange(ServerFields); HashSet activeGroups = new HashSet(ServerFields.Select((ActiveField activeField2) => activeField2.GroupId), StringComparer.Ordinal); Outlines.RemoveAll((FieldOutline outline) => !outline.IsDraft || activeGroups.Contains(outline.GroupId)); Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer != (Object)null)) { return; } Vector3 position = ((Component)localPlayer).transform.position; Point2 point = new Point2(position.x, position.z); foreach (ActiveField serverField in ServerFields) { if (serverField.Geometry.DistanceTo(point) <= 128.0) { Outlines.Add(new FieldOutline { GroupId = serverField.GroupId, Stones = serverField.Geometry.Stones.ToArray(), IsDraft = false }); } } } } internal static ActiveField? Build(string group, IReadOnlyList zdos) { if (zdos.Count < 2 || zdos.Count > 8 || zdos.Any((ZDO z) => z.GetInt("baseprotection_active", 1) == 0)) { return null; } ZDO[] array = zdos.OrderBy((ZDO z) => z.GetInt("baseprotection_order", -1)).ToArray(); long owner = array[0].GetLong(ZDOVars.s_creator, 0L); if (owner == 0L || array.Any((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != owner)) { return null; } string approvals = array[0].GetString("baseprotection_consents", ""); if (!CreatorConsent.TryParse(approvals, out HashSet _) || array.Any((ZDO z) => z.GetString("baseprotection_consents", "") != approvals)) { return null; } for (int num = 0; num < array.Length; num++) { int num2 = array[num].GetInt("baseprotection_order", -1); if (num2 < 0 || (num > 0 && num2 == array[num - 1].GetInt("baseprotection_order", -1))) { return null; } } Vector3[] array2 = array.Select((ZDO z) => z.GetPosition()).ToArray(); Point2[] stones = array2.Select((Vector3 v) => new Point2(v.x, v.z)).ToArray(); BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; if (!FieldGeometry.TryCreate(stones, instance.MaxEdge.Value, instance.MaxArea.Value, out FieldGeometry field, out string _)) { return null; } return new ActiveField { GroupId = group, OwnerId = owner, Geometry = field, Vertices = array2 }; } internal static bool Contains(Vector3 position) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!BaseProtectionPlugin.FeaturesAvailable) { return false; } if (!ZNet.instance.IsServer() && !_hasServerSnapshot) { return false; } Point2 point = new Point2(position.x, position.z); foreach (ActiveField field in Fields) { if (field.Geometry.Contains(point)) { return true; } } return false; } internal static List GetAllStoneZdos() { List list = new List(); if (ZDOMan.instance == null) { return list; } int num = 0; int num2 = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative("piece_baseprotection_runestone", list, ref num)) { if (++num2 > 4096) { throw new InvalidOperationException("Stone scan did not complete."); } } return list; } internal static List BuildAll(IReadOnlyList allStones) { List list = new List(); foreach (IGrouping item in from z in allStones where !string.IsNullOrEmpty(z.GetString("baseprotection_group", "")) group z by z.GetString("baseprotection_group", "")) { ActiveField activeField = Build(item.Key, item.ToArray()); if (activeField != null) { list.Add(activeField); } } return list; } internal static string EncodeShape(IEnumerable positions) { return string.Join(";", positions.Select((Vector3 p) => p.x.ToString("R", CultureInfo.InvariantCulture) + "," + p.z.ToString("R", CultureInfo.InvariantCulture))); } internal static bool TryDecodeShape(string encoded, out Point2[] points) { points = Array.Empty(); if (string.IsNullOrEmpty(encoded)) { return false; } string[] array = encoded.Split(new char[1] { ';' }); if (array.Length < 2 || array.Length > 8) { return false; } Point2[] array2 = new Point2[array.Length]; for (int i = 0; i < array.Length; i++) { string[] array3 = array[i].Split(new char[1] { ',' }); if (array3.Length != 2 || !double.TryParse(array3[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !double.TryParse(array3[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { return false; } array2[i] = new Point2(result, result2); } points = array2; return true; } } internal static class FieldVisuals { private static readonly Dictionary Lines = new Dictionary(); private static Material? _material; internal static void Refresh(IReadOnlyList fields, bool visible) { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_0145: 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_0151: Unknown result type (might be due to invalid IL or missing references) if (Application.isBatchMode || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null) { Clear(); return; } HashSet hashSet = new HashSet(); foreach (FieldOutline field in fields) { hashSet.Add(field.GroupId); if (!Lines.TryGetValue(field.GroupId, out LineRenderer value) || (Object)(object)value == (Object)null) { if ((Object)(object)_material == (Object)null) { Shader val = Shader.Find("Sprites/Default"); if ((Object)(object)val == (Object)null) { return; } _material = new Material(val); } value = new GameObject("BaseProtection field outline").AddComponent(); ((Renderer)value).sharedMaterial = _material; value.useWorldSpace = true; value.startWidth = 0.18f; value.endWidth = 0.18f; value.numCapVertices = 4; Lines[field.GroupId] = value; } value.loop = !field.IsDraft || field.Stones.Length == 2; value.startColor = (field.IsDraft ? new Color(1f, 0.75f, 0.2f, 0.8f) : new Color(0.25f, 0.9f, 1f, 0.8f)); value.endColor = value.startColor; List list = Outline(field); value.positionCount = list.Count; value.SetPositions(list.ToArray()); } foreach (string item in new List(Lines.Keys)) { if (!hashSet.Contains(item)) { if ((Object)(object)Lines[item] != (Object)null) { Object.Destroy((Object)(object)((Component)Lines[item]).gameObject); } Lines.Remove(item); } } SetVisibility(visible); } internal static void SetVisibility(bool visible) { foreach (LineRenderer value in Lines.Values) { if ((Object)(object)value != (Object)null && ((Component)value).gameObject.activeSelf != visible) { ((Component)value).gameObject.SetActive(visible); } } } internal static void Clear() { foreach (LineRenderer value in Lines.Values) { if ((Object)(object)value != (Object)null) { Object.Destroy((Object)(object)((Component)value).gameObject); } } Lines.Clear(); if ((Object)(object)_material != (Object)null) { Object.Destroy((Object)(object)_material); } _material = null; } private static List Outline(FieldOutline field) { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) List list = new List(); Point2[] stones = field.Stones; if (stones.Length == 2) { Point2 point = stones[0]; Point2 point2 = stones[1]; double num = (point.X + point2.X) / 2.0; double num2 = (point.Z + point2.Z) / 2.0; double num3 = Math.Sqrt((point.X - point2.X) * (point.X - point2.X) + (point.Z - point2.Z) * (point.Z - point2.Z)) / 2.0; for (int i = 0; i < 96; i++) { double num4 = (double)(i * 2) * Math.PI / 96.0; list.Add(OnGround(num + Math.Cos(num4) * num3, num2 + Math.Sin(num4) * num3)); } } else { int num5 = (field.IsDraft ? (stones.Length - 1) : stones.Length); for (int j = 0; j < num5; j++) { Point2 point3 = stones[j]; Point2 point4 = stones[(j + 1) % stones.Length]; double num6 = Math.Sqrt((point3.X - point4.X) * (point3.X - point4.X) + (point3.Z - point4.Z) * (point3.Z - point4.Z)); int num7 = Math.Max(1, (int)Math.Ceiling(num6 / 2.0)); for (int k = 0; k < num7; k++) { double num8 = (double)k / (double)num7; list.Add(OnGround(point3.X + (point4.X - point3.X) * num8, point3.Z + (point4.Z - point3.Z) * num8)); } } if (field.IsDraft) { list.Add(OnGround(stones[^1].X, stones[^1].Z)); } } return list; } private static Vector3 OnGround(double x, double z) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor((float)x, 0f, (float)z); val.y = ZoneSystem.instance.GetGroundHeight(val) + 0.2f; return val; } } [HarmonyPatch(typeof(BaseAI), "MoveTowards")] internal static class MobRepulsionPatch { private const float DetectionDistance = 8f; internal static void Prefix(BaseAI __instance, ref Vector3 dir) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Invalid comparison between Unknown and I4 //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)BaseProtectionPlugin.Instance == (Object)null || !BaseProtectionPlugin.Instance.RepelHostileMobs.Value || !BaseProtectionPlugin.FeaturesAvailable) { return; } MonsterAI val = (MonsterAI)(object)((__instance is MonsterAI) ? __instance : null); if (val == null || FieldRegistry.ActiveFields.Count == 0) { return; } Character component = ((Component)val).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsOwner() || component.IsBoss() || component.IsTamed() || val.IsEventCreature() || (int)component.GetFaction() == 11 || ((int)component.GetFaction() == 10 && !((BaseAI)val).IsAggravated())) { return; } float num = Mathf.Sqrt(dir.x * dir.x + dir.z * dir.z); if (num < 0.001f) { return; } Vector3 position = ((Component)component).transform.position; if (FieldRegistry.Contains(position) || !IsHostileToAnyPlayer(component)) { return; } Point2 position2 = new Point2(position.x, position.z); Point2 point = new Point2(dir.x, dir.z); float num2 = 8f + Mathf.Clamp(component.GetRadius(), 0f, 8f); int preferredSide = (((((Object)val).GetInstanceID() & 1) != 0) ? 1 : (-1)); double num3 = double.PositiveInfinity; Point2 point2 = point; foreach (ActiveField activeField in FieldRegistry.ActiveFields) { if (activeField.Geometry.TrySteerOutside(position2, point, num2, preferredSide, out var direction, out var boundaryDistance) && !(boundaryDistance >= num3)) { num3 = boundaryDistance; point2 = direction; } } if (!double.IsPositiveInfinity(num3)) { dir = new Vector3((float)(point2.X * (double)num), dir.y, (float)(point2.Z * (double)num)); } } private static bool IsHostileToAnyPlayer(Character character) { foreach (Player allPlayer in Player.GetAllPlayers()) { if ((Object)(object)allPlayer != (Object)null && BaseAI.IsEnemy(character, (Character)(object)allPlayer)) { return true; } } return false; } } [HarmonyPatch(typeof(BaseAI), "MoveTowardsSwoop")] internal static class MobRepulsionSwoopPatch { private static void Prefix(BaseAI __instance, ref Vector3 dir) { MobRepulsionPatch.Prefix(__instance, ref dir); } } internal static class NetworkCommands { private sealed class PendingRemoval { internal long RequestId; internal ItemData? Tool; internal float DurabilityCost; internal float SentAt; internal bool Confirmed; } private sealed class ServerPendingRemoval { internal long Sender; internal long RequestId; internal Vector3 Position; internal Quaternion Rotation; internal Vector3 RefundPosition; internal int StoneCount; internal bool Cheated; internal float SentAt; } private const string LinkRpc = "BaseProtection.Link.v1"; private const string UnlinkRpc = "BaseProtection.Unlink.v1"; private const string FinalizeRpc = "BaseProtection.Finalize.v1"; private const string FinishWithStoneRpc = "BaseProtection.FinishWithStone.v1"; private const string ConsentRpc = "BaseProtection.Consent.v1"; private const string ReplyRpc = "BaseProtection.Reply.v1"; private const string RemoveRpc = "BaseProtection.Remove.v1"; private const string RemoveResultRpc = "BaseProtection.RemoveResult.v1"; private const string RemoveVisualRpc = "BaseProtection.RemoveVisual.v1"; private const string FieldSnapshotRequestRpc = "BaseProtection.FieldSnapshotRequest.v1"; private const string FieldSnapshotRpc = "BaseProtection.FieldSnapshot.v1"; private const int FieldSnapshotProtocol = 1; private const int MaximumSnapshotFields = 16384; private const int MaximumSnapshotBytes = 4194304; private const int MaximumGroupIdLength = 128; private const double MaximumCoordinate = 1000000.0; private const float SnapshotRequestCooldown = 5f; private const float SnapshotRequestRetention = 60f; private const int MaximumTrackedSnapshotPeers = 512; private static ZRoutedRpc? _registered; private static ZNet? _snapshotNetwork; private static long _snapshotSource; private static float _lastSnapshotRequestTime = -1f; private static long _lastAppliedSnapshotRevision = -1L; private static long _serverSnapshotRevision; private static byte[]? _serverSnapshotBody; private static readonly Dictionary LastSnapshotRequestByPeer = new Dictionary(); private static float _nextSnapshotRequestCleanup; private static float _linkRequestTime = -1f; private const float RemoveReplyTimeout = 15f; private const float ServerRemoveTimeout = 30f; private static long _nextRemovalRequestId; private static float _nextServerRemoveCleanup; private static readonly MethodInfo? PlaceDurabilityMethod = AccessTools.Method(typeof(Player), "GetPlaceDurability", new Type[1] { typeof(ItemData) }, (Type[])null); private static readonly Dictionary PendingRemovals = new Dictionary(); private static readonly Dictionary ServerPendingRemovals = new Dictionary(); private static readonly Dictionary LastRemovalDenialLog = new Dictionary(); private static bool TryGetServerPeerId(out long peerId) { peerId = 0L; if ((Object)(object)ZNet.instance == (Object)null) { return false; } if (ZNet.instance.IsServer()) { peerId = ZNet.GetUID(); return true; } ZNetPeer serverPeer = ZNet.instance.GetServerPeer(); if (serverPeer == null) { return false; } peerId = serverPeer.m_uid; return true; } internal static void TryRegister() { ZRoutedRpc instance = ZRoutedRpc.instance; ZNet instance2 = ZNet.instance; if (instance == null || (Object)(object)instance2 == (Object)null) { return; } if (instance != _registered) { instance.Register("BaseProtection.Link.v1", (Action)OnLink); instance.Register("BaseProtection.Unlink.v1", (Action)OnUnlink); instance.Register("BaseProtection.Finalize.v1", (Action)OnFinalize); instance.Register("BaseProtection.FinishWithStone.v1", (Action)OnFinishWithStone); instance.Register("BaseProtection.Consent.v1", (Action)OnConsent); instance.Register("BaseProtection.Reply.v1", (Action)OnReply); instance.Register("BaseProtection.Remove.v1", (Action)OnRemove); instance.Register("BaseProtection.RemoveResult.v1", (Method)OnRemoveResult); instance.Register("BaseProtection.RemoveVisual.v1", (Action)OnRemoveVisual); instance.Register("BaseProtection.FieldSnapshotRequest.v1", (Action)OnFieldSnapshotRequest); instance.Register("BaseProtection.FieldSnapshot.v1", (Action)OnFieldSnapshot); _registered = instance; } if ((Object)(object)instance2 != (Object)(object)_snapshotNetwork) { _snapshotNetwork = instance2; _snapshotSource = 0L; _lastSnapshotRequestTime = -1f; _lastAppliedSnapshotRevision = -1L; _serverSnapshotRevision = 0L; _serverSnapshotBody = null; LastSnapshotRequestByPeer.Clear(); PendingRemovals.Clear(); _nextRemovalRequestId = 0L; ServerPendingRemovals.Clear(); _nextServerRemoveCleanup = 0f; LastRemovalDenialLog.Clear(); _nextSnapshotRequestCleanup = 0f; if (!instance2.IsServer()) { FieldRegistry.ClearServerSnapshot(); } } if (instance2.IsServer()) { return; } if (!TryGetServerPeerId(out var peerId)) { if (_snapshotSource != 0L) { _snapshotSource = 0L; _lastSnapshotRequestTime = -1f; _lastAppliedSnapshotRevision = -1L; FieldRegistry.ClearServerSnapshot(); } return; } if (_snapshotSource != peerId) { _snapshotSource = peerId; _lastSnapshotRequestTime = -1f; _lastAppliedSnapshotRevision = -1L; FieldRegistry.ClearServerSnapshot(); } if (!FieldRegistry.HasServerSnapshot && (!(_lastSnapshotRequestTime >= 0f) || !(Time.time - _lastSnapshotRequestTime < 5f))) { _lastSnapshotRequestTime = Time.time; instance.InvokeRoutedRPC(peerId, "BaseProtection.FieldSnapshotRequest.v1", Array.Empty()); } } internal static void PublishFieldSnapshot(IReadOnlyList fields) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && _registered != null) { if (!TryEncodeFieldSnapshot(fields, out byte[] body)) { ZPackage val = new ZPackage(); val.Write(0); body = val.GetArray(); } if (_serverSnapshotBody == null || !_serverSnapshotBody.SequenceEqual(body)) { _serverSnapshotBody = body; _serverSnapshotRevision++; _registered.InvokeRoutedRPC(0L, "BaseProtection.FieldSnapshot.v1", new object[1] { CreateFieldSnapshotPackage() }); } } } private static ZPackage CreateFieldSnapshotPackage() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(1); val.Write(_serverSnapshotRevision); val.Write(_serverSnapshotBody ?? Array.Empty()); return val; } private static bool TryEncodeFieldSnapshot(IReadOnlyList fields, out byte[] body) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown body = Array.Empty(); if (fields.Count > 16384) { BaseProtectionPlugin.Instance.LogWarning("Too many active fields to synchronize."); return false; } ZPackage val = new ZPackage(); val.Write(fields.Count); foreach (ActiveField item in fields.OrderBy((ActiveField f) => f.GroupId, StringComparer.Ordinal)) { IReadOnlyList stones = item.Geometry.Stones; if (item.GroupId.Length == 0 || item.GroupId.Length > 128 || item.OwnerId == 0L || stones.Count < 2 || stones.Count > 8) { BaseProtectionPlugin.Instance.LogWarning("An active field has invalid snapshot data."); return false; } val.Write(item.GroupId); val.Write(item.OwnerId); val.Write(stones.Count); foreach (Point2 item2 in stones) { val.Write(item2.X); val.Write(item2.Z); } } if (val.Size() > 4194304) { BaseProtectionPlugin.Instance.LogWarning("The active-field snapshot exceeds the network size limit."); return false; } body = val.GetArray(); return true; } private static void OnFieldSnapshotRequest(long sender) { ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer() || !StoneRoutedPeerContext.Matches(sender) || instance.GetPeer(sender) == null || ZDOMan.instance == null) { return; } float time = Time.time; CleanSnapshotRequestPeers(instance, time); if (LastSnapshotRequestByPeer.TryGetValue(sender, out var value) && time >= value && time - value < 5f) { return; } LastSnapshotRequestByPeer[sender] = time; if (_serverSnapshotBody == null) { FieldRegistry.Refresh(); } if (_serverSnapshotBody != null) { ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(sender, "BaseProtection.FieldSnapshot.v1", new object[1] { CreateFieldSnapshotPackage() }); } } } private static void CleanSnapshotRequestPeers(ZNet network, float now) { if (now < _nextSnapshotRequestCleanup && LastSnapshotRequestByPeer.Count < 512) { return; } KeyValuePair[] array = LastSnapshotRequestByPeer.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair keyValuePair = array[i]; if (now < keyValuePair.Value || now - keyValuePair.Value >= 60f || network.GetPeer(keyValuePair.Key) == null) { LastSnapshotRequestByPeer.Remove(keyValuePair.Key); } } while (LastSnapshotRequestByPeer.Count >= 512) { long key = LastSnapshotRequestByPeer.Aggregate((KeyValuePair left, KeyValuePair right) => (!(left.Value <= right.Value)) ? right : left).Key; LastSnapshotRequestByPeer.Remove(key); } _nextSnapshotRequestCleanup = now + 60f; } private static void OnFieldSnapshot(long sender, ZPackage package) { if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer() || !TryGetServerPeerId(out var peerId) || sender != peerId || package == null || package.Size() > 4194336) { return; } try { if (package.ReadInt() != 1) { return; } long num = package.ReadLong(); if (num < _lastAppliedSnapshotRevision) { return; } int num2 = package.ReadInt(); if (num2 >= 0 && num2 <= 4194304 && package.Size() - package.GetPos() == num2) { byte[] array = package.ReadByteArray(num2); if (array.Length == num2 && TryDecodeFieldSnapshot(array, out List fields)) { _snapshotSource = sender; _lastAppliedSnapshotRevision = num; FieldRegistry.ApplyServerSnapshot(fields); } } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Discarded malformed field snapshot: " + ex.Message); } } private static bool TryDecodeFieldSnapshot(byte[] body, out List fields) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) fields = new List(); ZPackage val = new ZPackage(body); int num = val.ReadInt(); if (num < 0 || num > 16384) { return false; } HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < num; i++) { string text = val.ReadString(); long num2 = val.ReadLong(); int num3 = val.ReadInt(); if (text.Length == 0 || text.Length > 128 || !hashSet.Add(text) || num2 == 0L || num3 < 2 || num3 > 8) { return false; } Point2[] array = new Point2[num3]; Vector3[] array2 = (Vector3[])(object)new Vector3[num3]; for (int j = 0; j < num3; j++) { double num4 = val.ReadDouble(); double num5 = val.ReadDouble(); if (double.IsNaN(num4) || double.IsInfinity(num4) || Math.Abs(num4) > 1000000.0 || double.IsNaN(num5) || double.IsInfinity(num5) || Math.Abs(num5) > 1000000.0) { return false; } array[j] = new Point2(num4, num5); array2[j] = new Vector3((float)num4, 0f, (float)num5); } if (!FieldGeometry.TryCreate(array, 10000.0, 100000000.0, out FieldGeometry field, out string _)) { return false; } fields.Add(new ActiveField { GroupId = text, OwnerId = num2, Geometry = field, Vertices = array2 }); } return val.GetPos() == val.Size(); } internal static void RequestLink(ZDOID first, ZDOID second) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) TryRegister(); if (_registered == null || !TryGetServerPeerId(out var peerId)) { RunestoneInteraction.Notify("Cannot reach the host to link runestones yet."); return; } if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer()) { _linkRequestTime = Time.time; RunestoneInteraction.Notify("Link request sent to host..."); } BaseProtectionPlugin.Instance.LogInfo($"Sending runestone link request to peer {peerId}."); _registered.InvokeRoutedRPC(peerId, "BaseProtection.Link.v1", new object[2] { first, second }); } internal static void CheckPendingLink() { if (!(_linkRequestTime < 0f) && !(Time.time - _linkRequestTime < 5f)) { _linkRequestTime = -1f; RunestoneInteraction.Notify("No reply from host. Check both players' mod versions and BepInEx logs."); } } internal static void RequestUnlink(ZDOID stone) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) TryRegister(); if (_registered != null && TryGetServerPeerId(out var peerId)) { _registered.InvokeRoutedRPC(peerId, "BaseProtection.Unlink.v1", new object[1] { stone }); } else { RunestoneInteraction.Notify("Cannot reach the host to unlink this runestone yet."); } } internal static void RequestFinalize(ZDOID stone) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) TryRegister(); if (_registered != null && TryGetServerPeerId(out var peerId)) { _registered.InvokeRoutedRPC(peerId, "BaseProtection.Finalize.v1", new object[1] { stone }); } else { RunestoneInteraction.Notify("Cannot reach the host to finish this field yet."); } } internal static void RequestFinishWithStone(ZDOID draftStone, ZDOID newStone) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) TryRegister(); if (_registered != null && TryGetServerPeerId(out var peerId)) { _registered.InvokeRoutedRPC(peerId, "BaseProtection.FinishWithStone.v1", new object[2] { draftStone, newStone }); } else { RunestoneInteraction.Notify("Cannot reach the host to finish this field yet."); } } internal static void RequestToggleConsent(ZDOID stone) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) TryRegister(); if (_registered != null && TryGetServerPeerId(out var peerId)) { _registered.InvokeRoutedRPC(peerId, "BaseProtection.Consent.v1", new object[1] { stone }); } else { RunestoneInteraction.Notify("Cannot reach the host to update field approval yet."); } } internal static bool CanRequestRemove() { TryRegister(); if (_registered != null && TryGetServerPeerId(out var peerId)) { return peerId != 0; } return false; } internal static bool IsRemovePending(Piece piece) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)piece).GetComponent(); ZDOID? val = ((component == null) ? ((ZDOID?)null) : component.GetZDO()?.m_uid); if (val.HasValue) { return PendingRemovals.ContainsKey(val.Value); } return false; } internal static bool IsServerRemovalPending(ZDOID stoneId) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return ServerPendingRemovals.ContainsKey(stoneId); } internal static bool RequestRemove(ZDOID stoneId) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) if (!CanRequestRemove() || !TryGetServerPeerId(out var peerId)) { RunestoneInteraction.Notify("Cannot reach the server to remove this runestone yet."); return false; } if (PendingRemovals.ContainsKey(stoneId)) { return false; } Player localPlayer = Player.m_localPlayer; ItemData val = ((localPlayer != null) ? ((Humanoid)localPlayer).RightItem : null); long num = ++_nextRemovalRequestId; if (num == 0L) { num = ++_nextRemovalRequestId; } PendingRemovals.Add(stoneId, new PendingRemoval { RequestId = num, Tool = val, DurabilityCost = ((val != null && val.m_shared.m_useDurability && (Object)(object)localPlayer != (Object)null) ? GetRemovalDurabilityCost(localPlayer, val) : 0f), SentAt = Time.time }); if (ZNet.instance.IsServer()) { if (TryRemoveStone(peerId, stoneId, num, out string denial)) { return true; } PendingRemovals.Remove(stoneId); RunestoneInteraction.Notify(denial); return false; } try { _registered.InvokeRoutedRPC(peerId, "BaseProtection.Remove.v1", new object[2] { stoneId, num }); } catch (Exception error) { PendingRemovals.Remove(stoneId); BaseProtectionPlugin.Instance.LogError(error); RunestoneInteraction.Notify("Could not send the runestone removal request."); return false; } return true; } private static float GetRemovalDurabilityCost(Player player, ItemData tool) { try { return (PlaceDurabilityMethod?.Invoke(player, new object[1] { tool }) is float num) ? (num * Game.m_durabilityRate) : 0f; } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Could not read hammer durability cost: " + ex.Message); return 0f; } } private static void RefundRemovalDurability(PendingRemoval pending) { ItemData tool = pending.Tool; if (tool != null && !(pending.DurabilityCost <= 0f)) { tool.m_durability = Math.Min(tool.GetMaxDurability(), tool.m_durability + pending.DurabilityCost); } } internal static void CheckPendingRemove() { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) KeyValuePair[] array = PendingRemovals.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair keyValuePair = array[i]; if (keyValuePair.Value.Confirmed) { ZDOMan instance = ZDOMan.instance; if (((instance != null) ? instance.GetZDO(keyValuePair.Key) : null) == null) { PendingRemovals.Remove(keyValuePair.Key); } else if (!(Time.time - keyValuePair.Value.SentAt < 15f)) { PendingRemovals.Remove(keyValuePair.Key); RunestoneInteraction.Notify("The server removed this runestone, but your client still shows it. Reconnect if it persists."); } } else if (!(Time.time - keyValuePair.Value.SentAt < 15f)) { PendingRemovals.Remove(keyValuePair.Key); ZDOMan instance2 = ZDOMan.instance; if (((instance2 != null) ? instance2.GetZDO(keyValuePair.Key) : null) != null) { RefundRemovalDurability(keyValuePair.Value); RunestoneInteraction.Notify("No removal reply from the server. Try again shortly."); } } } ZNet instance3 = ZNet.instance; if ((Object)(object)instance3 == (Object)null || !instance3.IsServer() || Time.time < _nextServerRemoveCleanup) { return; } _nextServerRemoveCleanup = Time.time + 1f; KeyValuePair[] array2 = ServerPendingRemovals.ToArray(); for (int i = 0; i < array2.Length; i++) { KeyValuePair keyValuePair2 = array2[i]; if (Time.time - keyValuePair2.Value.SentAt < 30f) { continue; } ZDOMan instance4 = ZDOMan.instance; if (((instance4 != null) ? instance4.GetZDO(keyValuePair2.Key) : null) == null) { OnStoneDestroyed(keyValuePair2.Key); continue; } ServerPendingRemovals.Remove(keyValuePair2.Key); try { ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(keyValuePair2.Value.Sender, "BaseProtection.RemoveResult.v1", new object[4] { keyValuePair2.Key, keyValuePair2.Value.RequestId, false, "The server did not finish removing this runestone. Try again." }); } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning($"Could not report timed-out removal to peer {keyValuePair2.Value.Sender}: {ex.Message}"); } } } private static void OnReply(long sender, string text) { if (_registered == null || !TryGetServerPeerId(out var peerId) || sender != peerId) { BaseProtectionPlugin.Instance.LogWarning($"Ignoring runestone reply from unexpected peer {sender}."); return; } _linkRequestTime = -1f; RunestoneInteraction.OnServerReply(text); } private static void OnRemove(long sender, ZDOID stoneId, long requestId) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !StoneRoutedPeerContext.Matches(sender) || TryRemoveStone(sender, stoneId, requestId, out string denial)) { return; } float time = Time.time; if (!LastRemovalDenialLog.TryGetValue(sender, out var value) || time < value || time - value >= 5f) { if (LastRemovalDenialLog.Count >= 512) { LastRemovalDenialLog.Clear(); } LastRemovalDenialLog[sender] = time; BaseProtectionPlugin.Instance.LogWarning($"Denied runestone removal from peer {sender}: {denial}"); } ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(sender, "BaseProtection.RemoveResult.v1", new object[4] { stoneId, requestId, false, denial }); } } private static bool TryRemoveStone(long sender, ZDOID stoneId, long requestId, out string denial) { //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) denial = "The runestone is not ready on the server. Try again shortly."; ZDOMan instance = ZDOMan.instance; ZNet instance2 = ZNet.instance; if ((Object)(object)instance2 == (Object)null || !instance2.IsServer() || instance == null || !StoneRoutedPeerContext.Matches(sender)) { return false; } ZDO zDO = instance.GetZDO(stoneId); if (!StoneAccess.CanServerRemove(zDO, sender, out denial)) { return false; } if (ServerPendingRemovals.ContainsKey(stoneId)) { denial = "Runestone removal is already being processed."; return false; } ZoneSystem instance3 = ZoneSystem.instance; if ((Object)(object)instance3 == (Object)null) { return false; } bool globalKey = instance3.GetGlobalKey((GlobalKeys)24); object obj; if (!globalKey) { ObjectDB instance4 = ObjectDB.instance; obj = ((instance4 != null) ? instance4.GetItemPrefab("Stone") : null); } else { obj = null; } GameObject val = (GameObject)obj; if (!globalKey && (Object)(object)((val != null) ? val.GetComponent() : null) == (Object)null) { denial = "The server cannot prepare the runestone's Stone refund."; return false; } try { long uID = ZNet.GetUID(); if (zDO.GetOwner() != uID) { zDO.SetOwner(uID); } if (!zDO.IsOwner()) { throw new InvalidOperationException("The server could not claim the runestone before removal."); } Vector3 position = zDO.GetPosition(); ZNetScene instance5 = ZNetScene.instance; object obj2; if (instance5 == null) { obj2 = null; } else { GameObject prefab = instance5.GetPrefab(StoneAccess.StonePrefabHash); obj2 = ((prefab != null) ? prefab.GetComponent() : null); } Piece val2 = (Piece)obj2; ServerPendingRemoval value = new ServerPendingRemoval { Sender = sender, RequestId = requestId, Position = position, Rotation = zDO.GetRotation(), RefundPosition = position + Vector3.up * (val2?.m_returnResourceHeightOffset ?? 0f), StoneCount = ((!globalKey) ? ((zDO.GetLong(ZDOVars.s_creator, 0L) == 0L) ? Math.Max(1, 3) : 10) : 0), Cheated = (zDO.GetInt(ZDOVars.s_cheated, 0) == 2 && !PlayerProfile.s_bypassCheatChecks), SentAt = Time.time }; ServerPendingRemovals.Add(stoneId, value); instance.DestroyZDO(zDO); denial = ""; return true; } catch (Exception error) { ServerPendingRemovals.Remove(stoneId); BaseProtectionPlugin.Instance.LogError(error); denial = "The server could not remove this runestone. Try again shortly."; return false; } } private static void OnRemoveResult(long sender, ZDOID stoneId, long requestId, bool success, string denial) { //IL_0012: 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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (!TryGetServerPeerId(out var peerId) || sender != peerId || !PendingRemovals.TryGetValue(stoneId, out PendingRemoval value) || value.RequestId != requestId) { return; } if (success) { ZDOMan instance = ZDOMan.instance; if (((instance != null) ? instance.GetZDO(stoneId) : null) == null) { PendingRemovals.Remove(stoneId); } else { value.Confirmed = true; value.SentAt = Time.time; } if (!string.IsNullOrEmpty(denial)) { RunestoneInteraction.Notify(denial); } } else { PendingRemovals.Remove(stoneId); RefundRemovalDurability(value); RunestoneInteraction.Notify(denial); } } internal static void OnStoneDestroying(ZDOID stoneId) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!ServerPendingRemovals.TryGetValue(stoneId, out ServerPendingRemoval value)) { return; } try { ZNetScene instance = ZNetScene.instance; GameObject val = ((instance != null) ? instance.FindInstance(stoneId) : null); object obj = ((val != null) ? val.GetComponent() : null); if (obj == null) { if (instance == null) { obj = null; } else { GameObject prefab = instance.GetPrefab(StoneAccess.StonePrefabHash); obj = ((prefab != null) ? prefab.GetComponent() : null); } } WearNTear val2 = (WearNTear)obj; if ((Object)(object)val2 != (Object)null) { Transform val3 = ((val != null) ? val.transform : null); val2.m_destroyedEffect.Create((val3 != null) ? val3.position : value.Position, (val3 != null) ? val3.rotation : value.Rotation, val3, 1f, -1, ZDOID.None); } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Could not create runestone destruction effects: " + ex.Message); } try { ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(0L, "BaseProtection.RemoveVisual.v1", new object[1] { stoneId }); } } catch (Exception ex2) { BaseProtectionPlugin.Instance.LogWarning("Could not broadcast runestone removal effects: " + ex2.Message); } } internal static void OnStoneDestroyed(ZDOID stoneId) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) if (!ServerPendingRemovals.TryGetValue(stoneId, out ServerPendingRemoval value)) { return; } ZDOMan instance = ZDOMan.instance; if (((instance != null) ? instance.GetZDO(stoneId) : null) != null) { return; } ServerPendingRemovals.Remove(stoneId); string text = ""; if (value.StoneCount > 0) { ItemDrop val = null; try { ObjectDB instance2 = ObjectDB.instance; GameObject obj = ((instance2 != null) ? instance2.GetItemPrefab("Stone") : null); if ((Object)(object)((obj != null) ? obj.GetComponent() : null) == (Object)null) { throw new InvalidOperationException("Stone item prefab is unavailable."); } val = Object.Instantiate(obj, value.RefundPosition, Quaternion.identity).GetComponent(); val.SetStack(value.StoneCount); ItemDrop.OnCreateNew(val, false); if (value.Cheated) { val.m_itemData.m_cheated = true; } } catch (Exception error) { if ((Object)(object)val != (Object)null) { ZNetScene instance3 = ZNetScene.instance; if (instance3 != null) { instance3.Destroy(((Component)val).gameObject); } } BaseProtectionPlugin.Instance.LogError(error); text = "Runestone removed, but the server could not return its Stone."; } } try { ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(value.Sender, "BaseProtection.RemoveResult.v1", new object[4] { stoneId, value.RequestId, true, text }); } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning($"Could not confirm runestone removal to peer {value.Sender}: {ex.Message}"); } } private static void OnRemoveVisual(long sender, ZDOID stoneId) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!TryGetServerPeerId(out var peerId) || sender != peerId || Application.isBatchMode) { return; } ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { return; } try { GameObject val = instance.FindInstance(stoneId); WearNTear val2 = ((val != null) ? val.GetComponent() : null); if (!((Object)(object)val2 != (Object)null) || !StoneAccess.IsStone((Component)(object)val2) || !val2.m_autoCreateFragments) { return; } GameObject[] fragmentRoots = val2.m_fragmentRoots; if (fragmentRoots != null && fragmentRoots.Length != 0) { GameObject[] array = fragmentRoots; foreach (GameObject val3 in array) { if (!((Object)(object)val3 == (Object)null)) { val3.SetActive(true); Destructible.CreateFragments(val3, false); } } } else { Destructible.CreateFragments(val, true); } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Could not display runestone removal effects: " + ex.Message); } } private static void Reply(long recipient, string text) { BaseProtectionPlugin.Instance.LogInfo($"Runestone reply to peer {recipient}: {text}"); ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(recipient, "BaseProtection.Reply.v1", new object[1] { text }); } } private static bool TryGetOwner(long sender, out long playerId) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) playerId = 0L; if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !StoneRoutedPeerContext.Matches(sender)) { return false; } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer != null) { if (((ZDOID)(ref peer.m_characterID)).UserID != sender) { return false; } ZDOMan instance = ZDOMan.instance; ZDO val = ((instance != null) ? instance.GetZDO(peer.m_characterID) : null); playerId = ((val != null) ? val.GetLong(ZDOVars.s_playerID, 0L) : 0); } else if (sender == ZNet.GetUID() && (Object)(object)Player.m_localPlayer != (Object)null) { playerId = Player.m_localPlayer.GetPlayerID(); } return playerId != 0; } private static Vector3? GetRequesterPosition(long sender) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) ZNet instance = ZNet.instance; ZNetPeer val = ((instance != null) ? instance.GetPeer(sender) : null); if (val != null) { ZDOMan instance2 = ZDOMan.instance; if (instance2 == null) { return null; } ZDO zDO = instance2.GetZDO(val.m_characterID); if (zDO == null) { return null; } return zDO.GetPosition(); } if (sender == ZNet.GetUID()) { Player localPlayer = Player.m_localPlayer; if (localPlayer == null) { return null; } return ((Component)localPlayer).transform.position; } return null; } private static bool RequireOwner(long sender, out long playerId) { if (TryGetOwner(sender, out playerId)) { return true; } BaseProtectionPlugin.Instance.LogWarning($"Runestone request from peer {sender} has no player ID."); Reply(sender, "The host could not identify your player. Rejoin and try again."); return false; } private static bool IsStone(ZDO? zdo) { if (zdo != null) { return zdo.GetPrefab() == StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone"); } return false; } private static bool TryReadConsents(IReadOnlyList members, out HashSet creators) { creators = new HashSet(); if (members.Count == 0) { return false; } string encoded = members[0].GetString("baseprotection_consents", ""); if (members.Any((ZDO member) => member.GetString("baseprotection_consents", "") != encoded)) { return false; } return CreatorConsent.TryParse(encoded, out creators); } private static void WriteConsents(IEnumerable members, HashSet creators) { string text = CreatorConsent.Format(creators); foreach (ZDO member in members) { member.SetOwner(ZNet.GetUID()); member.Set("baseprotection_consents", text); } } private static void MarkDraft(IEnumerable members) { foreach (ZDO member in members) { member.SetOwner(ZNet.GetUID()); member.Set("baseprotection_active", 0); } } private static void InvalidateApprovals(IEnumerable members) { MarkDraft(members); foreach (ZDO member in members) { member.Set("baseprotection_consents", ""); } } private static void OnConsent(long sender, ZDOID stoneId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) if (!RequireOwner(sender, out var playerId)) { return; } try { ZDO zDO = ZDOMan.instance.GetZDO(stoneId); string group = ((zDO != null) ? zDO.GetString("baseprotection_group", "") : null) ?? ""; if (!IsStone(zDO) || group.Length == 0) { Reply(sender, "Approvals require a linked runestone field."); return; } Vector3? requesterPosition = GetRequesterPosition(sender); if (!requesterPosition.HasValue || Vector3.Distance(requesterPosition.Value, zDO.GetPosition()) > 6f) { Reply(sender, "Stand beside the runestone to update field approval."); return; } ZDO[] array = (from z in FieldRegistry.GetAllStoneZdos() where z.GetString("baseprotection_group", "") == @group orderby z.GetInt("baseprotection_order", -1) select z).ToArray(); if (array.Length < 2 || array.Length > 8 || !array.Any((ZDO z) => z.m_uid == stoneId) || array.Any((ZDO z) => z.GetInt("baseprotection_order", -1) < 0) || array.Select((ZDO z) => z.GetInt("baseprotection_order", -1)).Distinct().Count() != array.Length) { Reply(sender, "This field has invalid runestone data."); return; } long fieldOwner = array[0].GetLong(ZDOVars.s_creator, 0L); bool active = array[0].GetInt("baseprotection_active", 1) != 0; if (fieldOwner == 0L || fieldOwner == playerId || array.Any((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != fieldOwner || z.GetInt("baseprotection_active", 1) != 0 != active)) { Reply(sender, "Only another builder can approve a valid field."); return; } if (!TryReadConsents(array, out HashSet creators)) { Reply(sender, "Field approval data is invalid; recreate this draft."); return; } if (creators.Remove(playerId)) { if (active) { MarkDraft(array); } WriteConsents(array, creators); if (active) { WriteGroup(array, group, active: false); FieldRegistry.Refresh(); Reply(sender, "Approval withdrawn. The field is now a draft."); } else { Reply(sender, "Approval withdrawn from this draft."); } return; } if (active) { Reply(sender, "Only an existing approval can be withdrawn from an active field."); return; } if (creators.Count >= 32) { Reply(sender, "This draft has reached its builder approval limit."); return; } BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; Vector3[] array2 = array.Select((ZDO z) => z.GetPosition()).ToArray(); Point2[] stones = array2.Select((Vector3 v) => new Point2(v.x, v.z)).ToArray(); if (!PolygonOrdering.Untangle(stones).Select((int value, int index) => value == index).All((bool equal) => equal)) { Reply(sender, "Ask the field owner to Shift+Use a draft stone once to fix its order before approval."); return; } if (!FieldGeometry.TryCreate(stones, instance.MaxEdge.Value, instance.MaxArea.Value, out FieldGeometry field, out string error)) { Reply(sender, "The draft cannot be approved yet: " + error); return; } float num = Math.Max(0f, instance.ForeignStructureBuffer.Value); if (num <= 0f) { Reply(sender, "Structure approval is unnecessary while the server's foreign structure buffer is disabled."); return; } if (!TryFindStructureNear(field, array2, num, (long creator) => creator == playerId, out var found)) { Reply(sender, "The server could not check nearby structures. Try again shortly."); return; } if (!found) { Reply(sender, "This character has no structures within the field's protected area or buffer."); return; } creators.Add(playerId); WriteConsents(array, creators); Reply(sender, "You approved this draft field near structures placed by this character."); } catch (Exception error2) { BaseProtectionPlugin.Instance.LogError(error2); Reply(sender, "Could not update field approval; check the server log."); } } private static void OnLink(long sender, ZDOID sourceId, ZDOID targetId) { //IL_003c: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0124: 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) BaseProtectionPlugin.Instance.LogInfo($"Received runestone link request from peer {sender}."); if (!RequireOwner(sender, out var playerId)) { return; } try { ZDO source = ZDOMan.instance.GetZDO(sourceId); ZDO val = ZDOMan.instance.GetZDO(targetId); if (!IsStone(source) || !IsStone(val) || sourceId == targetId) { Reply(sender, "Both targets must be different linked runestones."); return; } if (source.GetLong(ZDOVars.s_creator, 0L) != playerId || val.GetLong(ZDOVars.s_creator, 0L) != playerId) { Reply(sender, "You can only link stones that you placed."); return; } string sourceGroup = source.GetString("baseprotection_group", ""); string text = val.GetString("baseprotection_group", ""); if (sourceGroup.Length != 0 && text.Length != 0) { Reply(sender, "Both stones are already linked. Select an unlinked stone to add to a field."); return; } Vector3? requesterPosition = GetRequesterPosition(sender); if (!requesterPosition.HasValue || Vector3.Distance(requesterPosition.Value, val.GetPosition()) > 6f) { Reply(sender, "Stand beside the target stone to link it."); return; } if (text.Length != 0) { ZDO val2 = val; val = source; source = val2; sourceGroup = text; } List allStoneZdos = FieldRegistry.GetAllStoneZdos(); List list = (string.IsNullOrEmpty(sourceGroup) ? new List { source } : (from z in allStoneZdos where z.GetString("baseprotection_group", "") == sourceGroup orderby z.GetInt("baseprotection_order", -1) select z).ToList()); if (!list.Any((ZDO z) => z.m_uid == source.m_uid) || list.Count >= 8 || list.Any((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != playerId)) { Reply(sender, "This field already has eight stones or has invalid link data."); return; } list.Add(val); string text2 = (string.IsNullOrEmpty(sourceGroup) ? Guid.NewGuid().ToString("N") : sourceGroup); InvalidateApprovals(list); WriteGroup(list, text2, active: false); FieldRegistry.Refresh(); Reply(sender, $"Draft has {list.Count} stones. Shift+E a draft stone to finish."); } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); Reply(sender, "Linking failed; check the server log."); } } private static string? ValidateProposal(string groupId, long owner, List members, List allStones) { BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; if (!TryReadConsents(members, out HashSet approvedCreators)) { return "Field approval data is invalid; recreate this draft."; } Vector3[] array = members.Select((ZDO z) => z.GetPosition()).ToArray(); if (!FieldGeometry.TryCreate(array.Select((Vector3 v) => new Point2(v.x, v.z)).ToArray(), instance.MaxEdge.Value, instance.MaxArea.Value, out FieldGeometry field, out string error)) { return error; } ActiveField[] array2 = (from f in FieldRegistry.BuildAll(allStones) where f.GroupId != groupId select f).ToArray(); ActiveField[] array3 = array2; foreach (ActiveField activeField in array3) { if (field.Overlaps(activeField.Geometry) || field.DistanceTo(activeField.Geometry) < (double)Math.Max(0f, instance.FieldGap.Value)) { return "This field is too close to another field."; } } ActiveField[] array4 = array2.Where((ActiveField f) => f.OwnerId == owner).ToArray(); if (array4.Length + 1 > instance.MaxFieldsPerPlayer.Value) { return "You have reached your field limit."; } double num2 = array4.Sum((ActiveField f) => f.Geometry.Area); float value = instance.MaxTotalAreaPerPlayer.Value; if (num2 + field.Area > (double)value) { return $"Field needs {field.Area:0} m²; your other fields use {num2:0} m²; " + $"the per-player limit is {value:0} m²."; } if (!TryFindStructureNear(field, array, Math.Max(0f, instance.ForeignStructureBuffer.Value), (long creator) => creator != owner && !approvedCreators.Contains(creator), out var found)) { return "The server could not check nearby structures. Try again shortly."; } if (found) { return "The field is too close to another player's structure. Ask that builder to Ctrl+Shift+Use a draft stone to approve it."; } return null; } private static bool TryFindStructureNear(FieldGeometry geometry, Vector3[] vertices, float buffer, Func matchesCreator, out bool found) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) found = false; if (buffer <= 0f) { return true; } if ((Object)(object)ZNetScene.instance == (Object)null || (Object)(object)ZoneSystem.instance == (Object)null || ZDOMan.instance == null) { return false; } List list = new List(); List list2 = new List(); HashSet hashSet = new HashSet(); HashSet hashSet2 = new HashSet(); float num = (float)(geometry.MinX - (double)buffer); float num2 = (float)(geometry.MaxX + (double)buffer); float num3 = (float)(geometry.MinZ - (double)buffer); float num4 = (float)(geometry.MaxZ + (double)buffer); for (float num5 = num; num5 <= num2 + 64f; num5 += 64f) { for (float num6 = num3; num6 <= num4 + 64f; num6 += 64f) { hashSet2.Add(ZoneSystem.GetZone(new Vector3(num5, 0f, num6))); if (hashSet2.Count > 4096) { return false; } } } foreach (Vector3 val in vertices) { hashSet2.Add(ZoneSystem.GetZone(val)); } foreach (Vector2s item in hashSet2) { list.Clear(); list2.Clear(); ZDOMan.instance.FindSectorObjects(item, SimulationDistance.OriginalDistance, list, list2); foreach (ZDO item2 in list) { if (!hashSet.Add(item2.m_uid)) { continue; } long num7 = item2.GetLong(ZDOVars.s_creator, 0L); if (num7 == 0L || !matchesCreator(num7)) { continue; } GameObject prefab = ZNetScene.instance.GetPrefab(item2.GetPrefab()); if (!((Object)(object)prefab == (Object)null) && !((Object)(object)prefab.GetComponent() == (Object)null)) { Vector3 position = item2.GetPosition(); if (geometry.DistanceTo(new Point2(position.x, position.z)) <= (double)buffer) { found = true; return true; } } } } return true; } private static void WriteGroup(IReadOnlyList members, string group, bool active) { string text = FieldRegistry.EncodeShape(members.Select((ZDO z) => z.GetPosition())); for (int num = 0; num < members.Count; num++) { ZDO obj = members[num]; obj.SetOwner(ZNet.GetUID()); obj.Set("baseprotection_group", group); obj.Set("baseprotection_order", num); obj.Set("baseprotection_active", active ? 1 : 0); obj.Set("baseprotection_shape", text); } } internal static void RepairAfterDestroyed(string group, long owner, bool wasActive) { try { List allStoneZdos = FieldRegistry.GetAllStoneZdos(); List members = (from z in allStoneZdos where z.GetString("baseprotection_group", "") == @group orderby z.GetInt("baseprotection_order", -1) select z).ToList(); InvalidateApprovals(members); if (members.Count < 2) { foreach (ZDO item in members) { item.SetOwner(ZNet.GetUID()); item.Set("baseprotection_group", ""); item.Set("baseprotection_order", -1); item.Set("baseprotection_active", 0); item.Set("baseprotection_shape", ""); } FieldRegistry.Refresh(); return; } int[] source = PolygonOrdering.Untangle((from z in members select z.GetPosition() into v select new Point2(v.x, v.z)).ToArray()); members = source.Select((int index) => members[index]).ToList(); bool flag = wasActive && members.All((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) == owner) && ValidateProposal(group, owner, members, allStoneZdos) == null; WriteGroup(members, group, flag); FieldRegistry.Refresh(); if (!flag && wasActive) { BaseProtectionPlugin.Instance.LogWarning("Runestone field " + group + " became an inactive draft after a stone was destroyed."); } } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); } } private static void OnFinalize(long sender, ZDOID stoneId) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) if (!RequireOwner(sender, out var playerId)) { return; } try { ZDO zDO = ZDOMan.instance.GetZDO(stoneId); if (!IsStone(zDO) || zDO.GetLong(ZDOVars.s_creator, 0L) != playerId) { Reply(sender, "You can only finish your own runestone field."); return; } Vector3? requesterPosition = GetRequesterPosition(sender); if (!requesterPosition.HasValue || Vector3.Distance(requesterPosition.Value, zDO.GetPosition()) > 6f) { Reply(sender, "Stand beside a draft stone to finish the field."); return; } string group = zDO.GetString("baseprotection_group", ""); if (string.IsNullOrEmpty(group) || zDO.GetInt("baseprotection_active", 1) != 0) { Reply(sender, "This stone is not part of an unfinished draft."); return; } List allStoneZdos = FieldRegistry.GetAllStoneZdos(); List members = (from z in allStoneZdos where z.GetString("baseprotection_group", "") == @group orderby z.GetInt("baseprotection_order", -1) select z).ToList(); if (members.Count < 2 || members.Count > 8 || members.Any((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != playerId || z.GetInt("baseprotection_active", 1) != 0)) { Reply(sender, "The draft has invalid stone data."); return; } int[] source = PolygonOrdering.Untangle((from z in members select z.GetPosition() into v select new Point2(v.x, v.z)).ToArray()); bool flag = !source.Select((int value, int index) => value == index).All((bool equal) => equal); if (flag) { members = source.Select((int index) => members[index]).ToList(); InvalidateApprovals(members); } string text = ValidateProposal(group, playerId, members, allStoneZdos); if (text != null) { if (flag) { WriteGroup(members, group, active: false); FieldRegistry.Refresh(); Reply(sender, "Draft order adjusted. Review the new outline, then try again: " + text); } else { Reply(sender, text); } } else { WriteGroup(members, group, active: true); FieldRegistry.Refresh(); Reply(sender, flag ? $"Field active with {members.Count} stones; polygon order adjusted." : $"Field active with {members.Count} stones."); } } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); Reply(sender, "Finishing failed; check the server log."); } } private static void OnFinishWithStone(long sender, ZDOID draftStoneId, ZDOID newStoneId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (!RequireOwner(sender, out var playerId)) { return; } try { ZDO zDO = ZDOMan.instance.GetZDO(draftStoneId); ZDO zDO2 = ZDOMan.instance.GetZDO(newStoneId); if (!IsStone(zDO) || !IsStone(zDO2) || draftStoneId == newStoneId || zDO.GetLong(ZDOVars.s_creator, 0L) != playerId || zDO2.GetLong(ZDOVars.s_creator, 0L) != playerId) { Reply(sender, "Both stones must be different runestones that you placed."); return; } string group = zDO.GetString("baseprotection_group", ""); if (group.Length == 0 || zDO.GetInt("baseprotection_active", 1) != 0 || zDO2.GetString("baseprotection_group", "").Length != 0) { Reply(sender, "Select a draft stone, then Shift+E an unlinked stone."); return; } Vector3? requesterPosition = GetRequesterPosition(sender); if (!requesterPosition.HasValue || Vector3.Distance(requesterPosition.Value, zDO2.GetPosition()) > 6f) { Reply(sender, "Stand beside the new stone to add and finish the draft."); return; } List allStoneZdos = FieldRegistry.GetAllStoneZdos(); List members = (from z in allStoneZdos where z.GetString("baseprotection_group", "") == @group orderby z.GetInt("baseprotection_order", -1) select z).ToList(); if (members.Count < 2 || members.Count >= 8 || !members.Any((ZDO z) => z.m_uid == draftStoneId) || members.Any((ZDO z) => z.GetLong(ZDOVars.s_creator, 0L) != playerId || z.GetInt("baseprotection_active", 1) != 0)) { Reply(sender, "The draft is full or has invalid stone data."); return; } members.Add(zDO2); int[] source = PolygonOrdering.Untangle((from z in members select z.GetPosition() into v select new Point2(v.x, v.z)).ToArray()); bool flag = !source.Select((int value, int index) => value == index).All((bool equal) => equal); if (flag) { members = source.Select((int index) => members[index]).ToList(); } InvalidateApprovals(members); string text = ValidateProposal(group, playerId, members, allStoneZdos); WriteGroup(members, group, text == null); FieldRegistry.Refresh(); if (text != null) { Reply(sender, $"Draft has {members.Count} stones; could not finish: {text}"); } else { Reply(sender, flag ? $"Field active with {members.Count} stones; polygon order adjusted." : $"Field active with {members.Count} stones."); } } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); Reply(sender, "Adding and finishing failed; check the server log."); } } private static void OnUnlink(long sender, ZDOID stoneId) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) if (!RequireOwner(sender, out var playerId)) { return; } try { ZDO zDO = ZDOMan.instance.GetZDO(stoneId); if (!IsStone(zDO) || zDO.GetLong(ZDOVars.s_creator, 0L) != playerId) { Reply(sender, "You can only unlink stones that you placed."); return; } Vector3? requesterPosition = GetRequesterPosition(sender); if (!requesterPosition.HasValue || Vector3.Distance(requesterPosition.Value, zDO.GetPosition()) > 6f) { Reply(sender, "Stand beside the stone to unlink it."); return; } string group = zDO.GetString("baseprotection_group", ""); if (string.IsNullOrEmpty(group)) { Reply(sender, "This stone is not linked."); return; } ZDO[] array = (from z in FieldRegistry.GetAllStoneZdos() where z.GetString("baseprotection_group", "") == @group orderby z.GetInt("baseprotection_order", -1) select z).ToArray(); ZDO[] array2 = array.Where((ZDO member) => member.m_uid != stoneId).ToArray(); InvalidateApprovals(array); zDO.SetOwner(ZNet.GetUID()); zDO.Set("baseprotection_group", ""); zDO.Set("baseprotection_order", -1); zDO.Set("baseprotection_active", 0); zDO.Set("baseprotection_shape", ""); if (array2.Length >= 2) { WriteGroup(array2, group, active: false); } else { ZDO[] array3 = array2; foreach (ZDO obj in array3) { obj.SetOwner(ZNet.GetUID()); obj.Set("baseprotection_group", ""); obj.Set("baseprotection_order", -1); obj.Set("baseprotection_active", 0); obj.Set("baseprotection_shape", ""); } } FieldRegistry.Refresh(); Reply(sender, (array2.Length < 2) ? "Field deactivated." : $"Draft now has {array2.Length} stones. Shift+E to finish it."); } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); Reply(sender, "Unlinking failed; check the server log."); } } } [HarmonyPatch(typeof(WearNTear), "UpdateWear")] internal static class RainWearPatch { private static void Prefix(WearNTear __instance, out bool __state) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) __state = false; if (__instance.m_noRoofWear) { BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; if (StoneAccess.IsStone((Component)(object)__instance) || (!((Object)(object)instance == (Object)null) && instance.PreventRainWearInFields.Value && !((Object)(object)((Component)__instance).GetComponent() == (Object)null) && FieldRegistry.Contains(((Component)__instance).transform.position))) { __instance.m_noRoofWear = false; __state = true; } } } private static void Postfix(WearNTear __instance, bool __state) { if (__state) { __instance.m_noRoofWear = true; } } private static Exception? Finalizer(WearNTear __instance, Exception? __exception, bool __state) { if (__state) { __instance.m_noRoofWear = true; } return __exception; } } public sealed class RunestoneInteraction : MonoBehaviour, Hoverable, Interactable, IPlaced { private static ZDOID _selected = ZDOID.None; private static ZDOID _pendingTarget = ZDOID.None; private static ZDOID _pendingSource = ZDOID.None; private static ZDOID _alignmentAnchor = ZDOID.None; private static bool _hasAlignmentOrigin; private static bool _anchorOwned; private static bool _selectedLinked; private static bool _selectedWasDraft; private static string _selectedGroup = ""; private static string _anchorGroup = ""; private static Point2 _alignmentOrigin; private static Point2[] _anchorStones = Array.Empty(); private static readonly List<(ZDOID Id, Point2 Position)> _placedStones = new List<(ZDOID, Point2)>(); private static Point2[] _placedPoints = Array.Empty(); private static ZDOMan? _selectionWorld; private static ZDOMan? _alignmentWorld; private static ZDOMan? _placementWorld; private static int _anchorRevision; private static int _pendingAnchorRevision = -1; private ZNetView? _view; private static string UseKey { get { ZInput instance = ZInput.instance; string text = ((instance != null) ? instance.GetBoundKeyString("Use", true) : null); if (!string.IsNullOrWhiteSpace(text)) { return text; } return "Use"; } } private void Awake() { _view = ((Component)this).GetComponent(); FieldRegistry.Add(this); } private void OnDestroy() { FieldRegistry.Remove(this); } public void OnPlaced() { //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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) if (_view == null) { _view = ((Component)this).GetComponent(); } ZNetView? view = _view; ZDO zdo = ((view != null) ? view.GetZDO() : null); if (zdo == null) { return; } ZDO zdo2 = zdo; Player localPlayer = Player.m_localPlayer; if (IsOwnedBy(zdo2, (localPlayer != null) ? localPlayer.GetPlayerID() : 0)) { UpdateSelectionCache(); if (_placementWorld != ZDOMan.instance) { _placedStones.Clear(); _placedPoints = Array.Empty(); _placementWorld = ZDOMan.instance; } Vector3 position = zdo.GetPosition(); _placedStones.RemoveAll(((ZDOID Id, Point2 Position) stone) => stone.Id == zdo.m_uid); _placedStones.Add((zdo.m_uid, new Point2(position.x, position.z))); if (_placedStones.Count > 2) { _placedStones.RemoveAt(0); } _placedPoints = _placedStones.ConvertAll(((ZDOID Id, Point2 Position) stone) => stone.Position).ToArray(); SetAlignmentAnchor(zdo.m_uid); Notify("Runestone selected for Ctrl snapping."); } } public string GetHoverName() { return "Linked Runestone"; } public float GetHoverOffset() { return 0f; } private static string KeyPrompt(string keys) { return "[" + keys + "]"; } private static bool IsOwnedBy(ZDO zdo, long playerId) { if (playerId != 0L) { return zdo.GetLong(ZDOVars.s_creator, 0L) == playerId; } return false; } public string GetHoverText() { //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f5: Unknown result type (might be due to invalid IL or missing references) //IL_0427: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Unknown result type (might be due to invalid IL or missing references) //IL_04d0: Unknown result type (might be due to invalid IL or missing references) //IL_04d5: Unknown result type (might be due to invalid IL or missing references) //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04ee: Unknown result type (might be due to invalid IL or missing references) //IL_052d: Unknown result type (might be due to invalid IL or missing references) //IL_052f: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_0507: Unknown result type (might be due to invalid IL or missing references) //IL_0509: Unknown result type (might be due to invalid IL or missing references) ZNetView? view = _view; ZDO val = ((view != null) ? view.GetZDO() : null); string text = ((val != null) ? val.GetString("baseprotection_group", "") : null) ?? ""; bool flag = val != null && text.Length != 0 && val.GetInt("baseprotection_active", 1) == 0; string text2 = ((val == null) ? "Loading" : ((text.Length == 0) ? "Unlinked" : (flag ? "Draft" : "Active"))); if (val == null) { return "Linked Runestone (" + text2 + ")\nRunestone network data is loading"; } Player localPlayer = Player.m_localPlayer; long num = ((localPlayer != null) ? localPlayer.GetPlayerID() : 0); if (num == 0L) { return "Linked Runestone (" + text2 + ")\nPlayer identity is loading"; } if (val.GetLong(ZDOVars.s_creator, 0L) == 0L) { return "Linked Runestone (" + text2 + ")\nRunestone ownership is loading"; } if (!IsOwnedBy(val, num)) { string text3 = "Linked Runestone (" + text2 + ")\nPlaced by another player\n" + KeyPrompt(UseKey) + " Set Ctrl snap anchor (alignment only)"; HashSet creators; bool flag2 = CreatorConsent.TryParse(val.GetString("baseprotection_consents", ""), out creators) && creators.Contains(num); if (flag) { text3 = text3 + "\n" + KeyPrompt("Ctrl+Shift+" + UseKey) + " " + (flag2 ? "Withdraw your structure approval" : "Approve near structures you built"); } else if (text.Length != 0 && flag2) { text3 = text3 + "\n" + KeyPrompt("Ctrl+Shift+" + UseKey) + " Withdraw approval (deactivates field)"; } if (!(_alignmentAnchor == val.m_uid)) { return text3; } return text3 + "\nCtrl snap anchor selected"; } string text4 = "Linked Runestone (" + text2 + ")\n" + KeyPrompt(UseKey) + " Select / add " + KeyPrompt("Ctrl+" + UseKey) + " Unlink"; if (_selected == val.m_uid) { text4 += "\nSelected for next placement"; } else if (text.Length != 0 && text == _selectedGroup) { text4 = text4 + "\n" + KeyPrompt(UseKey) + " Select for next placement"; } if (_alignmentAnchor == val.m_uid) { text4 += "\nCtrl snap anchor selected"; } if (flag) { text4 = text4 + "\n" + KeyPrompt("Shift+" + UseKey) + " Finish"; } else if (text.Length == 0 && _selected != ZDOID.None && ZDOMan.instance != null) { ZDO zDO = ZDOMan.instance.GetZDO(_selected); if ((zDO != null && zDO.GetString("baseprotection_group", "").Length != 0 && zDO.GetInt("baseprotection_active", 1) == 0) || (zDO == null && _selectedWasDraft)) { text4 = text4 + "\n" + KeyPrompt("Shift+" + UseKey) + " Add + finish"; } } if (_selected == ZDOID.None || ZDOMan.instance == null) { return text4; } ZDO zDO2 = ZDOMan.instance.GetZDO(_selected); if (zDO2 == null || zDO2.GetPrefab() != StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone")) { return text4; } string text5 = zDO2.GetString("baseprotection_group", ""); string text6 = val.GetString("baseprotection_group", ""); if (text5.Length != 0 && text6.Length != 0 && _selected != val.m_uid) { return text4; } ZDO obj = ((text5.Length == 0 && text6.Length != 0) ? val : zDO2); ZDO val2 = ((obj == val) ? zDO2 : val); Vector3 position = obj.GetPosition(); Vector3 a = position; string text7 = obj.GetString("baseprotection_group", ""); if (FieldRegistry.TryDecodeShape(obj.GetString("baseprotection_shape", ""), out Point2[] points) || (text7.Length != 0 && FieldRegistry.TryGetGroupOutline(text7, out points))) { position.x = (float)points[0].X; position.z = (float)points[0].Z; a.x = (float)points[^1].X; a.z = (float)points[^1].Z; } Vector3 position2 = val2.GetPosition(); float value = BaseProtectionPlugin.Instance.MaxEdge.Value; if (_selected == val.m_uid) { if (!flag) { return text4; } return text4 + "\nClosing edge to first: " + Metric(a, position, value); } return text4 + "\nNext edge: " + Metric(a, position2, value) + "\nDistance from first: " + Metric(position, position2, value) + " (closing edge if finished here)"; } public bool Interact(Humanoid user, bool hold, bool alt) { //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_02fd: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_038a: Unknown result type (might be due to invalid IL or missing references) //IL_0390: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) if (!hold) { Player val = (Player)(object)((user is Player) ? user : null); if (val != null) { if (_view == null) { _view = ((Component)this).GetComponent(); } ZNetView? view = _view; ZDO val2 = ((view != null) ? view.GetZDO() : null); if (val2 == null) { Notify("Runestone network data is not ready. Try again shortly."); return true; } long playerID = val.GetPlayerID(); if (playerID == 0L) { Notify("Player identity is not ready. Try again shortly."); return true; } UpdateSelectionCache(); bool flag = Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305); bool flag2 = Input.GetKey((KeyCode)304) || Input.GetKey((KeyCode)303); if (!IsOwnedBy(val2, playerID)) { if (val2.GetLong(ZDOVars.s_creator, 0L) == 0L) { Notify("Runestone ownership is not ready. Try again shortly."); } else if (flag && flag2 && !string.IsNullOrEmpty(val2.GetString("baseprotection_group", ""))) { NetworkCommands.RequestToggleConsent(val2.m_uid); } else if (flag || flag2) { Notify("Only the player who placed this stone can link or unlink it."); } else { SetAlignmentAnchor(val2.m_uid); Notify("Ctrl snap anchor set (alignment only)."); } return true; } if (flag) { ClearLinkSelection(); NetworkCommands.RequestUnlink(val2.m_uid); return true; } if (flag2) { object obj; if (!(_selected == ZDOID.None)) { ZDOMan instance = ZDOMan.instance; obj = ((instance != null) ? instance.GetZDO(_selected) : null); } else { obj = null; } ZDO val3 = (ZDO)obj; if (string.IsNullOrEmpty(val2.GetString("baseprotection_group", "")) && _selected != ZDOID.None && ((val3 != null && !string.IsNullOrEmpty(val3.GetString("baseprotection_group", "")) && val3.GetInt("baseprotection_active", 1) == 0) || (val3 == null && _selectedWasDraft))) { ZDOID selected = _selected; ClearLinkSelection(); _pendingTarget = val2.m_uid; _pendingAnchorRevision = _anchorRevision; NetworkCommands.RequestFinishWithStone(selected, val2.m_uid); } else { ClearLinkSelection(); NetworkCommands.RequestFinalize(val2.m_uid); } return true; } SetAlignmentAnchor(val2.m_uid); if (_selected == ZDOID.None || _selected == val2.m_uid) { SelectForLink(val2.m_uid); Notify("Runestone selected. Use an unlinked stone or an existing field to link it."); return true; } ZDOMan instance2 = ZDOMan.instance; ZDO obj2 = ((instance2 != null) ? instance2.GetZDO(_selected) : null); string text = val2.GetString("baseprotection_group", ""); string text2 = ((obj2 != null) ? obj2.GetString("baseprotection_group", "") : null) ?? _selectedGroup; bool flag3 = ((obj2 == null) ? _selectedLinked : (text2.Length != 0)); BaseProtectionPlugin.Instance.LogInfo($"Runestone interaction: selected linked={flag3}, " + $"hovered linked={text.Length != 0}."); if (text.Length != 0 && flag3) { if (text2.Length != 0 && text != text2) { Notify("Both stones belong to different fields. Select an unlinked stone to add."); return true; } SelectForLink(val2.m_uid); Notify("Runestone selected for alignment. Use an unlinked stone to add to this field."); return true; } ZDOMan instance3 = ZDOMan.instance; ZDO val4 = ((instance3 != null) ? instance3.GetZDO(_selected) : null); _pendingTarget = ((((val4 == null) ? (!_selectedLinked) : string.IsNullOrEmpty(val4.GetString("baseprotection_group", ""))) && text.Length != 0) ? _selected : val2.m_uid); _pendingSource = _selected; _pendingAnchorRevision = _anchorRevision; Notify("Linking runestones..."); NetworkCommands.RequestLink(_selected, val2.m_uid); return true; } } return false; } public bool UseItem(Humanoid user, ItemData item) { return false; } internal static bool TryGetAlignmentAnchors(out Point2 origin, out Point2[] cornerStones) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) UpdateSelectionCache(); origin = _alignmentOrigin; cornerStones = Array.Empty(); if (_anchorOwned) { if (_anchorGroup.Length != 0) { cornerStones = _anchorStones; } else if (_placementWorld == ZDOMan.instance && _placedStones.Count == 2 && (_placedStones[0].Id == _alignmentAnchor || _placedStones[1].Id == _alignmentAnchor)) { cornerStones = _placedPoints; } } if (_alignmentAnchor != ZDOID.None) { return _hasAlignmentOrigin; } return false; } internal static void UpdateSelectionCache() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) if (_selected != ZDOID.None && _selectionWorld != ZDOMan.instance) { ClearLinkSelection(); } if (_alignmentAnchor != ZDOID.None && _alignmentWorld != ZDOMan.instance) { ClearAlignmentAnchor(); } if (ZDOMan.instance == null) { return; } if (_selected != ZDOID.None) { ZDO zDO = ZDOMan.instance.GetZDO(_selected); if (zDO != null) { if (zDO.GetPrefab() == StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone")) { Player localPlayer = Player.m_localPlayer; if (IsOwnedBy(zDO, (localPlayer != null) ? localPlayer.GetPlayerID() : 0)) { string text = (_selectedGroup = zDO.GetString("baseprotection_group", "")); _selectedLinked = text.Length != 0; _selectedWasDraft = text.Length != 0 && zDO.GetInt("baseprotection_active", 1) == 0; goto IL_00e8; } } ClearLinkSelection(); } } goto IL_00e8; IL_00e8: if (_alignmentAnchor == ZDOID.None) { return; } ZDO zDO2 = ZDOMan.instance.GetZDO(_alignmentAnchor); if (zDO2 == null) { return; } if (zDO2.GetPrefab() != StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone")) { ClearAlignmentAnchor(); return; } Vector3 position = zDO2.GetPosition(); _alignmentOrigin = new Point2(position.x, position.z); _hasAlignmentOrigin = true; Player localPlayer2 = Player.m_localPlayer; _anchorOwned = IsOwnedBy(zDO2, (localPlayer2 != null) ? localPlayer2.GetPlayerID() : 0); _anchorGroup = zDO2.GetString("baseprotection_group", ""); _anchorStones = Array.Empty(); if (_anchorOwned && _anchorGroup.Length != 0 && (FieldRegistry.TryDecodeShape(zDO2.GetString("baseprotection_shape", ""), out Point2[] points) || FieldRegistry.TryGetGroupOutline(_anchorGroup, out points)) && points.Length != 0) { _anchorStones = points; } } private static void SelectForLink(ZDOID uid) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) _selected = uid; _selectionWorld = ZDOMan.instance; _selectedLinked = false; _selectedWasDraft = false; _selectedGroup = ""; UpdateSelectionCache(); } private static void SetAlignmentAnchor(ZDOID uid) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (_alignmentAnchor != uid || _alignmentWorld != ZDOMan.instance) { _alignmentAnchor = uid; _alignmentWorld = ZDOMan.instance; _hasAlignmentOrigin = false; _anchorOwned = false; _anchorGroup = ""; _anchorStones = Array.Empty(); } _anchorRevision++; UpdateSelectionCache(); } private static void ClearLinkSelection() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) _selected = ZDOID.None; _pendingTarget = ZDOID.None; _pendingSource = ZDOID.None; _pendingAnchorRevision = -1; _selectedLinked = false; _selectedWasDraft = false; _selectedGroup = ""; _selectionWorld = null; } private static void ClearAlignmentAnchor() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) _alignmentAnchor = ZDOID.None; _hasAlignmentOrigin = false; _anchorOwned = false; _anchorGroup = ""; _anchorStones = Array.Empty(); _alignmentOrigin = default(Point2); _alignmentWorld = null; _anchorRevision++; } internal static void ClearSelection() { ClearLinkSelection(); ClearAlignmentAnchor(); _placedStones.Clear(); _placedPoints = Array.Empty(); _placementWorld = null; } internal static void OnStoneDestroyed(ZDOID uid) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (_selected == uid) { ClearLinkSelection(); } else if (_pendingTarget == uid) { _pendingTarget = ZDOID.None; } if (_alignmentAnchor == uid) { ClearAlignmentAnchor(); } if (_placedStones.RemoveAll(((ZDOID Id, Point2 Position) stone) => stone.Id == uid) > 0) { _placedPoints = _placedStones.ConvertAll(((ZDOID Id, Point2 Position) stone) => stone.Position).ToArray(); } } private static string Metric(Vector3 a, Vector3 b, float maximum) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) float num = a.x - b.x; float num2 = a.z - b.z; float num3 = Mathf.Sqrt(num * num + num2 * num2); string text = $"{num3:0.0} m / {maximum:0.#} m max"; if (!(num3 > maximum)) { return text; } return "" + text + ""; } internal static void Notify(string message) { if ((Object)(object)MessageHud.instance != (Object)null) { MessageHud.instance.ShowMessage((MessageType)2, message, 0, (Sprite)null, false, true); } } internal static void OnServerReply(string message) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) if (message == "You can only link stones that you placed." && _pendingSource != ZDOID.None && _selected == _pendingSource) { ClearLinkSelection(); Notify(message.Replace("Shift+E", "Shift+" + UseKey)); return; } if (_pendingTarget != ZDOID.None) { if (message.StartsWith("Draft has ")) { ZDOID pendingTarget = _pendingTarget; bool flag = _anchorRevision == _pendingAnchorRevision; SelectForLink(pendingTarget); _selectedLinked = true; _selectedWasDraft = true; if (flag) { SetAlignmentAnchor(pendingTarget); } } _pendingTarget = ZDOID.None; } _pendingSource = ZDOID.None; _pendingAnchorRevision = -1; Notify(message.Replace("Shift+E", "Shift+" + UseKey)); } } [HarmonyPatch(typeof(Player), "Interact", new Type[] { typeof(GameObject), typeof(bool), typeof(bool) })] internal static class RunestoneInteractPatch { private static bool Prefix(Player __instance, GameObject go, bool hold, bool alt) { if ((Object)(object)go == (Object)null) { return true; } RunestoneInteraction componentInParent = go.GetComponentInParent(); if ((Object)(object)componentInParent == (Object)null) { return true; } if (((Character)__instance).InAttack() || ((Character)__instance).InDodge()) { return false; } componentInParent.Interact((Humanoid)(object)__instance, hold, alt); return false; } } internal sealed class SafeFloatRange : AcceptableValueBase { private readonly float _minimum; private readonly float _maximum; private readonly float _fallback; internal SafeFloatRange(float minimum, float maximum, float fallback) : base(typeof(float)) { _minimum = minimum; _maximum = maximum; _fallback = fallback; } public override bool IsValid(object value) { if (value is float num && !float.IsNaN(num) && !float.IsInfinity(num) && num >= _minimum) { return num <= _maximum; } return false; } public override object Clamp(object value) { if (!(value is float num) || float.IsNaN(num)) { return _fallback; } if (float.IsNegativeInfinity(num) || num < _minimum) { return _minimum; } if (float.IsPositiveInfinity(num) || num > _maximum) { return _maximum; } return num; } public override string ToDescriptionString() { return $"Accepted range: {_minimum:0.##} to {_maximum:0.##} (finite)."; } } internal sealed class SafeIntegerRange : AcceptableValueBase { private readonly int _minimum; private readonly int _maximum; internal SafeIntegerRange(int minimum, int maximum) : base(typeof(int)) { _minimum = minimum; _maximum = maximum; } public override bool IsValid(object value) { if (value is int num && num >= _minimum) { return num <= _maximum; } return false; } public override object Clamp(object value) { if (!(value is int num)) { return _minimum; } if (num < _minimum) { return _minimum; } return (num > _maximum) ? _maximum : num; } public override string ToDescriptionString() { return $"Accepted range: {_minimum} to {_maximum}."; } } internal static class SpawnRules { private static readonly SpawnPolicy Policy = new SpawnPolicy(); private static string _lastOverrides = ""; private static string _lastPrefabCheck = ""; private static SpawnPolicy _current = new SpawnPolicy(); internal static bool WaitingForFieldSnapshot { get { if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && BaseProtectionPlugin.FeaturesAvailable) { return !FieldRegistry.HasServerSnapshot; } return false; } } internal static bool ShouldBlock(SpawnSource source, string? creature = null, bool locationAllowsPlayerBase = false) { BaseProtectionPlugin instance = BaseProtectionPlugin.Instance; Policy.LocationPoints = instance.LocationPoints.Value; Policy.PhysicalSpawners = instance.PhysicalSpawners.Value; string text = instance.BiomeCreatureOverrides.Value ?? ""; if (text != _lastOverrides) { _lastOverrides = text; SpawnPolicy spawnPolicy = new SpawnPolicy { LocationPoints = Policy.LocationPoints, PhysicalSpawners = Policy.PhysicalSpawners }; CreatureOverrideParseResult creatureOverrideParseResult = CreatureOverrideParser.Parse(text); foreach (string warning in creatureOverrideParseResult.Warnings) { instance.LogWarning("Biome creature overrides: " + warning); } foreach (KeyValuePair item in creatureOverrideParseResult.Blocked) { spawnPolicy.SetBiomeCreatureBlocked(item.Key, item.Value); } _current = spawnPolicy; } if (text != _lastPrefabCheck && (Object)(object)ZNetScene.instance != (Object)null) { _lastPrefabCheck = text; foreach (string key in CreatureOverrideParser.Parse(text).Blocked.Keys) { if ((Object)(object)ZNetScene.instance.GetPrefab(key) == (Object)null) { instance.LogWarning("Biome creature override '" + key + "' is not a registered prefab. Check its exact internal name; the entry will remain in the config."); } } } _current.LocationPoints = Policy.LocationPoints; _current.PhysicalSpawners = Policy.PhysicalSpawners; return _current.ShouldBlock(source, creature, locationAllowsPlayerBase); } } [HarmonyPatch(typeof(SpawnSystem), "UpdateSpawnList")] internal static class SpawnListContextPatch { [ThreadStatic] internal static bool IsRaid; private static void Prefix(bool eventSpawners, out bool __state) { __state = IsRaid; IsRaid = eventSpawners; } private static void Postfix(bool __state) { IsRaid = __state; } private static Exception? Finalizer(Exception? __exception, bool __state) { IsRaid = __state; return __exception; } } [HarmonyPatch(typeof(SpawnSystem), "UpdateSpawning")] internal static class SpawnSnapshotGatePatch { private static bool Prefix() { return !SpawnRules.WaitingForFieldSnapshot; } } [HarmonyPatch(typeof(SpawnSystem), "IsSpawnPointGood")] internal static class BiomeAndRaidSpawnPatch { private static void Postfix(SpawnData spawn, ref Vector3 spawnPoint, ref bool __result) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (__result) { if (SpawnRules.WaitingForFieldSnapshot) { __result = false; } else if (FieldRegistry.Contains(spawnPoint) && SpawnRules.ShouldBlock(SpawnListContextPatch.IsRaid ? SpawnSource.Raid : SpawnSource.Biome, ((Object)(object)spawn.m_prefab != (Object)null) ? ((Object)spawn.m_prefab).name : null)) { __result = false; } } } } [HarmonyPatch(typeof(CreatureSpawner), "UpdateSpawner")] internal static class LocationSpawnPatch { private static bool Prefix(CreatureSpawner __instance) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (SpawnRules.WaitingForFieldSnapshot) { return false; } if (!FieldRegistry.Contains(((Component)__instance).transform.position)) { return true; } return !SpawnRules.ShouldBlock(SpawnSource.LocationPoint, null, __instance.m_spawnInPlayerBase); } } [HarmonyPatch(typeof(SpawnArea), "FindSpawnPoint")] internal static class PhysicalSpawnerPatch { private static void Postfix(ref Vector3 point, ref bool __result) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (__result && (SpawnRules.WaitingForFieldSnapshot || (FieldRegistry.Contains(point) && SpawnRules.ShouldBlock(SpawnSource.PhysicalSpawner)))) { __result = false; } } } internal static class StoneAccess { internal static readonly int StonePrefabHash = StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone"); internal static bool IsStoneZdo(ZDO? zdo) { if (zdo != null) { return zdo.GetPrefab() == StonePrefabHash; } return false; } internal static bool IsStone(Component component) { if ((Object)(object)component != (Object)null) { return (Object)(object)component.GetComponent() != (Object)null; } return false; } private static ZDO? GetStoneZdo(Component component) { if (!IsStone(component)) { return null; } ZNetView component2 = component.GetComponent(); ZDO val = ((component2 != null) ? component2.GetZDO() : null); if (!IsStoneZdo(val)) { return null; } return val; } internal static bool CanLocalEdit(Player player, Piece piece) { ZDO stoneZdo = GetStoneZdo((Component)(object)piece); if (stoneZdo == null || player.GetPlayerID() == 0L) { return false; } if (stoneZdo.GetLong(ZDOVars.s_creator, 0L) != player.GetPlayerID()) { if ((Object)(object)ZNet.instance != (Object)null) { return ZNet.instance.LocalPlayerIsAdminOrHost(); } return false; } return true; } internal static void AdoptServerOwnership() { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || ZDOMan.instance == null) { return; } long uID = ZNet.GetUID(); if (uID == 0L) { return; } foreach (ZDO allStoneZdo in FieldRegistry.GetAllStoneZdos()) { if (allStoneZdo.GetOwner() != uID) { allStoneZdo.SetOwner(uID); } } } private static bool TryGetServerRequester(long sender, out long playerId, out ZDOID characterId, out Vector3 position, out bool admin, out string denial) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) playerId = 0L; characterId = ZDOID.None; position = default(Vector3); admin = false; denial = "The server could not verify the removal request."; ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer() || !StoneRoutedPeerContext.Matches(sender)) { return false; } if (sender == ZNet.GetUID()) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } playerId = localPlayer.GetPlayerID(); characterId = ((Character)localPlayer).GetZDOID(); position = ((Component)localPlayer).transform.position; admin = true; if (playerId == 0L || characterId == ZDOID.None) { return false; } denial = ""; return true; } ZNetPeer peer = instance.GetPeer(sender); if (peer == null || ((ZDOID)(ref peer.m_characterID)).UserID != sender || peer.m_socket == null) { return false; } ZDOMan instance2 = ZDOMan.instance; ZDO val = ((instance2 != null) ? instance2.GetZDO(peer.m_characterID) : null); if (val == null) { denial = "The server cannot find your character. Rejoin and try again."; return false; } playerId = val.GetLong(ZDOVars.s_playerID, 0L); characterId = peer.m_characterID; position = val.GetPosition(); admin = instance.IsAdmin(peer.m_socket.GetHostName()); if (playerId == 0L) { denial = "Your character identity is still loading. Try again shortly."; return false; } denial = ""; return true; } private static bool CanServerEdit(long sender, ZDO stone, out ZDOID characterId, out Vector3 position, out string denial) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) characterId = ZDOID.None; position = default(Vector3); denial = "The server could not verify the removal request."; if (!TryGetServerRequester(sender, out var playerId, out characterId, out position, out var admin, out denial)) { return false; } if (admin || stone.GetLong(ZDOVars.s_creator, 0L) == playerId) { return true; } denial = "Only the stone owner or a server admin can remove it."; return false; } internal static bool CanServerRemove(ZDO? stone, long sender, out string denial) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) denial = "The runestone is not ready on the server. Try again shortly."; if (stone == null || !IsStoneZdo(stone)) { return false; } if (!CanServerEdit(sender, stone, out var _, out var position, out denial)) { return false; } if (Vector3.Distance(position, stone.GetPosition()) <= 6f) { return true; } denial = "Move closer to the runestone and try again."; return false; } internal static bool CanServerRepair(ZDO? stone, long sender, out string denial) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) denial = "The runestone is not ready on the server. Try again shortly."; if (stone == null || !IsStoneZdo(stone)) { return false; } if (!TryGetServerRequester(sender, out var _, out var _, out var position, out var _, out denial)) { return false; } if (Vector3.Distance(position, stone.GetPosition()) <= 6f) { return true; } denial = "Move closer to the runestone and try again."; return false; } } [HarmonyPatch(typeof(ZRoutedRpc), "RPC_RoutedRPC", new Type[] { typeof(ZRpc), typeof(ZPackage) })] internal static class StoneRoutedPeerContext { private readonly struct State { internal readonly bool Incoming; internal readonly long PeerId; internal State(bool incoming, long peerId) { Incoming = incoming; PeerId = peerId; } } [ThreadStatic] private static bool _incoming; [ThreadStatic] private static long _peerId; internal static bool Matches(long sender) { if (!_incoming) { return sender == ZNet.GetUID(); } if (_peerId != 0L) { return sender == _peerId; } return false; } internal static bool IsServerOrigin(long sender) { if (!_incoming) { return sender == ZNet.GetUID(); } return false; } private static bool Prefix(ZRpc rpc, ZPackage pkg, out State __state) { __state = new State(_incoming, _peerId); ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer()) { return true; } _incoming = true; _peerId = 0L; foreach (ZNetPeer peer in instance.GetPeers()) { if (peer.m_rpc == rpc) { _peerId = peer.m_uid; break; } } if (_peerId == 0L || pkg == null) { Restore(__state); return false; } int pos = pkg.GetPos(); try { if (pkg.Size() - pos < 16) { Restore(__state); return false; } pkg.ReadLong(); if (pkg.ReadLong() == _peerId) { return true; } Restore(__state); return false; } catch (Exception) { Restore(__state); return false; } finally { pkg.SetPos(pos); } } private static void Postfix(State __state) { Restore(__state); } private static Exception? Finalizer(Exception? __exception, State __state) { Restore(__state); return __exception; } private static void Restore(State state) { _incoming = state.Incoming; _peerId = state.PeerId; } } [HarmonyPatch(typeof(ZDO), "SetOwner", new Type[] { typeof(long) })] internal static class RunestoneServerOwnershipPatch { private static void Prefix(ZDO __instance, ref long uid) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && StoneAccess.IsStoneZdo(__instance) && ZNet.GetUID() != 0L) { uid = ZNet.GetUID(); } } } [HarmonyPatch(typeof(ZDO), "Deserialize", new Type[] { typeof(ZPackage) })] internal static class RunestoneDeserializedOwnershipPatch { private static void Postfix(ZDO __instance) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !StoneAccess.IsStoneZdo(__instance)) { return; } long uID = ZNet.GetUID(); if (uID == 0L) { return; } if (__instance.GetOwner() != uID) { __instance.SetOwner(uID); } if (RunestoneZdoDataPatch.BecameStoneFromClient(__instance.m_uid)) { __instance.Set("baseprotection_group", ""); __instance.Set("baseprotection_order", -1); __instance.Set("baseprotection_active", 0); __instance.Set("baseprotection_shape", ""); __instance.Set("baseprotection_consents", ""); } if (RunestoneZdoDataPatch.HasForeignCreatorUid(__instance.m_uid)) { BaseProtectionPlugin.Instance.LogWarning($"Discarding runestone {__instance.m_uid} created with another peer's ZDO ID."); ZDOMan instance = ZDOMan.instance; if (instance != null) { instance.DestroyZDO(__instance); } } } } [HarmonyPatch(typeof(ZDOMan), "RPC_DestroyZDO", new Type[] { typeof(long), typeof(ZPackage) })] internal static class RunestoneDestroyZdoPatch { private static bool Prefix(ZDOMan __instance, long sender, ref ZPackage pkg) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Expected O, but got Unknown //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer()) { return true; } if (StoneRoutedPeerContext.IsServerOrigin(sender)) { return true; } if (!StoneRoutedPeerContext.Matches(sender) || pkg == null) { return false; } ZPackage val = pkg; int pos = val.GetPos(); try { if (val.Size() - pos < 4) { return false; } int num = val.ReadInt(); if (num < 0 || num > (val.Size() - val.GetPos()) / 12) { return false; } List list = new List(num); bool flag = false; for (int i = 0; i < num; i++) { ZDOID val2 = val.ReadZDOID(); if (StoneAccess.IsStoneZdo(__instance.GetZDO(val2))) { flag = true; } else { list.Add(val2); } } if (!flag) { return true; } if (list.Count == 0) { return false; } ZPackage val3 = new ZPackage(); val3.Write(list.Count); foreach (ZDOID item in list) { val3.Write(item); } val3.SetPos(0); pkg = val3; return true; } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning($"Discarded malformed DestroyZDO packet from peer {sender}: {ex.Message}"); return false; } finally { val.SetPos(pos); } } } [HarmonyPatch(typeof(ZDOMan), "RPC_ZDOData", new Type[] { typeof(ZRpc), typeof(ZPackage) })] internal static class RunestoneZdoDataPatch { private readonly struct ReceiveState { internal readonly HashSet? Candidates; internal readonly long PeerUid; internal ReceiveState(HashSet? candidates, long peerUid) { Candidates = candidates; PeerUid = peerUid; } } [ThreadStatic] private static HashSet? _becameStoneCandidates; [ThreadStatic] private static long _sendingPeerUid; internal static bool BecameStoneFromClient(ZDOID id) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return _becameStoneCandidates?.Contains(id) ?? false; } internal static bool HasForeignCreatorUid(ZDOID id) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) if (BecameStoneFromClient(id) && _sendingPeerUid != 0L) { return ((ZDOID)(ref id)).UserID != _sendingPeerUid; } return false; } private static bool IsProtected(ZDOMan manager, ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ZDO zDO = manager.GetZDO(id); if (StoneAccess.IsStoneZdo(zDO)) { return zDO.GetOwner() == ZNet.GetUID(); } return false; } private static bool Prefix(ZDOMan __instance, ZRpc rpc, ref ZPackage pkg, out ReceiveState __state) { __state = new ReceiveState(_becameStoneCandidates, _sendingPeerUid); _becameStoneCandidates = null; _sendingPeerUid = 0L; if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return true; } if (pkg == null) { return false; } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_rpc == rpc) { _sendingPeerUid = peer.m_uid; break; } } ZPackage val = pkg; int pos = val.GetPos(); try { if (!TryScan(__instance, val, out bool changed, out HashSet candidates)) { return false; } if (!changed) { _becameStoneCandidates = candidates; return true; } val.SetPos(pos); if (!TryCopyAllowed(__instance, val, out ZPackage filtered)) { return false; } filtered.SetPos(0); pkg = filtered; _becameStoneCandidates = candidates; return true; } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Discarded malformed ZDOData packet: " + ex.Message); return false; } finally { val.SetPos(pos); } } private static void Postfix(ReceiveState __state) { Restore(__state); } private static Exception? Finalizer(Exception? __exception, ReceiveState __state) { Restore(__state); return __exception; } private static void Restore(ReceiveState state) { _becameStoneCandidates = state.Candidates; _sendingPeerUid = state.PeerUid; } private static bool TryScan(ZDOMan manager, ZPackage packet, out bool changed, out HashSet candidates) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) changed = false; candidates = new HashSet(); if (packet.Size() - packet.GetPos() < 4) { return false; } int num = packet.ReadInt(); if (num < 0 || num > (packet.Size() - packet.GetPos()) / 12) { return false; } for (int i = 0; i < num; i++) { if (IsProtected(manager, packet.ReadZDOID())) { changed = true; } } while (true) { if (packet.Size() - packet.GetPos() < 12) { return false; } ZDOID val = packet.ReadZDOID(); if (((ZDOID)(ref val)).IsNone()) { return packet.GetPos() == packet.Size(); } if (!StoneAccess.IsStoneZdo(manager.GetZDO(val))) { candidates.Add(val); } if (packet.Size() - packet.GetPos() < 30) { return false; } packet.ReadUShort(); packet.ReadUInt(); packet.ReadLong(); packet.ReadVector3(); int num2 = packet.ReadInt(); if (num2 < 0 || num2 > packet.Size() - packet.GetPos()) { break; } packet.SetPos(packet.GetPos() + num2); if (IsProtected(manager, val)) { changed = true; } } return false; } private static bool TryCopyAllowed(ZDOMan manager, ZPackage packet, out ZPackage filtered) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) filtered = new ZPackage(); int num = packet.ReadInt(); List list = new List(num); for (int i = 0; i < num; i++) { ZDOID val = packet.ReadZDOID(); if (!IsProtected(manager, val)) { list.Add(val); } } filtered.Write(list.Count); foreach (ZDOID item in list) { filtered.Write(item); } while (true) { ZDOID val2 = packet.ReadZDOID(); if (((ZDOID)(ref val2)).IsNone()) { filtered.Write(val2); return true; } ushort num2 = packet.ReadUShort(); uint num3 = packet.ReadUInt(); long num4 = packet.ReadLong(); Vector3 val3 = packet.ReadVector3(); int num5 = packet.ReadInt(); if (num5 < 0 || num5 > packet.Size() - packet.GetPos()) { return false; } byte[] array = packet.ReadByteArray(num5); if (array.Length != num5) { break; } if (!IsProtected(manager, val2)) { filtered.Write(val2); filtered.Write(num2); filtered.Write(num3); filtered.Write(num4); filtered.Write(val3); filtered.Write(array); } } return false; } } [HarmonyPatch(typeof(WearNTear), "RPC_Remove", new Type[] { typeof(long), typeof(bool) })] internal static class RunestoneRemovePatch { private static bool Prefix(WearNTear __instance) { return !StoneAccess.IsStone((Component)(object)__instance); } } [HarmonyPatch(typeof(WearNTear), "Remove", new Type[] { typeof(bool) })] internal static class RunestoneRemoveRoutingPatch { [ThreadStatic] internal static bool RequestRejected; private static bool Prefix(WearNTear __instance) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (!StoneAccess.IsStone((Component)(object)__instance)) { return true; } ZNetView component = ((Component)__instance).GetComponent(); ZDO val = ((component != null) ? component.GetZDO() : null); if (!StoneAccess.IsStoneZdo(val)) { RunestoneInteraction.Notify("Runestone network data is not ready. Try again shortly."); RequestRejected = true; return false; } RequestRejected = !NetworkCommands.RequestRemove(val.m_uid); return false; } } [HarmonyPatch(typeof(WearNTear), "RPC_Damage", new Type[] { typeof(long), typeof(HitData) })] internal static class RunestoneDamagePatch { private static bool Prefix(WearNTear __instance) { return !StoneAccess.IsStone((Component)(object)__instance); } } [HarmonyPatch(typeof(WearNTear), "ApplyDamage", new Type[] { typeof(float), typeof(HitData) })] internal static class RunestoneWearPatch { private static bool Prefix(WearNTear __instance, ref bool __result) { if (!StoneAccess.IsStone((Component)(object)__instance)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(ZDOMan), "HandleDestroyedZDO")] internal static class StoneDestroyedPatch { private sealed class DestroyedStone { internal string Group = ""; internal long Owner; internal bool WasActive; } private static void Prefix(ZDOMan __instance, ZDOID uid, out DestroyedStone? __state) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) __state = null; RunestoneInteraction.OnStoneDestroyed(uid); if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { ZDO zDO = __instance.GetZDO(uid); if (zDO != null && zDO.GetPrefab() == StringExtensionMethods.GetStableHashCode("piece_baseprotection_runestone")) { string text = zDO.GetString("baseprotection_group", ""); NetworkCommands.OnStoneDestroying(uid); __state = new DestroyedStone { Group = text, Owner = zDO.GetLong(ZDOVars.s_creator, 0L), WasActive = (zDO.GetInt("baseprotection_active", 1) != 0) }; } } } private static void Postfix(ZDOID uid, DestroyedStone? __state) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (__state != null) { if (!string.IsNullOrEmpty(__state.Group)) { NetworkCommands.RepairAfterDestroyed(__state.Group, __state.Owner, __state.WasActive); } NetworkCommands.OnStoneDestroyed(uid); } } } [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] internal static class StonePlacementAlignment { private static int _cornerSnapFrame = -1; private static readonly FieldInfo PlacementGhost = AccessTools.Field(typeof(Player), "m_placementGhost"); private static readonly MethodInfo NoBuildCheck = AccessTools.Method(typeof(Location), "IsInsideNoBuildLocation", new Type[1] { typeof(Vector3) }, (Type[])null); private static readonly MethodInfo AlignedNoBuildCheck = AccessTools.Method(typeof(StonePlacementAlignment), "CheckNoBuildLocation", (Type[])null, (Type[])null); private static IEnumerable Transpiler(IEnumerable instructions) { foreach (CodeInstruction instruction in instructions) { if (CodeInstructionExtensions.Calls(instruction, NoBuildCheck)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AlignedNoBuildCheck); } else { yield return instruction; } } } private static bool CheckNoBuildLocation(Vector3 position, Player player) { //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)(object)Player.m_localPlayer && (Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305)) && (Object)(object)ZoneSystem.instance != (Object)null) { object? value = PlacementGhost.GetValue(player); GameObject val = (GameObject)((value is GameObject) ? value : null); if (val != null && ((Object)val).name.StartsWith("piece_baseprotection_runestone", StringComparison.Ordinal) && RunestoneInteraction.TryGetAlignmentAnchors(out Point2 origin, out Point2[] cornerStones)) { Point2 candidate = new Point2(position.x, position.z); Point2 snapped; bool flag = StoneAlignment.TrySnapCorner(origin, cornerStones, candidate, BaseProtectionPlugin.Instance.MaxEdge.Value, out snapped); if (flag || StoneAlignment.TrySnap(origin, candidate, out snapped)) { position.x = (float)snapped.X; position.z = (float)snapped.Z; position.y = ZoneSystem.instance.GetGroundHeight(position); val.transform.position = position; if (flag) { if (_cornerSnapFrame != Time.frameCount && _cornerSnapFrame != Time.frameCount - 1) { RunestoneInteraction.Notify("Corner snapped"); } _cornerSnapFrame = Time.frameCount; } } } } return Location.IsInsideNoBuildLocation(position); } } internal static class StoneRepairCommands { private sealed class PendingRepair { internal long RequestId; internal float SentAt; internal Player Player; internal Piece Piece; internal ItemData Tool; } private const string RepairRpc = "BaseProtection.Repair.v1"; private const string ResultRpc = "BaseProtection.RepairResult.v1"; private const float ReplyTimeout = 15f; private static ZRoutedRpc? _registered; private static ZNet? _network; private static long _nextRequestId; private static readonly Dictionary Pending = new Dictionary(); private static readonly MethodInfo? CheckCanRemoveMethod = AccessTools.Method(typeof(Player), "CheckCanRemovePiece", new Type[1] { typeof(Piece) }, (Type[])null); private static readonly MethodInfo? BuildStaminaMethod = AccessTools.Method(typeof(Player), "GetBuildStamina", (Type[])null, (Type[])null); private static readonly FieldInfo? AnimationField = AccessTools.Field(typeof(Character), "m_zanim"); private static readonly FieldInfo? LastRepairField = AccessTools.Field(typeof(WearNTear), "m_lastRepair"); internal static void TryRegister() { ZRoutedRpc instance = ZRoutedRpc.instance; ZNet instance2 = ZNet.instance; if (instance != null && !((Object)(object)instance2 == (Object)null)) { if (instance != _registered) { instance.Register("BaseProtection.Repair.v1", (Action)OnRepair); instance.Register("BaseProtection.RepairResult.v1", (Method)OnResult); _registered = instance; } if (!((Object)(object)instance2 == (Object)(object)_network)) { _network = instance2; Pending.Clear(); _nextRequestId = 0L; } } } internal static void CheckPending() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) KeyValuePair[] array = Pending.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair keyValuePair = array[i]; if (!(Time.time - keyValuePair.Value.SentAt < 15f)) { Pending.Remove(keyValuePair.Key); RunestoneInteraction.Notify("No runestone repair reply from the server. Try again shortly."); } } } internal static bool CheckLocalRepair(Player player, Piece piece) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) if (CheckCanRemoveMethod == null) { RunestoneInteraction.Notify("The hammer cannot check runestone repair requirements."); return false; } bool repairingPiece = VirtualBuildStationContext.RepairingPiece; try { VirtualBuildStationContext.RepairingPiece = true; object obj = CheckCanRemoveMethod.Invoke(player, new object[1] { piece }); if (!(obj is bool) || !(bool)obj) { return false; } } catch (Exception ex) { BaseProtectionPlugin.Instance.LogWarning("Could not check runestone repair requirements: " + ex.Message); return false; } finally { VirtualBuildStationContext.RepairingPiece = repairingPiece; } return PrivateArea.CheckAccess(((Component)piece).transform.position, 0f, true, false); } internal static void RequestRepair(Player player, Piece piece, ItemData tool) { //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)piece).GetComponent(); ZDO val = ((component != null) ? component.GetZDO() : null); WearNTear component2 = ((Component)piece).GetComponent(); if (!StoneAccess.IsStoneZdo(val) || (Object)(object)component2 == (Object)null) { RunestoneInteraction.Notify("Runestone network data is not ready. Try again shortly."); return; } TryRegister(); if (_registered == null || !TryGetServerPeerId(out var peerId)) { RunestoneInteraction.Notify("Cannot reach the server to repair this runestone yet."); } else if (Pending.ContainsKey(val.m_uid)) { RunestoneInteraction.Notify("Runestone repair is already being processed."); } else if (val.GetFloat(ZDOVars.s_health, component2.m_health) >= component2.m_health) { ((Character)player).Message((MessageType)1, piece.m_name + " $msg_doesnotneedrepair", 0, (Sprite)null, false); } else { if (LastRepairField?.GetValue(component2) is float num && Time.time - num < 1f) { return; } LastRepairField?.SetValue(component2, Time.time); PendingRepair pendingRepair = new PendingRepair { RequestId = NextRequestId(), SentAt = Time.time, Player = player, Piece = piece, Tool = tool }; if (!ZNet.instance.IsServer()) { Pending.Add(val.m_uid, pendingRepair); try { _registered.InvokeRoutedRPC(peerId, "BaseProtection.Repair.v1", new object[2] { val.m_uid, pendingRepair.RequestId }); return; } catch (Exception error) { Pending.Remove(val.m_uid); BaseProtectionPlugin.Instance.LogError(error); RunestoneInteraction.Notify("Could not send the runestone repair request."); return; } } if (TryRepairStone(peerId, val.m_uid, out string denial)) { CompleteRepair(pendingRepair); } else { RunestoneInteraction.Notify(denial); } } } private static long NextRequestId() { long num = ++_nextRequestId; if (num != 0L) { return num; } return ++_nextRequestId; } private static bool TryGetServerPeerId(out long peerId) { peerId = 0L; ZNet instance = ZNet.instance; if ((Object)(object)instance == (Object)null) { return false; } peerId = (instance.IsServer() ? ZNet.GetUID() : (instance.GetServerPeer()?.m_uid ?? 0)); return peerId != 0; } private static void OnRepair(long sender, ZDOID stoneId, long requestId) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && StoneRoutedPeerContext.Matches(sender)) { string denial; bool flag = TryRepairStone(sender, stoneId, out denial); ZRoutedRpc? registered = _registered; if (registered != null) { registered.InvokeRoutedRPC(sender, "BaseProtection.RepairResult.v1", new object[4] { stoneId, requestId, flag, denial }); } } } private static bool TryRepairStone(long sender, ZDOID stoneId, out string denial) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) denial = "The runestone is not ready on the server. Try again shortly."; ZNet instance = ZNet.instance; ZDOMan instance2 = ZDOMan.instance; if ((Object)(object)instance == (Object)null || !instance.IsServer() || instance2 == null || !StoneRoutedPeerContext.Matches(sender)) { return false; } ZDO zDO = instance2.GetZDO(stoneId); if (!StoneAccess.CanServerRepair(zDO, sender, out denial)) { return false; } if (NetworkCommands.IsServerRemovalPending(stoneId)) { denial = "This runestone is being dismantled."; return false; } ZNetScene instance3 = ZNetScene.instance; object obj; if (instance3 == null) { obj = null; } else { GameObject prefab = instance3.GetPrefab(StoneAccess.StonePrefabHash); obj = ((prefab != null) ? prefab.GetComponent() : null); } WearNTear val = (WearNTear)obj; if ((Object)(object)val == (Object)null || val.m_health <= 0f) { denial = "The server cannot inspect this runestone's health."; return false; } if (zDO.GetFloat(ZDOVars.s_health, val.m_health) >= val.m_health) { denial = "This runestone does not need repair."; return false; } try { long uID = ZNet.GetUID(); if (zDO.GetOwner() != uID) { zDO.SetOwner(uID); } if (!zDO.IsOwner()) { denial = "The server cannot claim this runestone yet. Try again shortly."; return false; } zDO.Set(ZDOVars.s_health, val.m_health); denial = ""; return true; } catch (Exception error) { BaseProtectionPlugin.Instance.LogError(error); denial = "The server could not repair this runestone. Try again shortly."; return false; } } private static void OnResult(long sender, ZDOID stoneId, long requestId, bool success, string denial) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (TryGetServerPeerId(out var peerId) && sender == peerId && Pending.TryGetValue(stoneId, out PendingRepair value) && value.RequestId == requestId) { Pending.Remove(stoneId); if (success) { CompleteRepair(value); } else { RunestoneInteraction.Notify(denial); } } } private static void CompleteRepair(PendingRepair pending) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) Player player = pending.Player; Piece piece = pending.Piece; ItemData tool = pending.Tool; if (!((Object)(object)player == (Object)null) && tool != null) { player.FaceLookDirection(); object? obj = AnimationField?.GetValue(player); ZSyncAnimation val = (ZSyncAnimation)((obj is ZSyncAnimation) ? obj : null); if (val != null) { val.SetTrigger(tool.m_shared.m_attack.m_attackAnimation); } if ((Object)(object)piece != (Object)null) { piece.m_placeEffect.Create(((Component)piece).transform.position, ((Component)piece).transform.rotation, (Transform)null, 1f, -1, ((Character)player).GetZDOID()); ((Character)player).Message((MessageType)1, Localization.instance.Localize("$msg_repaired", new string[1] { piece.m_name }), 0, (Sprite)null, false); } else { RunestoneInteraction.Notify("Runestone repaired."); } if (BuildStaminaMethod?.Invoke(player, null) is float num) { ((Character)player).UseStamina(num); } ((Character)player).UseEitr(tool.m_shared.m_attack.m_attackEitr); if (tool.m_shared.m_useDurability) { tool.m_durability -= tool.m_shared.m_useDurabilityDrain * Game.m_durabilityRate; } } } } [HarmonyPatch(typeof(Player), "Repair", new Type[] { typeof(ItemData), typeof(Piece) })] internal static class RunestoneRepairPatch { [HarmonyPriority(0)] private static bool Prefix(Player __instance, ItemData __0) { if (!((Character)__instance).InPlaceMode()) { return true; } Piece hoveringPiece = __instance.GetHoveringPiece(); if ((Object)(object)hoveringPiece == (Object)null || !StoneAccess.IsStone((Component)(object)hoveringPiece)) { return true; } if (!StoneRepairCommands.CheckLocalRepair(__instance, hoveringPiece)) { return false; } StoneRepairCommands.RequestRepair(__instance, hoveringPiece, __0); return false; } } [HarmonyPatch(typeof(WearNTear), "Repair")] internal static class RunestoneDirectRepairPatch { private static bool Prefix(WearNTear __instance, ref bool __result) { if (!StoneAccess.IsStone((Component)(object)__instance)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(WearNTear), "RPC_Repair", new Type[] { typeof(long) })] internal static class RunestoneDirectRepairRpcPatch { private static bool Prefix(WearNTear __instance) { return !StoneAccess.IsStone((Component)(object)__instance); } } }