Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of BuildPieceSwap v0.2.1
BepInEx/plugins/BuildPieceSwap/BuildPieceSwap.dll
Decompiled 4 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using BuildPieceSwap.Core; using HarmonyLib; using Microsoft.CodeAnalysis; using TMPro; using UnityEngine; using UnityEngine.Sprites; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BuildPieceSwap")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.2.1.0")] [assembly: AssemblyInformationalVersion("0.2.1+627c93de35fe4ea8fc7db780adf6d890daf2a24a")] [assembly: AssemblyProduct("BuildPieceSwap")] [assembly: AssemblyTitle("BuildPieceSwap")] [assembly: AssemblyVersion("0.2.1.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BuildPieceSwap { [BepInPlugin("dellarion.valheim.vanillabuildswap", "BuildPieceSwap", "0.2.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { public const string Guid = "dellarion.valheim.vanillabuildswap"; public const string PluginVersion = "0.2.1"; internal static ManualLogSource Log; private Harmony harmony; private bool compatible; private void Awake() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Expected O, but got Unknown //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_014d: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Expected O, but got Unknown //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; if (Version.GetVersionString(false) != "1.0.21") { Log.LogError((object)"Only the audited Valheim 1.0.21 is supported; no patches installed."); return; } try { Catalog.Initialize(); harmony = new Harmony("dellarion.valheim.vanillabuildswap"); harmony.Patch((MethodBase)AccessTools.Method(typeof(Player), "UpdatePlacement", (Type[])null, (Type[])null), new HarmonyMethod(typeof(Plugin), "PlacementPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(GameCamera), "UpdateCamera", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(UpgradeController), "CameraInput", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNetScene), "CreateObject", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(SwapEngine), "RestoreScale", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZNet), "SaveWorldThread", (Type[])null, (Type[])null), new HarmonyMethod(typeof(WorldCommit), "ThreadStarted", (Type[])null), new HarmonyMethod(typeof(WorldCommit), "ThreadFinished", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "PrepareSave", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(WorldCommit), "SnapshotStarted", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)AccessTools.Method(typeof(SaveSystem), "EndSave", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(WorldCommit), "SaveEnded", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); string[] array = new string[7] { "Damage", "RPC_Damage", "Remove", "RPC_Remove", "ApplyDamage", "UpdateWear", "CanBeRemoved" }; foreach (string text in array) { MethodInfo methodInfo = AccessTools.Method(typeof(WearNTear), text, (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("WearNTear." + text); } harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin), "UnlockedPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } compatible = true; Log.LogInfo((object)"BuildPieceSwap 0.2.1 initialized; structural catalogue will be built from registered pieces."); } catch (Exception ex) { compatible = false; Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } Log.LogError((object)("Initialization failed; upgrade patches removed: " + ex)); } } private static bool PlacementPrefix(Player __instance, bool __0) { return UpgradeController.Placement(__instance, __0); } private static bool UnlockedPrefix(WearNTear __instance) { ZNetView component = ((Component)__instance).GetComponent<ZNetView>(); return !Object.op_Implicit((Object)(object)component) || !Network.Locked(component.GetZDO()); } private void Update() { if (!compatible) { return; } try { Network.Tick(); } catch (Exception ex) { Log.LogError((object)("Upgrade update stopped safely: " + ex)); } } private void LateUpdate() { if (!compatible) { return; } try { Carousel.Render(); } catch (Exception ex) { Carousel.Hide(); Log.LogWarning((object)("Overlay unavailable: " + ex.Message)); } try { UpgradeHint.Render(); } catch (Exception ex2) { Log.LogWarning((object)("Upgrade hint unavailable: " + ex2.Message)); } } private void OnDestroy() { UpgradeController.Reset(); Carousel.Destroy(); UpgradeHint.Destroy(); Harmony obj = harmony; if (obj != null) { obj.UnpatchSelf(); } } } internal static class BuildFeedback { internal static void Play(Piece target, ZDO data) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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) try { target.m_placeEffect.Create(data.GetPosition(), data.GetRotation(), (Transform)null, 1f, -1, default(ZDOID)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Native placement feedback failed: " + ex.Message)); } } } internal static class Catalog { private static readonly List<(string group, string left, string right, string policy)> pairs = new List<(string, string, string, string)>(); internal static readonly Dictionary<int, Piece> Pieces = new Dictionary<int, Piece>(); private static CompatibilityIndex index; private static readonly Dictionary<int, string> localShapes = new Dictionary<int, string>(); private static bool initialized; private static string presetSignature; private static string registryStamp; internal static string Signature { get; private set; } internal static bool Ready => index != null && index.Options.Values.Any((int[] v) => v.Length != 0); private static Dictionary<int, GameObject> Registry => Native.Get<Dictionary<int, GameObject>>(ZNetScene.instance, "m_namedPrefabs"); internal static void Initialize() { if (initialized) { return; } using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BuildPieceSwap.Resources.compatibility.tsv"); using StreamReader streamReader = new StreamReader(stream); string text = streamReader.ReadToEnd(); using SHA256 sHA = SHA256.Create(); presetSignature = BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", ""); initialized = true; foreach (string item in text.Split('\n').Skip(1)) { string[] array = item.Trim().Split('\t'); if (array.Length == 4) { pairs.Add((array[0], array[1], array[2], array[3])); } } } private static IEnumerable<GameObject> RegisteredBuildPieces() { HashSet<GameObject> hashSet = new HashSet<GameObject>(); PieceTable[] array = Resources.FindObjectsOfTypeAll<PieceTable>(); foreach (PieceTable val in array) { if (!Object.op_Implicit((Object)(object)val) || val.m_pieces == null) { continue; } foreach (GameObject piece in val.m_pieces) { if (Object.op_Implicit((Object)(object)piece)) { string text = Native.PrefabName(piece); if (Registry.TryGetValue(StringExtensionMethods.GetStableHashCode(text), out var value) && Object.op_Implicit((Object)(object)value) && Native.PrefabName(value) == text) { hashSet.Add(value); } } } } return hashSet.OrderBy<GameObject, string>((GameObject p) => Native.PrefabName(p), StringComparer.Ordinal); } private static string RegistryStamp(IEnumerable<GameObject> pieces) { return Registry.Count + ":" + (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.m_items.Count : (-1)) + ":" + string.Join(";", pieces.Select((GameObject p) => Native.PrefabName(p) + ":" + ((Object)p).GetInstanceID())); } internal static bool RefreshIfChanged() { GameObject[] array = RegisteredBuildPieces().ToArray(); if (Ready && RegistryStamp(array) == registryStamp) { return false; } string signature = Signature; Load(array); return signature != Signature; } internal static void Load() { Load(RegisteredBuildPieces().ToArray()); } private static void Load(GameObject[] registered) { Initialize(); Pieces.Clear(); localShapes.Clear(); foreach (GameObject item in Registry.Values.Where((GameObject p) => Object.op_Implicit((Object)(object)p)).OrderBy<GameObject, string>((GameObject p) => Native.PrefabName(p), StringComparer.Ordinal)) { Piece component = item.GetComponent<Piece>(); if (Object.op_Implicit((Object)(object)component)) { Pieces[StringExtensionMethods.GetStableHashCode(Native.PrefabName(item))] = component; } } List<StructuralDescriptor> list = new List<StructuralDescriptor>(); int num = 0; int num2 = 0; foreach (GameObject val in registered) { Piece component2 = val.GetComponent<Piece>(); if (!Object.op_Implicit((Object)(object)component2)) { continue; } try { string reason; StructuralDescriptor descriptor = StructuralReader.Describe(component2, null, out reason); if (!descriptor.Structural) { num++; if (pairs.Any(((string group, string left, string right, string policy) p) => p.left == descriptor.Name || p.right == descriptor.Name)) { Plugin.Log.LogWarning((object)("Excluded audited piece " + descriptor.Name + ": " + reason)); } continue; } list.Add(descriptor); localShapes[descriptor.Id] = CollisionProfile(component2); if (descriptor.Geometry == null) { num2++; } } catch (Exception ex) { num++; Plugin.Log.LogWarning((object)("Excluded " + ((Object)val).name + ": " + ex.Message)); } } HashSet<int> hashSet = new HashSet<int>(list.Select((StructuralDescriptor d) => d.Id)); List<(int, int)> list2 = new List<(int, int)>(); foreach (var pair in pairs) { int stableHashCode = StringExtensionMethods.GetStableHashCode(pair.left); int stableHashCode2 = StringExtensionMethods.GetStableHashCode(pair.right); if (hashSet.Contains(stableHashCode) && hashSet.Contains(stableHashCode2) && CuratedCompatible(Pieces[stableHashCode], Pieces[stableHashCode2])) { list2.Add((stableHashCode, stableHashCode2)); } } index = CompatibilityIndex.Build(list, list2); Signature = CompatibilityIndex.Digest(CompatibilityIndex.Fields(presetSignature, index.Signature)); registryStamp = RegistryStamp(registered); Plugin.Log.LogInfo((object)("Catalogue: " + index.Nodes.Count + " structural pieces, " + index.Options.Values.Sum((int[] v) => v.Length) + " directed replacements, " + num + " excluded, " + num2 + " without readable collision geometry. Signature " + Signature)); } internal static IReadOnlyList<int> Options(int source) { int[] value; return (index != null && index.Options.TryGetValue(source, out value)) ? ((IReadOnlyList<int>)value) : ((IReadOnlyList<int>)Array.Empty<int>()); } internal static bool Allows(int source, int target) { return Options(source).Contains(target); } internal static bool InstanceMatches(Piece piece, int id) { string reason; return InstanceMatches(piece, id, out reason); } internal static bool InstanceMatches(Piece piece, int id, out string reason) { //IL_00c3: Unknown result type (might be due to invalid IL or missing references) reason = "snapshot_identity"; if (index == null || !index.Nodes.TryGetValue(id, out var value) || !Pieces.TryGetValue(id, out var value2)) { return false; } try { string text = CollisionProfile(piece); if (text != localShapes[id]) { reason = "snapshot_geometry"; Plugin.Log.LogWarning((object)("Local collider mismatch: prefab=" + value.Name + " expected=" + localShapes[id] + " actual=" + text)); return false; } string reason2; StructuralDescriptor structuralDescriptor = StructuralReader.Describe(piece, ((Component)value2).transform.localScale, out reason2); SnapshotDifference snapshotDifference = StructuralDescriptor.Difference(value, structuralDescriptor); if (snapshotDifference == SnapshotDifference.None) { reason = null; return true; } reason = "snapshot_" + snapshotDifference.ToString().ToLowerInvariant(); Plugin.Log.LogWarning((object)("Snapshot mismatch: prefab=" + value.Name + " field=" + snapshotDifference.ToString() + snapshotDifference switch { SnapshotDifference.Recipe => " expected=" + value.Recipe + " actual=" + structuralDescriptor.Recipe, SnapshotDifference.Safety => " detail=" + reason2, _ => "", })); return false; } catch (Exception ex) { reason = "snapshot_safety"; Plugin.Log.LogWarning((object)("Snapshot read failed: " + value.Name + ": " + ex.Message)); return false; } } internal static bool Compatible(Piece a, Piece b) { int stableHashCode = StringExtensionMethods.GetStableHashCode(Native.PrefabName(((Component)a).gameObject)); int stableHashCode2 = StringExtensionMethods.GetStableHashCode(Native.PrefabName(((Component)b).gameObject)); return Allows(stableHashCode, stableHashCode2) && InstanceMatches(a, stableHashCode) && InstanceMatches(b, stableHashCode2); } private static bool CuratedCompatible(Piece a, Piece b) { //IL_006c: 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_0084: 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) try { string an = Native.PrefabName(((Component)a).gameObject); string bn = Native.PrefabName(((Component)b).gameObject); (string, string, string, string) tuple = pairs.FirstOrDefault(((string group, string left, string right, string policy) p) => (p.left == an && p.right == bn) || (p.left == bn && p.right == an)); if (tuple.Item4 == null) { return false; } ZNetView component = ((Component)a).GetComponent<ZNetView>(); ZNetView component2 = ((Component)b).GetComponent<ZNetView>(); if (((Component)a).transform.localScale != ((Component)b).transform.localScale || component.m_type != component2.m_type || component.m_persistent != component2.m_persistent || component.m_distant != component2.m_distant || component.m_syncInitialScale != component2.m_syncInitialScale) { return false; } bool flag = tuple.Item4.StartsWith("space-", StringComparison.Ordinal) || tuple.Item4 == "offset-rect"; if (flag ? (!GridShape.Matches(GridPoints(a), GridPoints(b), tuple.Item4)) : (SnapProfile(a) != SnapProfile(b))) { return false; } string text = CollisionProfile(a); string text2 = CollisionProfile(b); return text != null && text2 != null && (flag || tuple.Item4.StartsWith("grid", StringComparison.Ordinal) || text == text2); } catch { return false; } } private static string Number(float v) { return ((v == 0f) ? 0f : v).ToString("R", CultureInfo.InvariantCulture); } private static string Vec(Vector3 v) { //IL_0008: 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_0034: Unknown result type (might be due to invalid IL or missing references) return Number(v.x) + "," + Number(v.y) + "," + Number(v.z); } internal static Vector3 Alignment(Piece source, Piece target) { //IL_0087: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) string a = Native.PrefabName(((Component)source).gameObject); string b = Native.PrefabName(((Component)target).gameObject); if (!pairs.Any(((string group, string left, string right, string policy) p) => p.policy == "offset-rect" && ((p.left == a && p.right == b) || (p.right == a && p.left == b)))) { return Vector3.zero; } GridPoint gridPoint = GridShape.PivotOffset(GridPoints(source), GridPoints(target)); return new Vector3((float)gridPoint.X / 100000f, (float)gridPoint.Y / 100000f, (float)gridPoint.Z / 100000f); } private static IEnumerable<GridPoint> GridPoints(Piece p) { foreach (Transform item in ((Component)p).transform) { Transform t = item; if (((Component)t).CompareTag("snappoint")) { yield return new GridPoint(t.localPosition.x, t.localPosition.y, t.localPosition.z); } } } private static string SnapProfile(Piece p) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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) List<string> list = new List<string>(); foreach (Transform item in ((Component)p).transform) { Transform val = item; if (((Component)val).CompareTag("snappoint")) { list.Add(Vec(new Vector3((float)Math.Round(val.localPosition.x, 5), (float)Math.Round(val.localPosition.y, 5), (float)Math.Round(val.localPosition.z, 5)))); } } list.Sort(StringComparer.Ordinal); return string.Join(";", list); } private static Matrix4x4 LocalMatrix(Transform child, Transform root) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)child == (Object)(object)root) { return Matrix4x4.identity; } if (!Object.op_Implicit((Object)(object)child) || !Object.op_Implicit((Object)(object)child.parent)) { throw new InvalidOperationException("Collider is outside the piece root"); } return LocalMatrix(child.parent, root) * Matrix4x4.TRS(child.localPosition, child.localRotation, child.localScale); } internal static string CollisionProfile(Piece p) { //IL_00c8: 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_0205: 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_021a: 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_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) List<string> list = new List<string>(); Collider[] componentsInChildren = ((Component)p).GetComponentsInChildren<Collider>(true); foreach (Collider val in componentsInChildren) { if (val.isTrigger || Object.op_Implicit((Object)(object)val.attachedRigidbody)) { continue; } bool flag = false; Transform val2 = ((Component)val).transform; while (Object.op_Implicit((Object)(object)val2) && (Object)(object)val2 != (Object)(object)((Component)p).transform) { if (((Object)val2).name.Equals("Destruction", StringComparison.OrdinalIgnoreCase)) { flag = true; } val2 = val2.parent; } if (flag) { continue; } if (Object.op_Implicit((Object)(object)val.sharedMaterial)) { return null; } Matrix4x4 m = LocalMatrix(((Component)val).transform, ((Component)p).transform); MeshCollider val3 = (MeshCollider)(object)((val is MeshCollider) ? val : null); if (val3 != null) { if (!Object.op_Implicit((Object)(object)val3.sharedMesh)) { return null; } list.Add("mesh:" + ((Object)val3.sharedMesh).GetInstanceID() + ":" + val3.convex + ":" + ((Collider)val3).enabled + ":" + ((Component)val3).gameObject.layer + ":" + string.Join(";", Enumerable.Range(0, 4).Select(delegate(int num4) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Vector4 column = ((Matrix4x4)(ref m)).GetColumn(num4); return ((Vector4)(ref column)).ToString("R"); }))); continue; } BoxCollider val4 = (BoxCollider)(object)((val is BoxCollider) ? val : null); if (val4 == null) { return null; } List<string> list2 = new List<string>(); for (int num = -1; num <= 1; num += 2) { for (int num2 = -1; num2 <= 1; num2 += 2) { for (int num3 = -1; num3 <= 1; num3 += 2) { list2.Add(Vec(((Matrix4x4)(ref m)).MultiplyPoint3x4(val4.center + Vector3.Scale(val4.size, new Vector3((float)num, (float)num2, (float)num3)) / 2f))); } } } list2.Sort(StringComparer.Ordinal); list.Add(((Component)val4).gameObject.layer + ":" + ((Collider)val4).enabled + ":" + string.Join(";", list2)); } list.Sort(StringComparer.Ordinal); return (list.Count == 0) ? null : string.Join("|", list); } } internal static class ContainerResources { private static MethodInfo sources; private static MethodInfo count; private static MethodInfo acquire; private static MethodInfo owns; private static bool inspected; private static void Initialize() { if (inspected) { return; } inspected = true; if (!Chainloader.PluginInfos.TryGetValue("local.craftfromcontainers", out var value)) { return; } if (value.Metadata.Version.ToString() != "0.1.4") { Plugin.Log.LogWarning((object)"Container resource adapter requires the audited Craft From Containers 0.1.4."); return; } Assembly assembly = ((object)value.Instance).GetType().Assembly; Type type = assembly.GetType("CraftFromContainers.ContainerIndex"); Type type2 = assembly.GetType("CraftFromContainers.NetworkLeases"); sources = AccessTools.Method(type, "GetSourcesFor", new Type[1] { typeof(IEnumerable<string>) }, (Type[])null); count = AccessTools.Method(type, "Count", new Type[3] { typeof(string), typeof(int), typeof(bool) }, (Type[])null); acquire = AccessTools.Method(type2, "Acquire", new Type[4] { typeof(Player), typeof(List<Container>), typeof(Action), typeof(Action<string>) }, (Type[])null); owns = AccessTools.Method(type2, "Owns", new Type[1] { typeof(Container) }, (Type[])null); if (!(sources == null) && !(count == null) && !(acquire == null) && !(owns == null)) { return; } throw new MissingMethodException("Craft From Containers adapter contract changed"); } internal static int Available(Player player, string item) { Initialize(); int num = ((Humanoid)player).GetInventory().CountItems(item, -1, true); return num + ((!(count == null)) ? ((int)count.Invoke(null, new object[3] { item, -1, true })) : 0); } internal static void WithSources(Player player, Piece target, Action<List<Container>> ready, Action<string> failed) { try { Initialize(); string[] array = (from r in target.m_resources where r.GetAmount(1) > ((Humanoid)player).GetInventory().CountItems(r.m_resItem.m_itemData.m_shared.m_name, -1, true) select r.m_resItem.m_itemData.m_shared.m_name).Distinct().ToArray(); if (array.Length == 0 || sources == null) { ready(new List<Container>()); return; } List<Container> containers = (from c in (List<Container>)sources.Invoke(null, new object[1] { array }) orderby ((ZDOID)(ref ((Component)c).GetComponent<ZNetView>().GetZDO().m_uid)).UserID, ((ZDOID)(ref ((Component)c).GetComponent<ZNetView>().GetZDO().m_uid)).ID select c).ToList(); if (containers.Count == 0) { failed(Texts.Get("resources")); return; } acquire.Invoke(null, new object[4] { player, containers, (Action)delegate { try { if (containers.Any((Container c) => !Object.op_Implicit((Object)(object)c) || !(bool)owns.Invoke(null, new object[1] { c }))) { throw new InvalidOperationException(Texts.Get("inventory_changed")); } ready(containers); } catch (Exception ex2) { failed(ex2.Message); } }, failed }); } catch (Exception ex) { failed((ex as TargetInvocationException)?.InnerException?.Message ?? ex.Message); } } } internal sealed class PendingPayment { internal const string Key = "dellarion.vanillabuildswap.pending.v1"; internal string Id; internal long World; internal ZDOID Source; internal int From; internal int To; internal string Escrow; internal bool FreeBuild; internal bool IgnoreStation; internal string Encode() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(Id); val.Write(World); val.Write(Source); val.Write(From); val.Write(To); val.Write(Escrow); val.Write(FreeBuild); val.Write(IgnoreStation); return val.GetBase64(); } internal static PendingPayment Read(Player player) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (!player.m_customData.TryGetValue("dellarion.vanillabuildswap.pending.v1", out var value)) { return null; } ZPackage val = new ZPackage(value); PendingPayment pendingPayment = new PendingPayment { Id = val.ReadString(), World = val.ReadLong(), Source = val.ReadZDOID(), From = val.ReadInt(), To = val.ReadInt(), Escrow = val.ReadString() }; if (val.GetPos() < val.Size()) { pendingPayment.FreeBuild = val.ReadBool(); } if (val.GetPos() < val.Size()) { pendingPayment.IgnoreStation = val.ReadBool(); } return pendingPayment; } } internal static class InventoryEscrow { internal static bool FreeCost(Player player, Piece piece) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return player.NoCostCheat() || ZoneSystem.instance.GetGlobalKey(Native.Call<GlobalKeys>(piece, "FreeBuildKey", Array.Empty<object>())); } internal static string Save(Inventory inventory) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ZPackage val = new ZPackage(); inventory.Save(val); return val.GetBase64(); } private static Inventory Copy(Inventory original) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown Inventory val = new Inventory("BuildPieceSwap escrow", (Sprite)null, original.GetWidth(), original.GetHeight()); val.Load(new ZPackage(Save(original))); return val; } private static Inventory Take(IReadOnlyList<Inventory> inventories, Piece cost) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown Inventory val = inventories[0]; Inventory val2 = new Inventory("BuildPieceSwap escrow", (Sprite)null, val.GetWidth(), val.GetHeight()); Requirement[] resources = cost.m_resources; foreach (Requirement val3 in resources) { int num = val3.GetAmount(1); if (num <= 0) { continue; } if (!Object.op_Implicit((Object)(object)val3.m_resItem)) { throw new InvalidOperationException(Texts.Get("bad_recipe")); } string itemName = val3.m_resItem.m_itemData.m_shared.m_name; (Inventory, int, ItemData)[] array = (from s in inventories.SelectMany((Inventory source, int order) => from item2 in source.GetAllItems() where MaterialRules.Matches(item2.m_shared.m_name, item2.m_worldLevel, itemName, Game.m_worldLevel) select (source: source, order: order, item: item2)) orderby s.order, s.item.m_gridPos.y, s.item.m_gridPos.x select s).ToArray(); if (array.Sum(((Inventory source, int order, ItemData item) s) => s.item.m_stack) < num) { throw new InvalidOperationException(Texts.Get("resources")); } (Inventory, int, ItemData)[] array2 = array; for (int num2 = 0; num2 < array2.Length; num2++) { (Inventory, int, ItemData) tuple = array2[num2]; ItemData item = tuple.Item3; int num3 = Math.Min(num, item.m_stack); if (num3 == 0) { break; } ItemData val4 = item.Clone(); val4.m_stack = num3; val4.m_equipped = false; if (!val2.AddItem(val4) || !tuple.Item1.RemoveItem(item, num3)) { throw new InvalidOperationException(Texts.Get("inventory_changed")); } num -= num3; } if (num != 0) { throw new InvalidOperationException(Texts.Get("resources")); } } return val2; } private static void AddRecipe(Inventory inventory, Piece old) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (ZoneSystem.instance.GetGlobalKey(Native.Call<GlobalKeys>(old, "FreeBuildKey", Array.Empty<object>()))) { return; } Requirement[] resources = old.m_resources; foreach (Requirement val in resources) { int amount = val.GetAmount(1); if (amount > 0 && (!val.m_recover || !Object.op_Implicit((Object)(object)val.m_resItem) || !inventory.AddItem(((Component)val.m_resItem).gameObject, amount))) { throw new InvalidOperationException(Texts.Get("space")); } } } private static void AddEscrow(Inventory inventory, PendingPayment pending) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown Inventory val = new Inventory("BuildPieceSwap escrow", (Sprite)null, inventory.GetWidth(), inventory.GetHeight()); val.Load(new ZPackage(pending.Escrow)); foreach (ItemData item in val.GetAllItemsInGridOrder()) { if (!inventory.AddItem(item.Clone())) { throw new InvalidOperationException(Texts.Get("space")); } } } internal static void Reserve(Player player, PendingPayment pending, Action completed, Action<string> failed) { if (PendingPayment.Read(player) != null) { throw new InvalidOperationException(Texts.Get("pending")); } pending.FreeBuild = FreeCost(player, Catalog.Pieces[pending.To]); Action<List<Container>> action = delegate(List<Container> containers) { //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Expected O, but got Unknown //IL_01dd: Unknown result type (might be due to invalid IL or missing references) using (new OperationTiming("reserve available resources")) { if (!Object.op_Implicit((Object)(object)player) || (Object)(object)player != (Object)(object)Player.m_localPlayer || ((Character)player).IsDead() || !Network.IsReserving(pending) || !Object.op_Implicit((Object)(object)ZNet.instance) || pending.World != ZNet.instance.GetWorldUID() || PendingPayment.Read(player) != null) { throw new InvalidOperationException(Texts.Get("inventory_changed")); } pending.FreeBuild = FreeCost(player, Catalog.Pieces[pending.To]); pending.IgnoreStation = player.NoCostCheat(); List<Inventory> list = new List<Inventory> { ((Humanoid)player).GetInventory() }; list.AddRange(containers.Select((Container c) => c.GetInventory())); Inventory[] array = list.Select(Copy).ToArray(); Piece old = Catalog.Pieces[pending.From]; Piece cost = Catalog.Pieces[pending.To]; if (!pending.FreeBuild) { Take(array, cost); } AddRecipe(array[0], old); string[] array2 = list.Select(Save).ToArray(); try { pending.Escrow = Save((Inventory)((!pending.FreeBuild) ? ((object)Take(list, cost)) : ((object)new Inventory("BuildPieceSwap escrow", (Sprite)null, 1, 1)))); player.m_customData["dellarion.vanillabuildswap.pending.v1"] = pending.Encode(); foreach (Container container in containers) { Native.Call<object>(container, "Save", Array.Empty<object>()); } } catch { player.m_customData.Remove("dellarion.vanillabuildswap.pending.v1"); for (int num = 0; num < list.Count; num++) { try { list[num].Load(new ZPackage(array2[num])); } catch (Exception ex2) { Plugin.Log.LogError((object)("Inventory rollback notification failed: " + ex2)); } } foreach (Container container2 in containers) { try { Native.Call<object>(container2, "Save", Array.Empty<object>()); } catch (Exception ex3) { Plugin.Log.LogError((object)("Container rollback publication failed: " + ex3)); } } try { Native.Call<object>(player, "EquipInventoryItems", Array.Empty<object>()); } catch (Exception ex4) { Plugin.Log.LogError((object)("Equipment rollback notification failed: " + ex4)); } throw; } completed(); } }; if (pending.FreeBuild) { try { action(new List<Container>()); return; } catch (Exception ex) { failed(ex.Message); return; } } ContainerResources.WithSources(player, Catalog.Pieces[pending.To], action, failed); } internal static bool Settle(Player player, PendingPayment pending, bool committed) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown using (new OperationTiming("settle resources")) { Inventory inventory = ((Humanoid)player).GetInventory(); Inventory obj = Copy(inventory); Action<Inventory> action = delegate(Inventory inventory2) { if (committed) { AddRecipe(inventory2, Catalog.Pieces[pending.From]); } else { AddEscrow(inventory2, pending); } }; try { action(obj); } catch { UpgradeController.Status = Texts.Get("space"); return false; } string text = Save(inventory); try { action(inventory); player.m_customData.Remove("dellarion.vanillabuildswap.pending.v1"); return true; } catch (Exception ex) { inventory.Load(new ZPackage(text)); player.m_customData["dellarion.vanillabuildswap.pending.v1"] = pending.Encode(); Native.Call<object>(player, "EquipInventoryItems", Array.Empty<object>()); UpgradeController.Status = ex.Message; Plugin.Log.LogError((object)("Inventory settlement retained escrow: " + ex)); return false; } } } } internal static class Native { internal static T Get<T>(object obj, string name) { return (T)AccessTools.Field(obj.GetType(), name).GetValue(obj); } internal static void Set(object obj, string name, object value) { AccessTools.Field(obj.GetType(), name).SetValue(obj, value); } internal static T Static<T>(Type type, string name) { return (T)AccessTools.Field(type, name).GetValue(null); } internal static void CallStatic(Type type, string method, params object[] args) { AccessTools.Method(type, method, Array.ConvertAll(args, (object a) => a.GetType()), (Type[])null).Invoke(null, args); } internal static T Call<T>(object obj, string name, params object[] args) { try { return (T)AccessTools.Method(obj.GetType(), name, Array.ConvertAll(args, (object a) => a.GetType()), (Type[])null).Invoke(obj, args); } catch (TargetInvocationException ex) { throw ex.InnerException ?? ex; } } internal static string PrefabName(GameObject go) { return ((Object)go).name.Replace("(Clone)", "").Trim(); } } internal static class Network { private enum Kind { Hello, HelloReply, Request, Grant, Paid, Outcome, Ack, Refresh, Status, Refused, Cancel } internal const string RpcName = "BuildPieceSwapV2"; internal const string TxKey = "dellarion.vbs.tx"; internal const string ActorKey = "dellarion.vbs.actor"; internal const string PhaseKey = "dellarion.vbs.phase"; internal const string FromKey = "dellarion.vbs.from"; internal const string ToKey = "dellarion.vbs.to"; private const string DeadlineKey = "dellarion.vbs.deadline"; internal const string ResultKey = "dellarion.vbs.result"; private static ZRoutedRpc registered; private static readonly HashSet<long> peers = new HashSet<long>(); private static PendingPayment requested; private static PendingPayment reserving; private static readonly HashSet<ZDOID> watched = new HashSet<ZDOID>(); private static readonly Dictionary<ZDOID, int> refreshes = new Dictionary<ZDOID, int>(); private static float nextHello; private static float nextRetry; private static float nextRefresh; private static float nextRecovery; private static float requestDeadline; internal static bool ServerReady { get; private set; } private static long Server => ZNet.instance.IsServer() ? ZNet.GetUID() : Native.Call<long>(ZRoutedRpc.instance, "GetServerPeerID", Array.Empty<object>()); private static string Protocol => "0.2.1/Valheim-1.0.21/" + Catalog.Signature; internal static bool Busy => requested != null || reserving != null || (Object.op_Implicit((Object)(object)Player.m_localPlayer) && PendingPayment.Read(Player.m_localPlayer) != null); internal static void Watch(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) watched.Add(id); } internal static bool IsReserving(PendingPayment payment) { return reserving == payment; } private static ZPackage Packet(Kind kind) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write((int)kind); return val; } private static void Send(long peer, ZPackage p) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (peer == ZNet.GetUID()) { Handle(peer, new ZPackage(p.GetArray())); return; } registered.InvokeRoutedRPC(peer, "BuildPieceSwapV2", new object[1] { p }); } private static void SendOperation(long peer, Kind kind, PendingPayment operation) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) ZPackage val = Packet(kind); val.Write(operation.Id); val.Write(operation.Source); val.Write(operation.From); val.Write(operation.To); val.Write(operation.IgnoreStation); Send(peer, val); } internal static bool Locked(ZDO data) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return data != null && (data.GetInt("dellarion.vbs.phase", 0) != 0 || SwapEngine.IsRecovering(data.m_uid)); } internal static void Tick() { //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_03d6: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_0421: Unknown result type (might be due to invalid IL or missing references) //IL_0505: Unknown result type (might be due to invalid IL or missing references) //IL_050a: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)ZNet.instance) || !Object.op_Implicit((Object)(object)ZNetScene.instance) || ZRoutedRpc.instance == null) { return; } if (registered != ZRoutedRpc.instance) { registered = ZRoutedRpc.instance; peers.Clear(); watched.Clear(); refreshes.Clear(); requested = null; ServerReady = false; WorldCommit.ResetSession(); SwapEngine.ResetRecoveries(); reserving = null; nextHello = (nextRetry = (nextRefresh = 0f)); registered.Register<ZPackage>("BuildPieceSwapV2", (Action<long, ZPackage>)Handle); Catalog.Load(); foreach (ZDO key in Native.Get<Dictionary<ZDO, ZNetView>>(ZNetScene.instance, "m_instances").Keys) { if (key.GetInt("dellarion.vbs.phase", 0) != 0) { Watch(key.m_uid); } } } WorldCommit.Tick(); KeyValuePair<ZDOID, int>[] array = refreshes.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair<ZDOID, int> keyValuePair = array[i]; ZDO zDO = ZDOMan.instance.GetZDO(keyValuePair.Key); if (zDO == null) { refreshes.Remove(keyValuePair.Key); } else if (zDO.GetPrefab() == keyValuePair.Value && SwapEngine.Refresh(zDO)) { refreshes.Remove(keyValuePair.Key); } } if (Time.unscaledTime >= nextHello) { nextHello = Time.unscaledTime + 2f; if (!Busy && !watched.Any((ZDOID id) => Locked(ZDOMan.instance.GetZDO(id))) && Catalog.RefreshIfChanged()) { peers.Clear(); ServerReady = false; } ZPackage val = Packet(Kind.Hello); val.Write(Protocol); Send(Server, val); } if (Time.unscaledTime >= nextRetry && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { nextRetry = Time.unscaledTime + 2f; PendingPayment pendingPayment = PendingPayment.Read(Player.m_localPlayer); if (pendingPayment != null) { if (pendingPayment.World == ZNet.instance.GetWorldUID()) { SendOperation(Server, Kind.Status, pendingPayment); } else { UpgradeController.Status = Texts.Get("other_world"); } } if (requested != null && Time.unscaledTime > requestDeadline) { SendOperation(Server, Kind.Cancel, requested); requested = null; UpgradeController.Status = Texts.Get("timeout"); } } if (!(Time.unscaledTime >= nextRefresh)) { return; } nextRefresh = Time.unscaledTime + 0.25f; if (ZNet.instance.IsServer()) { SwapEngine.Recover(); } bool flag = ZNet.instance.IsServer() && Time.unscaledTime >= nextRecovery; if (flag) { nextRecovery = Time.unscaledTime + 2f; } ZDOID[] array2 = watched.ToArray(); foreach (ZDOID val2 in array2) { ZDO zDO2 = ZDOMan.instance.GetZDO(val2); if (SwapEngine.IsRecovering(val2)) { continue; } if (zDO2 == null || zDO2.GetInt("dellarion.vbs.phase", 0) == 0) { watched.Remove(val2); continue; } if (ZNet.instance.IsServer() && zDO2.GetInt("dellarion.vbs.phase", 0) == 1 && zDO2.GetLong("dellarion.vbs.deadline", 0L) < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) { zDO2.Set("dellarion.vbs.result", 3); zDO2.Set("dellarion.vbs.phase", 0); } if (zDO2.GetPrefab() == zDO2.GetInt("dellarion.vbs.to", 0)) { SwapEngine.Refresh(zDO2); } if (!flag || !TransactionRules.IsFinal((OperationPhase)zDO2.GetInt("dellarion.vbs.phase", 0))) { continue; } long num2 = zDO2.GetLong("dellarion.vbs.actor", 0L); PendingPayment op = new PendingPayment { Id = zDO2.GetString("dellarion.vbs.tx", ""), Source = zDO2.m_uid, From = zDO2.GetInt("dellarion.vbs.from", 0), To = zDO2.GetInt("dellarion.vbs.to", 0) }; long[] array3 = (from p in ZNet.instance.GetPeers() select p.m_uid).Concat(new long[1] { ZNet.GetUID() }).ToArray(); foreach (long num4 in array3) { Player val3 = Actor(num4); if (Object.op_Implicit((Object)(object)val3) && val3.GetPlayerID() == num2) { Reply(num4, op, (OperationPhase)zDO2.GetInt("dellarion.vbs.phase", 0)); } } } } internal static void Request(Piece source, int target) { //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) if (Busy) { PendingPayment pendingPayment = (Object.op_Implicit((Object)(object)Player.m_localPlayer) ? PendingPayment.Read(Player.m_localPlayer) : null); string text = ((pendingPayment != null && pendingPayment.World != ZNet.instance.GetWorldUID()) ? "other_world" : "busy"); UpgradeController.Status = Texts.Get(text); Plugin.Log.LogWarning((object)("Upgrade blocked locally: " + text + " requested=" + (requested != null) + " reserving=" + (reserving != null) + " escrow=" + (pendingPayment != null))); return; } if (!ServerReady) { UpgradeController.Status = Texts.Get("server"); Plugin.Log.LogWarning((object)("Upgrade blocked locally: server_not_ready catalogue=" + Catalog.Ready + " world_recovered=" + WorldCommit.Ready)); return; } Player localPlayer = Player.m_localPlayer; ZNetView component = ((Component)source).GetComponent<ZNetView>(); if (Object.op_Implicit((Object)(object)component) && component.IsValid() && Catalog.Allows(component.GetZDO().GetPrefab(), target)) { Piece val = Catalog.Pieces[target]; if ((!localPlayer.NoCostCheat() && (!localPlayer.HaveRequirements(val, (RequirementMode)1) || !localPlayer.HaveRequirements(val, (RequirementMode)0))) || !Native.Call<bool>(localPlayer, "CheckCanRemovePiece", new object[1] { source })) { UpgradeController.Status = Texts.Get("requirements"); Plugin.Log.LogWarning((object)("Upgrade blocked locally: requirements_or_source_station target=" + Native.PrefabName(((Component)val).gameObject))); return; } requested = new PendingPayment { Id = Guid.NewGuid().ToString("N"), World = ZNet.instance.GetWorldUID(), Source = component.GetZDO().m_uid, From = component.GetZDO().GetPrefab(), To = target, IgnoreStation = localPlayer.NoCostCheat() }; requestDeadline = Time.unscaledTime + 12f; UpgradeController.Status = Texts.Get("pending"); Plugin.Log.LogInfo((object)("Upgrade request: source=" + Native.PrefabName(((Component)source).gameObject) + " target=" + Native.PrefabName(((Component)val).gameObject))); SendOperation(Server, Kind.Request, requested); } } private static bool AllPeers() { return Catalog.Ready && (!ZNet.instance.IsServer() || WorldCommit.Ready) && (from p in ZNet.instance.GetPeers() where !p.m_server && p.m_uid != 0 select p).All((ZNetPeer p) => peers.Contains(p.m_uid)); } private static Player Actor(long sender) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (sender == ZNet.GetUID()) { return Player.m_localPlayer; } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer == null) { return null; } GameObject val = ZNetScene.instance.FindInstance(peer.m_characterID); Player val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<Player>() : null); if (!Object.op_Implicit((Object)(object)val2)) { return null; } ZNetView component = ((Component)val2).GetComponent<ZNetView>(); return (Object.op_Implicit((Object)(object)component) && component.IsValid() && component.GetZDO().GetOwner() == sender) ? val2 : null; } private static bool Access(Player actor, Vector3 position) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) List<PrivateArea> list = Native.Static<List<PrivateArea>>(typeof(PrivateArea), "m_allAreas"); bool flag = false; bool flag2 = false; foreach (PrivateArea item in list) { if (Object.op_Implicit((Object)(object)item) && Native.Call<bool>(item, "IsEnabled", Array.Empty<object>()) && Native.Call<bool>(item, "IsInside", new object[2] { position, 0f })) { flag = true; Piece component = ((Component)item).GetComponent<Piece>(); if ((Object.op_Implicit((Object)(object)component) && component.GetCreator() == actor.GetPlayerID()) || Native.Call<bool>(item, "IsPermitted", new object[1] { actor.GetPlayerID() })) { flag2 = true; } } } return !flag || flag2; } private static bool Validate(Player actor, ZDO data, PendingPayment operation, out Piece source, out Piece target, out string reason) { //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Unknown result type (might be due to invalid IL or missing references) source = (target = null); reason = "actor_unavailable"; if (!Object.op_Implicit((Object)(object)actor) || ((Character)actor).IsDead() || ((Character)actor).IsTeleporting()) { return false; } reason = "catalogue"; if (!AllPeers()) { return false; } reason = "source_missing"; if (data == null || data.GetPrefab() != operation.From) { return false; } reason = "pair_unavailable"; if (!Catalog.Allows(operation.From, operation.To) || !Catalog.Pieces.TryGetValue(operation.To, out target)) { return false; } GameObject val = ZNetScene.instance.FindInstance(data.m_uid); reason = "source_missing"; if (!Object.op_Implicit((Object)(object)val)) { return false; } reason = "source_parented"; if (Object.op_Implicit((Object)(object)val.transform.parent)) { return false; } source = val.GetComponent<Piece>(); reason = "source_health"; if (!Object.op_Implicit((Object)(object)source) || ((Component)source).GetComponent<WearNTear>().GetHealthPercentage() <= 0f) { return false; } reason = "distance"; float num = Vector3.Distance(((Component)actor).transform.position, val.transform.position); float num2 = Native.Get<float>(actor, "m_maxPlaceDistance"); if (num > num2) { Plugin.Log.LogWarning((object)("Upgrade distance: actual=" + num.ToString("F2", CultureInfo.InvariantCulture) + " limit=" + num2.ToString("F2", CultureInfo.InvariantCulture))); return false; } reason = "access"; if (!Access(actor, val.transform.position)) { return false; } if (!Catalog.InstanceMatches(source, operation.From, out reason) || !Catalog.InstanceMatches(Catalog.Pieces[operation.From], operation.From, out reason) || !Catalog.InstanceMatches(target, operation.To, out reason)) { return false; } reason = "source_station"; if (!Native.Call<bool>(actor, "CheckCanRemovePiece", new object[1] { source })) { return false; } reason = "target_station"; if (!operation.IgnoreStation && !actor.NoCostCheat() && Object.op_Implicit((Object)(object)target.m_craftingStation) && !Object.op_Implicit((Object)(object)CraftingStation.HaveBuildStationInRange(target.m_craftingStation.m_name, ((Component)actor).transform.position))) { return false; } reason = null; return true; } private static void Reply(long peer, PendingPayment op, OperationPhase phase) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) ZPackage val = Packet(Kind.Outcome); val.Write(op.Id); val.Write(op.Source); val.Write(op.From); val.Write(op.To); val.Write((int)phase); Send(peer, val); } private static void Refuse(long peer, string id, string reason = "refused") { Plugin.Log.LogWarning((object)("Upgrade refused by server: " + reason)); ZPackage val = Packet(Kind.Refused); val.Write(id); val.Write(reason); Send(peer, val); } private static void Handle(long sender, ZPackage packet) { //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_03d8: Unknown result type (might be due to invalid IL or missing references) //IL_03dd: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_04e3: Unknown result type (might be due to invalid IL or missing references) //IL_0412: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_06a6: Unknown result type (might be due to invalid IL or missing references) //IL_06b8: Unknown result type (might be due to invalid IL or missing references) //IL_07eb: Unknown result type (might be due to invalid IL or missing references) try { if (packet.Size() > 4096) { return; } Kind kind = (Kind)packet.ReadInt(); bool flag = ZNet.instance.IsServer(); if ((kind == Kind.HelloReply || kind == Kind.Grant || kind == Kind.Outcome || kind == Kind.Refused) && sender != Server) { return; } if (kind == Kind.Hello && flag) { if (packet.ReadString() == Protocol) { peers.Add(sender); } else { peers.Remove(sender); } ZPackage val = Packet(Kind.HelloReply); val.Write(Protocol); val.Write(peers.Contains(sender) && AllPeers()); Send(sender, val); } else { if (!flag && sender != Server) { return; } switch (kind) { case Kind.HelloReply: ServerReady = packet.ReadString() == Protocol && packet.ReadBool(); return; case Kind.Grant: { string text2 = packet.ReadString(); ZDOID val2 = packet.ReadZDOID(); int num2 = packet.ReadInt(); int num3 = packet.ReadInt(); if (requested == null || requested.Id != text2 || requested.Source != val2 || requested.From != num2 || requested.To != num3) { return; } PendingPayment pay = requested; requested = null; reserving = pay; try { InventoryEscrow.Reserve(Player.m_localPlayer, pay, delegate { if (IsReserving(pay)) { reserving = null; SendOperation(Server, Kind.Paid, pay); } }, delegate(string error) { if (IsReserving(pay)) { reserving = null; UpgradeController.Status = error; SendOperation(Server, Kind.Cancel, pay); } }); return; } catch (Exception ex) { reserving = null; UpgradeController.Status = ex.Message; SendOperation(Server, Kind.Cancel, pay); return; } } case Kind.Outcome: { string text3 = packet.ReadString(); ZDOID val3 = packet.ReadZDOID(); int num4 = packet.ReadInt(); int to = packet.ReadInt(); OperationPhase operationPhase = (OperationPhase)packet.ReadInt(); Player localPlayer = Player.m_localPlayer; PendingPayment pendingPayment = (Object.op_Implicit((Object)(object)localPlayer) ? PendingPayment.Read(localPlayer) : null); if (Object.op_Implicit((Object)(object)localPlayer) && pendingPayment == null && TransactionRules.IsFinal(operationPhase)) { SendOperation(Server, Kind.Ack, new PendingPayment { Id = text3, Source = val3, From = num4, To = to }); } else if (pendingPayment != null && !(pendingPayment.Source != val3) && TransactionRules.CanSettle(hasPending: true, pendingPayment.Id, text3, operationPhase) && InventoryEscrow.Settle(localPlayer, pendingPayment, operationPhase == OperationPhase.Committed)) { SendOperation(Server, Kind.Ack, pendingPayment); UpgradeController.Status = Texts.Get((operationPhase == OperationPhase.Committed) ? "done" : "refunded"); } return; } case Kind.Refused: { string text = packet.ReadString(); string key = ((packet.GetPos() < packet.Size()) ? packet.ReadString() : "refused"); if (requested?.Id == text) { requested = null; UpgradeController.Status = Texts.Get(key); } return; } case Kind.Refresh: if (sender == Server) { ZDOID key2 = packet.ReadZDOID(); int num = packet.ReadInt(); if (refreshes.Count < 512 && Catalog.Pieces.ContainsKey(num)) { refreshes[key2] = num; } } return; } if (!flag) { return; } PendingPayment pendingPayment2 = new PendingPayment { Id = packet.ReadString(), Source = packet.ReadZDOID(), From = packet.ReadInt(), To = packet.ReadInt(), IgnoreStation = packet.ReadBool() }; if (pendingPayment2.Id.Length != 32) { return; } Player val4 = Actor(sender); if (!Object.op_Implicit((Object)(object)val4)) { return; } if (SwapEngine.IsRecovering(pendingPayment2.Source)) { if (kind == Kind.Request) { Refuse(sender, pendingPayment2.Id, "recovery"); } return; } ZDO zDO = ZDOMan.instance.GetZDO(pendingPayment2.Source); string text4 = ((zDO != null) ? zDO.GetString("dellarion.vbs.tx", "") : null) ?? ""; long playerID = val4.GetPlayerID(); if (playerID == 0) { return; } OperationPhase operationPhase2 = ((zDO != null) ? ((OperationPhase)zDO.GetInt("dellarion.vbs.phase", 0)) : OperationPhase.None); bool flag2 = text4 == pendingPayment2.Id && zDO != null && zDO.GetLong("dellarion.vbs.actor", 0L) == playerID && zDO.GetInt("dellarion.vbs.from", 0) == pendingPayment2.From && zDO.GetInt("dellarion.vbs.to", 0) == pendingPayment2.To; switch (kind) { case Kind.Request: { if (flag2 && operationPhase2 == OperationPhase.Prepared) { SendOperation(sender, Kind.Grant, pendingPayment2); return; } if (operationPhase2 != OperationPhase.None) { Refuse(sender, pendingPayment2.Id, "locked"); return; } if (!Validate(val4, zDO, pendingPayment2, out var _, out var _, out var reason)) { Refuse(sender, pendingPayment2.Id, reason); return; } zDO.SetOwner(ZNet.GetUID()); zDO.Set("dellarion.vbs.tx", pendingPayment2.Id); zDO.Set("dellarion.vbs.actor", playerID); zDO.Set("dellarion.vbs.from", pendingPayment2.From); zDO.Set("dellarion.vbs.to", pendingPayment2.To); zDO.Set("dellarion.vbs.result", 0); zDO.Set("dellarion.vbs.deadline", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 20); zDO.Set("dellarion.vbs.phase", 1); Watch(zDO.m_uid); ZDOMan.instance.ForceSendZDO(zDO.m_uid); SendOperation(sender, Kind.Grant, pendingPayment2); return; } case Kind.Status: if (!flag2) { Reply(sender, pendingPayment2, OperationPhase.Rejected); } else if (operationPhase2 == OperationPhase.Prepared) { Commit(sender, val4, zDO, pendingPayment2); } else if (TransactionRules.IsFinal(operationPhase2)) { Reply(sender, pendingPayment2, operationPhase2); } else if (operationPhase2 == OperationPhase.None) { Reply(sender, pendingPayment2, (OperationPhase)zDO.GetInt("dellarion.vbs.result", 3)); } return; } if (!flag2) { if (kind == Kind.Paid) { Reply(sender, pendingPayment2, OperationPhase.Rejected); } return; } switch (kind) { case Kind.Paid: Commit(sender, val4, zDO, pendingPayment2); return; case Kind.Cancel: if (operationPhase2 == OperationPhase.Prepared) { zDO.Set("dellarion.vbs.result", 3); zDO.Set("dellarion.vbs.phase", 0); return; } break; } if (kind == Kind.Ack && TransactionRules.IsFinal(operationPhase2)) { zDO.Set("dellarion.vbs.phase", 0); ZDOMan.instance.ForceSendZDO(zDO.m_uid); } } } catch (Exception ex2) { Plugin.Log.LogWarning((object)("Ignored incomplete or failed upgrade RPC: " + ex2)); } } private static void Commit(long sender, Player actor, ZDO data, PendingPayment op) { //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) using (new OperationTiming("server replacement")) { OperationPhase phase = (OperationPhase)data.GetInt("dellarion.vbs.phase", 0); if (!TransactionRules.CanPay(phase, data.GetString("dellarion.vbs.tx", ""), op.Id, data.GetLong("dellarion.vbs.actor", 0L), actor.GetPlayerID())) { if (TransactionRules.IsFinal(phase)) { Reply(sender, op, phase); } return; } Piece source; Piece target; string reason; bool flag = Validate(actor, data, op, out source, out target, out reason); if (!flag) { Plugin.Log.LogWarning((object)("Upgrade commit rejected: " + reason)); } bool flag2 = false; if (flag) { try { using SwapEngine.StagedSwap stagedSwap = new SwapEngine.StagedSwap(data, source, target); data.Set("dellarion.vbs.phase", 2); data.Set("dellarion.vbs.result", 2); stagedSwap.Complete(); flag2 = true; } catch (SwapEngine.RecoveryPending recoveryPending) { Plugin.Log.LogError((object)("Upgrade blocked until original snapshot is restored: " + recoveryPending)); return; } catch (Exception ex) { Plugin.Log.LogWarning((object)("Original retained before commit: " + ex)); } } phase = (flag2 ? OperationPhase.Committed : OperationPhase.Rejected); data.Set("dellarion.vbs.result", (int)phase); data.Set("dellarion.vbs.phase", (int)phase); ZDOMan.instance.ForceSendZDO(data.m_uid); if (flag2) { BuildFeedback.Play(target, data); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { ZPackage val = Packet(Kind.Refresh); val.Write(data.m_uid); val.Write(data.GetPrefab()); Send(peer.m_uid, val); } } Reply(sender, op, phase); } } } internal sealed class OperationTiming : IDisposable { private readonly string stage; private readonly Stopwatch clock = Stopwatch.StartNew(); internal OperationTiming(string stage) { this.stage = stage; } public void Dispose() { clock.Stop(); Plugin.Log.LogInfo((object)("Upgrade timing: " + stage + " = " + clock.Elapsed.TotalMilliseconds.ToString("F1", CultureInfo.InvariantCulture) + " ms")); } } internal static class StructuralReader { private const int MaximumTriangles = 8192; private static readonly Type VisualOnly = typeof(Piece).Assembly.GetType("RandomMaterialValues"); private static readonly Type MaterialNotifier = typeof(Piece).Assembly.GetType("MaterialManNotifier"); private static readonly Type VisualRotation = typeof(Piece).Assembly.GetType("RandomPieceRotation"); private static readonly Type MeshCombine = Type.GetType("SimpleMeshCombine, assembly_simplemeshcombine", throwOnError: false); internal static string Number(float value) { if (float.IsNaN(value) || float.IsInfinity(value) || Math.Abs((double)value) > 1000000.0) { throw new InvalidOperationException("Non-finite or out-of-range structural coordinate"); } return ((long)Math.Round((double)value * 100000.0)).ToString(CultureInfo.InvariantCulture); } internal static string Point(Vector3 p) { //IL_0008: 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_0034: Unknown result type (might be due to invalid IL or missing references) return Number(p.x) + "," + Number(p.y) + "," + Number(p.z); } private static Matrix4x4 Local(Transform child, Transform root) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_002c: Unknown result type (might be due to invalid IL or missing references) return ((Object)(object)child == (Object)(object)root) ? Matrix4x4.identity : (Local(child.parent, root) * Matrix4x4.TRS(child.localPosition, child.localRotation, child.localScale)); } private static bool Fragment(Transform child, WearNTear wear) { foreach (GameObject item in Native.Get<IEnumerable<GameObject>>(wear, "m_fragmentRoots") ?? Array.Empty<GameObject>()) { if (Object.op_Implicit((Object)(object)item) && ((Object)(object)child == (Object)(object)item.transform || child.IsChildOf(item.transform))) { return true; } } return false; } private static bool HasStructure(Component component) { return component.GetComponentsInChildren<Collider>(true).Length != 0 || component.GetComponentsInChildren<Transform>(true).Any((Transform t) => ((Component)t).CompareTag("snappoint")); } private static StructuralComponent Kind(Component component) { Type type = ((object)component).GetType(); if (type == typeof(Piece)) { return StructuralComponent.Piece; } if (type == typeof(WearNTear)) { return StructuralComponent.WearNTear; } if (type == typeof(ZNetView)) { return StructuralComponent.ZNetView; } if (type == VisualOnly) { return StructuralComponent.MaterialValues; } if (type == MaterialNotifier) { return StructuralComponent.MaterialNotifier; } if (type == VisualRotation) { return StructuralComponent.RandomRotation; } if (type == MeshCombine) { return StructuralComponent.MeshCombine; } if (component is MonoBehaviour) { return StructuralComponent.UnknownBehaviour; } if (component is Transform) { return StructuralComponent.Transform; } if (component is Collider) { return StructuralComponent.Collider; } if (component is MeshFilter) { return StructuralComponent.MeshFilter; } if (component is MeshRenderer) { return StructuralComponent.MeshRenderer; } if (component is LODGroup) { return StructuralComponent.LodGroup; } if (component is ParticleSystem) { return StructuralComponent.ParticleSystem; } if (component is ParticleSystemRenderer) { return StructuralComponent.ParticleRenderer; } return StructuralComponent.OtherNative; } internal static bool Safe(Piece piece, out string reason) { reason = ""; WearNTear component = ((Component)piece).GetComponent<WearNTear>(); ZNetView component2 = ((Component)piece).GetComponent<ZNetView>(); if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component2) || !piece.m_enabled || !piece.m_canBeRemoved || !Object.op_Implicit((Object)(object)piece.m_icon) || !component.m_staticPosition || string.IsNullOrWhiteSpace(piece.m_name)) { reason = "not an enabled static building piece"; return false; } if (piece.m_comfort > 0 || piece.m_isUpgrade || piece.m_resources == null || piece.m_resources.Any((Requirement r) => !Object.op_Implicit((Object)(object)r.m_resItem) || !r.m_recover || r.GetAmount(1) < 0)) { reason = "interactive comfort, upgrade or unsupported recipe"; return false; } if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || piece.m_resources.Any((Requirement r) => !Object.op_Implicit((Object)(object)ObjectDB.instance.GetItemPrefab(Native.PrefabName(((Component)r.m_resItem).gameObject))))) { reason = "resource prefab is not registered for inventory recovery"; return false; } GameObject val = Native.Get<GameObject>(component, "m_wet"); bool flag = Object.op_Implicit((Object)(object)val) && StructuralComponents.WetBranchIsVisual((Object)(object)val.transform != (Object)(object)((Component)piece).transform && val.transform.IsChildOf(((Component)piece).transform), val.GetComponentsInChildren<Collider>(true).Length != 0, val.GetComponentsInChildren<Transform>(true).Any((Transform t) => ((Component)t).CompareTag("snappoint"))); Component[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Component>(true); foreach (Component val2 in componentsInChildren) { if (!Object.op_Implicit((Object)(object)val2)) { reason = "missing component"; return false; } StructuralComponent structuralComponent = Kind(val2); bool visualHasStructure = (structuralComponent == StructuralComponent.MeshCombine || structuralComponent == StructuralComponent.RandomRotation) && HasStructure(val2); bool inVisualWetBranch = flag && ((Object)(object)val2.transform == (Object)(object)val.transform || val2.transform.IsChildOf(val.transform)); string text = StructuralComponents.Rejection(structuralComponent, (Object)(object)val2.gameObject == (Object)(object)((Component)piece).gameObject, Fragment(val2.transform, component), visualHasStructure, inVisualWetBranch); if (text != null) { reason = text + ": " + ((object)val2).GetType().FullName; return false; } } return true; } internal static string Anchors(Piece piece) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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) List<string> list = new List<string>(); foreach (Transform item in ((Component)piece).transform) { Transform val = item; if (((Component)val).CompareTag("snappoint")) { Matrix4x4 val2 = Local(val, ((Component)piece).transform); list.Add(Point(((Matrix4x4)(ref val2)).MultiplyPoint3x4(Vector3.zero))); } } return string.Join(";", list.Distinct().OrderBy<string, string>((string p) => p, StringComparer.Ordinal)); } internal static string Geometry(Piece piece) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_045e: Unknown result type (might be due to invalid IL or missing references) //IL_048c: Unknown result type (might be due to invalid IL or missing references) //IL_04df: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: 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_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: Expected I4, but got Unknown WearNTear component = ((Component)piece).GetComponent<WearNTear>(); List<string> list = new List<string>(); Collider[] componentsInChildren = ((Component)piece).GetComponentsInChildren<Collider>(true); foreach (Collider val in componentsInChildren) { if (!val.enabled || val.isTrigger || Fragment(((Component)val).transform, component) || !ActiveWithin(((Component)val).transform, ((Component)piece).transform)) { continue; } if (Object.op_Implicit((Object)(object)val.attachedRigidbody) || Object.op_Implicit((Object)(object)val.sharedMaterial)) { return null; } Matrix4x4 matrix = Local(((Component)val).transform, ((Component)piece).transform); string[] obj = new string[5] { ((Component)val).gameObject.layer.ToString(CultureInfo.InvariantCulture), null, null, null, null }; LayerMask val2 = val.includeLayers; obj[1] = ((LayerMask)(ref val2)).value.ToString(CultureInfo.InvariantCulture); val2 = val.excludeLayers; obj[2] = ((LayerMask)(ref val2)).value.ToString(CultureInfo.InvariantCulture); obj[3] = val.layerOverridePriority.ToString(CultureInfo.InvariantCulture); obj[4] = Number(val.contactOffset); string text = CompatibilityIndex.Fields(obj); BoxCollider val3 = (BoxCollider)(object)((val is BoxCollider) ? val : null); if (val3 != null) { List<string> list2 = new List<string>(); for (int j = -1; j <= 1; j += 2) { for (int k = -1; k <= 1; k += 2) { for (int l = -1; l <= 1; l += 2) { list2.Add(Point(((Matrix4x4)(ref matrix)).MultiplyPoint3x4(val3.center + Vector3.Scale(val3.size, new Vector3((float)j, (float)k, (float)l)) / 2f))); } } } list.Add("box:" + text + ":" + string.Join(";", list2.OrderBy<string, string>((string c) => c, StringComparer.Ordinal))); continue; } MeshCollider val4 = (MeshCollider)(object)((val is MeshCollider) ? val : null); if (val4 != null) { if (!Object.op_Implicit((Object)(object)val4.sharedMesh) || !val4.sharedMesh.isReadable) { return null; } Vector3[] vertices = val4.sharedMesh.vertices; int[] triangles = val4.sharedMesh.triangles; if (triangles.Length == 0 || triangles.Length / 3 > 8192 || triangles.Length % 3 != 0) { return null; } List<string> list3 = new List<string>(); for (int num = 0; num < triangles.Length; num += 3) { string[] array = new int[3] { triangles[num], triangles[num + 1], triangles[num + 2] }.Select((int index) => Point(((Matrix4x4)(ref matrix)).MultiplyPoint3x4(vertices[index]))).ToArray(); list3.Add(CompatibilityIndex.OrientedFace(array[0], array[1], array[2])); } list.Add("mesh:" + text + ":" + val4.convex + ":" + ((int)val4.cookingOptions).ToString(CultureInfo.InvariantCulture) + ":" + CompatibilityIndex.Digest(string.Join("|", list3.OrderBy<string, string>((string f) => f, StringComparer.Ordinal)))); continue; } SphereCollider val5 = (SphereCollider)(object)((val is SphereCollider) ? val : null); if (val5 != null) { list.Add("sphere:" + text + ":" + Point(val5.center) + ":" + Number(val5.radius) + ":" + Matrix(matrix)); continue; } CapsuleCollider val6 = (CapsuleCollider)(object)((val is CapsuleCollider) ? val : null); if (val6 != null) { list.Add("capsule:" + text + ":" + Point(val6.center) + ":" + Number(val6.radius) + ":" + Number(val6.height) + ":" + val6.direction + ":" + Matrix(matrix)); continue; } return null; } return (list.Count == 0) ? null : CompatibilityIndex.Digest(string.Join("|", list.OrderBy<string, string>((string s) => s, StringComparer.Ordinal))); } private static bool ActiveWithin(Transform child, Transform root) { Transform val = child; while ((Object)(object)val != (Object)(object)root) { if (!Object.op_Implicit((Object)(object)val) || !((Component)val).gameObject.activeSelf) { return false; } val = val.parent; } return true; } private static string Matrix(Matrix4x4 m) { //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) return string.Join(";", from i in Enumerable.Range(0, 4) select Point(Vector4.op_Implicit(((Matrix4x4)(ref m)).GetColumn(i)))); } internal static StructuralDescriptor Describe(Piece piece, Vector3? nominalScale = null) { string reason; return Describe(piece, nominalScale, out reason); } internal static StructuralDescriptor Describe(Piece piece, Vector3? nominalScale, out string reason) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) bool flag = Safe(piece, out reason); ZNetView component = ((Component)piece).GetComponent<ZNetView>(); string text = Native.PrefabName(((Component)piece).gameObject); string network = (Object.op_Implicit((Object)(object)component) ? CompatibilityIndex.Fields(((object)Unsafe.As<ObjectType, ObjectType>(ref component.m_type)/*cast due to .constrained prefix*/).ToString(), component.m_persistent.ToString(), component.m_distant.ToString(), component.m_syncInitialScale.ToString(), Point((Vector3)(((??)nominalScale) ?? ((Component)piece).transform.localScale))) : ""); string text2 = ((piece.m_resources == null) ? "" : string.Join(";", (from r in piece.m_resources where Object.op_Implicit((Object)(object)r.m_resItem) select CompatibilityIndex.Fields(Native.PrefabName(((Component)r.m_resItem).gameObject), r.GetAmount(1).ToString(CultureInfo.InvariantCulture), r.m_recover.ToString())).OrderBy<string, string>((string r) => r, StringComparer.Ordinal))); WearNTear component2 = ((Component)piece).GetComponent<WearNTear>(); text2 = CompatibilityIndex.Fields(text2, Object.op_Implicit((Object)(object)piece.m_craftingStation) ? piece.m_craftingStation.m_name : "", piece.m_dlc, Object.op_Implicit((Object)(object)component2) ? CompatibilityIndex.Fields(Number(component2.m_health), ((object)Unsafe.As<MaterialType, MaterialType>(ref component2.m_materialType)/*cast due to .constrained prefix*/).ToString(), component2.m_supports.ToString(), Point(component2.m_comOffset), component2.m_noSupportWear.ToString()) : ""); string text3 = Anchors(piece); if (flag && text3.Split(';').Length < 2) { reason = "fewer than two distinct snap points"; } return new StructuralDescriptor { Id = StringExtensionMethods.GetStableHashCode(text), Name = text, Anchors = text3, Geometry = (flag ? Geometry(piece) : null), Network = network, Recipe = text2, Structural = (flag && text3.Split(';').Length >= 2) }; } } internal static class SwapEngine { internal sealed class RecoveryPending : Exception { internal RecoveryPending(Exception cause) : base("Replacement rollback is pending; payment must remain reserved", cause) { } } internal sealed class StagedSwap : IDisposable { internal readonly ZDO data; private readonly ZNetView old; private readonly int originalPrefab; private readonly Vector3 originalPosition; private readonly byte[] originalData; private readonly long originalOwner; internal readonly ReplacementGuard guard; private GameObject replacement; internal StagedSwap(ZDO data, Piece source, Piece target) { //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) this.data = data; old = ZNetScene.instance.FindInstance(data); if (!Object.op_Implicit((Object)(object)old) || Object.op_Implicit((Object)(object)((Component)old).transform.parent)) { throw new InvalidOperationException("Original instance is unavailable or parented"); } originalPrefab = data.GetPrefab(); originalPosition = data.GetPosition(); ZPackage val = new ZPackage(); Native.Call<object>(data, "Serialize", new object[1] { val }); originalData = val.GetArray(); originalOwner = data.GetOwner(); guard = new ReplacementGuard(Rollback, delegate { Retire(((Component)old).gameObject); }, delegate(Exception e) { Plugin.Log.LogError((object)("Committed replacement; original cleanup needs attention: " + e)); }); try { data.Set("dellarion.vbs.scale", ((Component)old).transform.localScale); data.Set(ZDOVars.s_health, ((Component)target).GetComponent<WearNTear>().m_health); data.SetPrefab(StringExtensionMethods.GetStableHashCode(Native.PrefabName(((Component)target).gameObject))); Vector3 val2 = Catalog.Alignment(Catalog.Pieces[originalPrefab], target); data.SetPosition(((Component)old).transform.TransformPoint(val2)); replacement = CreateChecked(data, old); ((Component)old).gameObject.SetActive(false); Physics.SyncTransforms(); } catch (Exception ex) { try { guard.Dispose(); } catch (Exception ex2) { recovering[data.m_uid] = this; throw new RecoveryPending(new AggregateException(ex, ex2)); } throw; } } internal void Complete() { guard.Commit(); } private void Rollback() { //IL_0036: 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_0066: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) Native.CallStatic(typeof(ZDO).Assembly.GetType("ZDOExtraData"), "Release", data, data.m_uid); Native.Call<object>(data, "Deserialize", new object[1] { (object)new ZPackage(originalData) }); data.SetOwner(originalOwner); data.SetPosition(originalPosition); Native.Call<object>(data, "IncreaseDataRevision", Array.Empty<object>()); if (Object.op_Implicit((Object)(object)replacement)) { Retire(replacement); } ZNetScene.instance.AddInstance(data, old); ((Component)old).gameObject.SetActive(true); Physics.SyncTransforms(); } public void Dispose() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) try { guard.Dispose(); } catch (Exception cause) { recovering[data.m_uid] = this; throw new RecoveryPending(cause); } } } private static readonly Dictionary<ZDOID, StagedSwap> recovering = new Dictionary<ZDOID, StagedSwap>(); internal const string ScaleKey = "dellarion.vbs.scale"; private static readonly MethodInfo Create = AccessTools.Method(typeof(ZNetScene), "CreateObject", (Type[])null, (Type[])null); internal static bool IsRecovering(ZDOID id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return recovering.ContainsKey(id); } internal static void ResetRecoveries() { recovering.Clear(); } internal static void Recover() { //IL_0059: 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) KeyValuePair<ZDOID, StagedSwap>[] array = recovering.ToArray(); for (int i = 0; i < array.Length; i++) { KeyValuePair<ZDOID, StagedSwap> keyValuePair = array[i]; try { keyValuePair.Value.guard.Dispose(); ZDO data = keyValuePair.Value.data; data.Set("dellarion.vbs.result", 3); data.Set("dellarion.vbs.phase", 3); ZDOMan.instance.ForceSendZDO(data.m_uid); recovering.Remove(keyValuePair.Key); } catch { } } } private static void Retire(GameObject go) { ZNetView component = go.GetComponent<ZNetView>(); if (Object.op_Implicit((Object)(object)component)) { Native.Set(component, "m_zdo", null); } go.SetActive(false); Object.Destroy((Object)(object)go); } private static GameObject CreateChecked(ZDO data, ZNetView old) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0087: 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) GameObject val = null; try { val = (GameObject)Create.Invoke(ZNetScene.instance, new object[1] { data }); if (!Object.op_Implicit((Object)(object)val)) { throw new InvalidOperationException("Native creation returned no object"); } ZNetView component = val.GetComponent<ZNetView>(); if (!Object.op_Implicit((Object)(object)component) || component.GetZDO() != data || !Object.op_Implicit((Object)(object)val.GetComponent<Piece>()) || !Object.op_Implicit((Object)(object)val.GetComponent<WearNTear>())) { throw new InvalidOperationException("Incomplete native replacement"); } val.transform.SetPositionAndRotation(data.GetPosition(), ((Component)old).transform.rotation); val.transform.localScale = ((Component)old).transform.localScale; Physics.SyncTransforms(); return val; } catch { if (Object.op_Implicit((Object)(object)val)) { Retire(val); } else { ZNetView val2 = ZNetScene.instance.FindInstance(data); if (Object.op_Implicit((Object)(object)val2) && (Object)(object)val2 != (Object)(object)old) { Retire(((Component)val2).gameObject); } } ZNetScene.instance.AddInstance(data, old); throw; } finally { AccessTools.Field(typeof(ZNetView), "m_useInitZDO").SetValue(null, false); AccessTools.Field(typeof(ZNetView), "m_initZDO").SetValue(null, null); } } internal static bool Refresh(ZDO data) { ZNetView val = ZNetScene.instance.FindInstance(data); if (!Object.op_Implicit((Object)(object)val) || StringExtensionMethods.GetStableHashCode(Native.PrefabName(((Component)val).gameObject)) == data.GetPrefab()) { return true; } if (Object.op_Implicit((Object)(object)((Component)val).transform.parent)) { return false; } try { CreateChecked(data, val); Retire(((Component)val).gameObject); return true; } catch (Exception ex) { Plugin.Log.LogError((object)("Client retained original instance and will retry: " + ex)); return false; } } internal static void RestoreScale(ZDO __0, GameObject __result) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)__result) && __0.GetString("dellarion.vbs.tx", "").Length != 0) { __result.transform.localScale = __0.GetVec3("dellarion.vbs.scale", __result.transform.localScale); if (__0.GetInt("dellarion.vbs.phase", 0) != 0) { Network.Watch(__0.m_uid); } } } } internal static class WorldCommit { private static DurableJournal journal; private static long world; private static long snapshotSequence; private static long snapshotWorld; [ThreadStatic] private static long savingSequence; [ThreadStatic] private static long savingWorld; private static long generation; private static long snapshotGeneration; [ThreadStatic] private static long savingGeneration; private static bool recovered; internal static bool Ready => recovered && journal != null; internal static void ResetSession() { journal = null; recovered = false; Interlocked.Increment(ref generation); } internal static void SnapshotStarted() { snapshotSequence = journal?.Sequence ?? 0; snapshotWorld = world; snapshotGeneration = generation; } internal static void ThreadStarted() { savingSequence = snapshotSequence; savingWorld = snapshotWorld; savingGeneration = snapshotGeneration; } internal static void SaveEnded(bool __1) { DurableJournal durableJournal = journal; if (!__1 || durableJournal == null || savingSequence == 0L || savingWorld != Volatile.Read(in world) || savingGeneration != Volatile.Read(in generation)) { return; } try { lock (durableJournal) { if (savingGeneration == Volatile.Read(in generation)) { durableJournal.Checkpoint(savingSequence); } } } catch (Exception ex) { Plugin.Log.LogError((object)("Could not retire legacy recovery records after ordinary world save: " + ex)); } } internal static void ThreadFinished() { savingSequence = 0L; savingWorld = 0L; } internal static void Initialize() { //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_0115: 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) //IL_013c: 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_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Expected O, but got Unknown //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) if (!ZNet.instance.IsServer()) { return; } long worldUID = ZNet.instance.GetWorldUID(); if (journal != null && world == worldUID && recovered) { return; } recovered = false; world = worldUID; journal = new DurableJournal(Path.Combine(Paths.ConfigPath, "VanillaBuildSwap", "world-" + worldUID + ".journal")); foreach (DurableJournal.Entry item in journal.Entries.Values.OrderBy((DurableJournal.Entry e) => e.Sequence)) { ZPackage val = new ZPackage(item.Payload); bool flag = val.ReadBool(); ZDOID val2 = val.ReadZDOID(); if (flag) { Native.Call<object>(ZDOMan.instance, "HandleDestroyedZDO", new object[1] { val2 }); continue; } Vector3 val3 = val.ReadVector3(); int num = val.ReadInt(); string text = val.ReadString(); byte[] array = val.ReadByteArray(); ZDO val4 = ZDOMan.instance.GetZDO(val2); if (val4 != null && val4.GetPrefab() == num && val4.GetString("dellarion.vbs.tx", "") == text) { Network.Watch(val2); continue; } if (val4 == null) { val4 = Native.Call<ZDO>(ZDOMan.instance, "CreateNewZDO", new object[3] { val2, val3, num }); long num2 = Native.Get<long>(ZDOMan.instance, "m_sessionID"); if (((ZDOID)(ref val2)).UserID == num2 && ((ZDOID)(ref val2)).ID >= Native.Get<uint>(ZDOMan.instance, "m_nextUid")) { Native.Set(ZDOMan.instance, "m_nextUid", checked(((ZDOID)(ref val2)).ID + 1)); } } Native.Call<object>(val4, "Deserialize", new object[1] { (object)new ZPackage(array) }); val4.SetPosition(val3); val4.SetOwner(ZNet.GetUID()); Native.Call<object>(val4, "IncreaseDataRevision", Array.Empty<object>()); Network.Watch(val2); } recovered = true; } internal static void Tick() { if (ZNet.instance.IsServer()) { Initialize(); } } } [Serializable] internal sealed class OverlayTokens { public float backgroundOpacity; public float sideOpacity; public float nextEndOpacity; public float lastOpacity; public float fadeHalf; public float borderWidth; public float nameHeightCells; public float detailHeightCells; public float healthGapUnits; public float cellGapUnits; public float textGapUnits; public float resourceRefreshSeconds; internal static OverlayTokens Load() { using Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BuildPieceSwap.tokens.overlay.json"); using StreamReader streamReader = new StreamReader(stream); return JsonUtility.FromJson<OverlayTokens>(streamReader.ReadToEnd()); } } public sealed class CarouselIcon : MaskableGraphic { public Sprite Sprite; public int Side; public float SideOpacity; public float NextEndOpacity; public float LastOpacity; public float FadeHalf; public override Texture mainTexture => (Texture)(object)(Object.op_Implicit((Object)(object)Sprite) ? Sprite.texture : Texture2D.whiteTexture); protected override void OnPopulateMesh(VertexHelper vh) { //IL_000e: 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_0042: 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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) vh.Clear(); Rect rect = ((Graphic)this).rectTransform.rect; Vector4 val = (Vector4)(Object.op_Implicit((Object)(object)Sprite) ? DataUtility.GetOuterUV(Sprite) : new Vector4(0f, 0f, 1f, 1f)); float num = ((Side < 0) ? FadeHalf : (1f - FadeHalf)); if (Side == 0) { num = FadeHalf; } float[] array = new float[3] { 0f, num, 1f }; float[] array2 = array