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 WorldEditorBridge v1.127.0
plugins/WorldEditorBridge.dll
Decompiled 4 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Microsoft.CodeAnalysis; using UnityEngine; using WorldEditorBridge.Api; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: AssemblyCompany("WorldEditorBridge")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.127.0.0")] [assembly: AssemblyInformationalVersion("1.127.0+32cdcbe34fb2b6e5ae8227b001c7868aa225cec4")] [assembly: AssemblyProduct("WorldEditorBridge")] [assembly: AssemblyTitle("WorldEditorBridge")] [assembly: AssemblyVersion("1.127.0.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Count; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Count; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyList(List<T> items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return _items.Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return _items.IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } internal static class BuildInfo { public const string Version = "1.127.0"; } namespace WorldEditorBridge { internal static class BridgeAccess { public const string TokenHeader = "X-Bridge-Token"; public static (int Status, string Text)? Refusal(IPAddress? caller, NameValueCollection headers, string token) { if (!MayConnect(caller)) { return (403, "only this machine and its local networks may connect: use an SSH tunnel to 127.0.0.1"); } if (!SameToken(headers["X-Bridge-Token"], token)) { return (401, "bad or missing token"); } return null; } public static bool MayConnect(IPAddress? ip) { if (ip == null) { return false; } if (ip.IsIPv4MappedToIPv6) { ip = ip.MapToIPv4(); } if (IPAddress.IsLoopback(ip)) { return true; } byte[] addressBytes = ip.GetAddressBytes(); if (ip.AddressFamily != AddressFamily.InterNetwork) { if ((addressBytes[0] & 0xFE) != 252) { return ip.IsIPv6LinkLocal; } return true; } if (addressBytes[0] != 10 && (addressBytes[0] != 172 || (addressBytes[1] & 0xF0) != 16) && (addressBytes[0] != 192 || addressBytes[1] != 168) && (addressBytes[0] != 169 || addressBytes[1] != 254)) { if (addressBytes[0] == 100) { return (addressBytes[1] & 0xC0) == 64; } return false; } return true; } public static bool SameToken(string? given, string? expected) { byte[] bytes = Encoding.UTF8.GetBytes(given ?? ""); byte[] bytes2 = Encoding.UTF8.GetBytes(expected ?? ""); int num = bytes.Length ^ bytes2.Length; for (int i = 0; i < bytes2.Length; i++) { num |= ((i < bytes.Length) ? bytes[i] : 0) ^ bytes2[i]; } if (num == 0) { return bytes2.Length != 0; } return false; } public static string? BindWarning(string bind) { if (!string.Equals(bind, "localhost", StringComparison.OrdinalIgnoreCase) && (!IPAddress.TryParse(bind.Trim('[', ']'), out IPAddress address) || !IPAddress.IsLoopback(address))) { return "WorldEditorBridge: BindAddress " + bind + " lets other machines of this one's local networks connect (never the internet's), and the token travels unencrypted (plain HTTP): anyone on those networks can read it and change the world. Keep 127.0.0.1 and reach it through an SSH tunnel (the editor makes one)."; } return null; } } [BepInPlugin("Tie.WorldEditorBridge", "WorldEditorBridge", "1.127.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class WorldEditorBridgePlugin : BaseUnityPlugin { private sealed class Job { public Func<byte[]> Work; public byte[] Result; public Exception Error; public readonly ManualResetEventSlim Done = new ManualResetEventSlim(initialState: false); public int State; } private sealed class ObjectMove(ZDOID id, int prefab, Vector3 from, Vector3 to, Vector3 rotation, SavedObject fallback) { public ZDOID Id { get; } = id; public int Prefab { get; } = prefab; public Vector3 From { get; } = from; public Vector3 To { get; } = to; public Vector3 Rotation { get; } = rotation; public SavedObject Fallback { get; } = fallback; public bool Data { get; set; } } private sealed class SavedObject { public int Flags { get; set; } public Vector3 Position { get; set; } public int Prefab { get; set; } public Vector3 Euler { get; set; } public ConnectionType LinkType { get; set; } public int LinkHash { get; set; } public List<KeyValuePair<int, float>> Floats { get; } = new List<KeyValuePair<int, float>>(); public List<KeyValuePair<int, Vector3>> Vec3s { get; } = new List<KeyValuePair<int, Vector3>>(); public List<KeyValuePair<int, Quaternion>> Quats { get; } = new List<KeyValuePair<int, Quaternion>>(); public List<KeyValuePair<int, int>> Ints { get; } = new List<KeyValuePair<int, int>>(); public List<KeyValuePair<int, long>> Longs { get; } = new List<KeyValuePair<int, long>>(); public List<KeyValuePair<int, string>> Strings { get; } = new List<KeyValuePair<int, string>>(); public List<KeyValuePair<int, byte[]>> Bytes { get; } = new List<KeyValuePair<int, byte[]>>(); public ZDO Make() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) ZDO val = ZDOMan.instance.CreateNewZDO(Position, Prefab); val.Persistent = (Flags & 0x100) != 0; val.Distant = (Flags & 0x200) != 0; val.Type = (ObjectType)(byte)((Flags >> 10) & 3); val.SetPrefab(Prefab); val.SetRotation(Quaternion.Euler(Euler)); SetValues(val); if ((int)LinkType != 0) { Relink(val, LinkType, LinkHash); } Announce(val); return val; } public void PutOn(ZDO zdo) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00db: 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_015c: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) FastIterableKeyValues<int, float> had = default(FastIterableKeyValues<int, float>); FastIterableKeyValues<int, Vector3> had2 = default(FastIterableKeyValues<int, Vector3>); FastIterableKeyValues<int, Quaternion> had3 = default(FastIterableKeyValues<int, Quaternion>); FastIterableKeyValues<int, int> had4 = default(FastIterableKeyValues<int, int>); FastIterableKeyValues<int, long> had5 = default(FastIterableKeyValues<int, long>); FastIterableKeyValues<int, string> had6 = default(FastIterableKeyValues<int, string>); FastIterableKeyValues<int, byte[]> had7 = default(FastIterableKeyValues<int, byte[]>); ZDOConnection val = default(ZDOConnection); ZDOExtraData.GetData(zdo.m_uid, ref had, ref had2, ref had3, ref had4, ref had5, ref had6, ref had7, ref val); foreach (int item in Stale<float>(had, Floats)) { zdo.RemoveFloat(item); } foreach (int item2 in Stale<Vector3>(had2, Vec3s)) { zdo.RemoveVec3(item2); } foreach (int item3 in Stale<Quaternion>(had3, Quats)) { zdo.RemoveQuaternion(item3); } foreach (int item4 in Stale<int>(had4, Ints)) { zdo.RemoveInt(item4); } foreach (int item5 in Stale<long>(had5, Longs)) { zdo.RemoveLong(item5); } foreach (int item6 in Stale<string>(had6, Strings)) { zdo.RemoveString(item6); } foreach (int item7 in Stale<byte[]>(had7, Bytes)) { zdo.RemoveByteArray(item7); } SetValues(zdo); uint dataRevision = zdo.DataRevision; zdo.DataRevision = dataRevision + 1; static List<int> Stale<T>(FastIterableKeyValues<int, T> val2, List<KeyValuePair<int, T>> now) { HashSet<int> hashSet = new HashSet<int>(); foreach (int item8 in now.Select((KeyValuePair<int, T> kv) => kv.Key)) { hashSet.Add(item8); } HashSet<int> hashSet2 = hashSet; List<int> list = new List<int>(); for (int num = 0; num < val2.Count; num++) { if (!hashSet2.Contains(val2[num].Key)) { list.Add(val2[num].Key); } } return list; } } private void SetValues(ZDO zdo) { Floats.ForEach(delegate(KeyValuePair<int, float> kv) { zdo.Set(kv.Key, kv.Value); }); Vec3s.ForEach(delegate(KeyValuePair<int, Vector3> kv) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) zdo.Set(kv.Key, kv.Value); }); Quats.ForEach(delegate(KeyValuePair<int, Quaternion> kv) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) zdo.Set(kv.Key, kv.Value); }); Ints.ForEach(delegate(KeyValuePair<int, int> kv) { zdo.Set(kv.Key, kv.Value, false); }); Longs.ForEach(delegate(KeyValuePair<int, long> kv) { zdo.Set(kv.Key, kv.Value); }); Strings.ForEach(delegate(KeyValuePair<int, string> kv) { zdo.Set(kv.Key, kv.Value); }); Bytes.ForEach(delegate(KeyValuePair<int, byte[]> kv) { zdo.Set(kv.Key, kv.Value); }); } } private const int CallsKept = 16; private readonly List<(string Id, byte[] Answer)> _calls = new List<(string, byte[])>(); private readonly string _run = Guid.NewGuid().ToString("N"); private const int CatalogueVersion = 1; private const string JotunnGuid = "com.jotunn.jotunn"; private static readonly FieldInfo NamedPrefabs = typeof(ZNetScene).GetField("m_namedPrefabs", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly Dictionary<string, string> ToolTables = new Dictionary<string, string> { ["_HammerPieceTable"] = "hammer", ["_HoePieceTable"] = "hoe", ["_CultivatorPieceTable"] = "cultivator", ["_FeasterPieceTable"] = "feaster" }; public const string PluginGuid = "Tie.WorldEditorBridge"; private const string OldGuid = "local.worldeditorbridge"; public const string Version = "1.127.0"; private const int SnapshotVersion = 1; private ConfigEntry<string> _bind; private ConfigEntry<int> _port; private ConfigEntry<string> _token; private HttpListener _listener; private Thread _thread; private volatile bool _running; private readonly ConcurrentQueue<Job> _jobs = new ConcurrentQueue<Job>(); private static readonly FieldInfo ObjectsById = typeof(ZDOMan).GetField("m_objectsByID", BindingFlags.Instance | BindingFlags.NonPublic); private readonly Queue<(float Due, List<AppliedObject> Gone, List<AppliedObject> Made)> _destroyChecks = new Queue<(float, List<AppliedObject>, List<AppliedObject>)>(); private static readonly FieldInfo GeneratedZones = typeof(ZoneSystem).GetField("m_generatedZones", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo ZdoRotation = typeof(ZDO).GetField("m_rotation", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo GlobalKeys = typeof(ZoneSystem).GetField("m_globalKeys", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly int LocationProxyPrefab = StringExtensionMethods.GetStableHashCode("LocationProxy"); private static readonly int DiscLocation = StringExtensionMethods.GetStableHashCode("DevGround1"); private const float DiscsEvery = 5f; private readonly HashSet<ZDOID> _discs = new HashSet<ZDOID>(); private ZDOMan _discsOf; private float _discsDue; private const int MaxConfigFile = 4194304; private static readonly MethodInfo MetaPath = typeof(World).GetMethod("GetMetaPath", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); private static readonly Dictionary<int, (ConnectionType Type, ZDOID Source, ZDOID Target)> Links = new Dictionary<int, (ConnectionType, ZDOID, ZDOID)>(); private const int MaxModBody = 16777216; private static readonly int TombstonePrefab = StringExtensionMethods.GetStableHashCode("Player_tombstone"); private static readonly int TerrainCompilerPrefab = StringExtensionMethods.GetStableHashCode("_TerrainCompiler"); private static readonly Dictionary<int, bool> Movers = new Dictionary<int, bool>(); private static readonly FieldInfo ObjectsBySector = typeof(ZDOMan).GetField("m_objectsBySector", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly FieldInfo PortalObjects = typeof(ZDOMan).GetField("m_portalObjects", BindingFlags.Instance | BindingFlags.NonPublic); private static void Announce(ZDO zdo) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown ZPackage val = new ZPackage(); zdo.Serialize(val); val.SetPos(0); zdo.Deserialize(val); } private byte[] ApplyObjectsOnce(string call, byte[] body) { if (call != null) { foreach (var (text, result) in _calls) { if (text == call) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"WorldEditorBridge: objects call sent again (its answer was lost): answered with what was done, not done twice"); return result; } } } byte[] array = Applied(ApplyObjects(body)); if (call != null) { if (_calls.Count == 16) { _calls.RemoveAt(0); } _calls.Add((call, array)); } return array; } private void EnableModQuery() { try { Type.GetType("Jotunn.Utils.ModQuery, Jotunn")?.GetMethod("Enable", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null)?.Invoke(null, null); } catch (Exception e) { Caught(e, "asking Jötunn to note which mod adds each prefab (no mod names)", brief: false, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.Catalogue.cs", 50, "EnableModQuery"); } } private byte[] Catalogue() { List<GameObject> list = AllPrefabs(); Dictionary<string, string> dictionary = PieceTools(); Dictionary<string, string> dictionary2 = new Dictionary<string, string>(); StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); foreach (GameObject item in list) { if (Object.op_Implicit((Object)(object)item.GetComponent<ZNetView>())) { Comma(stringBuilder).Append(Json(((Object)item).name)).Append(':').Append(PrefabEntry(item)); Piece component = item.GetComponent<Piece>(); if (component != null && Object.op_Implicit((Object)(object)component)) { Comma(stringBuilder2).Append(Json(((Object)item).name)).Append(':').Append(PieceEntry(item, component, dictionary.TryGetValue(((Object)item).name, out var value) ? value : null)); Comma(stringBuilder3).Append(Json(((Object)item).name)).Append(':').Append(CostEntry(component, dictionary2)); } } } StringBuilder stringBuilder4 = new StringBuilder(); foreach (KeyValuePair<string, string> item2 in PrefabMods()) { Comma(stringBuilder4).Append(Json(item2.Key)).Append(':').Append(Json(item2.Value)); } StringBuilder stringBuilder5 = new StringBuilder(); foreach (KeyValuePair<string, string> item3 in dictionary2) { Comma(stringBuilder5).Append(Json(item3.Key)).Append(':').Append(Json(item3.Value)); } string s = $"{{\"version\":{1},\"prefabs\":{{{stringBuilder}}},\"pieces\":{{{stringBuilder2}}},\"cost\":{{\"pieces\":{{{stringBuilder3}}},\"items\":{{{stringBuilder5}}}}},\"mods\":{{{stringBuilder4}}}}}"; return Encoding.UTF8.GetBytes(s); } private static StringBuilder Comma(StringBuilder sb) { if (sb.Length <= 0) { return sb; } return sb.Append(','); } private static string English(string token) { if (Localization.instance == null) { return token; } return Localization.instance.Localize(token); } private static string R(float v) { return Math.Round(v, 3).ToString("R", CultureInfo.InvariantCulture); } private static string CostEntry(Piece piece, Dictionary<string, string> items) { List<string> list = new List<string>(); Requirement[] array = piece.m_resources ?? Array.Empty<Requirement>(); foreach (Requirement val in array) { if (Object.op_Implicit((Object)(object)val.m_resItem) && val.m_amount > 0) { string name = ((Object)val.m_resItem).name; if (!items.ContainsKey(name)) { items[name] = English(val.m_resItem.m_itemData?.m_shared?.m_name ?? name); } list.Add($"[{Json(name)},{val.m_amount},{(val.m_recover ? 1 : 0)}]"); } } string text = "{\"n\":" + Json(English(piece.m_name ?? ((Object)piece).name)) + ",\"r\":[" + string.Join(",", list) + "]"; if (Object.op_Implicit((Object)(object)piece.m_craftingStation)) { text = text + ",\"st\":" + Json(English(piece.m_craftingStation.m_name ?? "")); } return text + "}"; } private static bool Finite(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (Finite(p.x) && Finite(p.y)) { return Finite(p.z); } return false; } private static bool Finite(float v) { if (!float.IsNaN(v)) { return !float.IsInfinity(v); } return false; } private static bool ActiveUnder(Transform t, Transform root) { while (Object.op_Implicit((Object)(object)t) && (Object)(object)t != (Object)(object)root) { if (!((Component)t).gameObject.activeSelf) { return false; } t = t.parent; } return true; } private Dictionary<string, string> PrefabMods() { Dictionary<string, string> dictionary = new Dictionary<string, string>(); Dictionary<string, string> dictionary2 = new Dictionary<string, string>(); try { if (!(Type.GetType("Jotunn.Utils.ModQuery, Jotunn")?.GetMethod("GetPrefabs", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null)?.Invoke(null, null) is IEnumerable enumerable)) { return dictionary; } foreach (object item in enumerable) { Type type = item.GetType(); object? obj = type.GetProperty("Prefab")?.GetValue(item); GameObject val = (GameObject)((obj is GameObject) ? obj : null); if (val == null || !Object.op_Implicit((Object)(object)val)) { continue; } object? obj2 = type.GetProperty("SourceMod")?.GetValue(item); BepInPlugin val2 = (BepInPlugin)((obj2 is BepInPlugin) ? obj2 : null); if (val2 != null) { if (!dictionary2.TryGetValue(val2.GUID, out var value)) { value = (dictionary2[val2.GUID] = ModName(val2)); } dictionary[((Object)val).name] = value; } } } catch (Exception e) { Caught(e, "asking Jötunn which mod adds each prefab (no mod names)", brief: false, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.CatalogueMods.cs", 41, "PrefabMods"); } return dictionary; } private string ModName(BepInPlugin plugin) { if (!Chainloader.PluginInfos.TryGetValue(plugin.GUID, out var value) || string.IsNullOrEmpty(value.Location)) { return plugin.Name; } string text = Path.GetFullPath(Paths.PluginPath).TrimEnd(new char[1] { Path.DirectorySeparatorChar }); char directorySeparatorChar = Path.DirectorySeparatorChar; string text2 = text + directorySeparatorChar; string fullPath = Path.GetFullPath(value.Location); if (!fullPath.StartsWith(text2, StringComparison.OrdinalIgnoreCase)) { return plugin.Name; } string[] array = fullPath.Substring(text2.Length).Split(new char[1] { Path.DirectorySeparatorChar }); if (array.Length < 2) { return plugin.Name; } string text3 = array[0]; try { string path = Path.Combine(text2 + text3, "manifest.json"); if (File.Exists(path)) { Match match = Regex.Match(File.ReadAllText(path), "\"name\"\\s*:\\s*\"([^\"]+)\""); if (match != null && match.Success) { return match.Groups[1].Value; } } } catch (Exception ex) when (((ex is IOException || ex is UnauthorizedAccessException) ? 1 : 0) != 0) { Caught(ex, "reading the manifest.json of " + text3 + " (its folder's name is used)", brief: true, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.CatalogueNames.cs", 45, "ModName"); } int num = text3.IndexOf('-'); if (num <= 0 || num >= text3.Length - 1) { return text3; } return text3.Substring(num + 1); } private static string PieceEntry(GameObject go, Piece piece, string tool) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected I4, but got Unknown //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_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: 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_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) Transform transform = go.transform; Matrix4x4 worldToLocalMatrix = transform.worldToLocalMatrix; StringBuilder stringBuilder = new StringBuilder($"{{\"cat\":{(int)piece.m_category},\"comfort\":{piece.m_comfort}"); List<Vector3> list = new List<Vector3>(); Transform[] componentsInChildren = go.GetComponentsInChildren<Transform>(true); foreach (Transform val in componentsInChildren) { if ((Object)(object)val != (Object)(object)transform && (((Component)val).CompareTag("snappoint") || ((Object)val).name.IndexOf("snappoint", StringComparison.OrdinalIgnoreCase) >= 0)) { Vector3 val2 = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val.position); if (Finite(val2)) { list.Add(val2); } } } if (list.Count > 0) { stringBuilder.Append(",\"snap\":[").Append(string.Join(",", list.Select((Vector3 p) => "[" + R(p.x) + "," + R(p.y) + "," + R(p.z) + "]"))).Append(']'); } Vector3 val3 = Vector3.positiveInfinity; Vector3 val4 = Vector3.negativeInfinity; BoxCollider[] componentsInChildren2 = go.GetComponentsInChildren<BoxCollider>(true); foreach (BoxCollider val5 in componentsInChildren2) { if (!((Collider)val5).isTrigger && ((Collider)val5).enabled && ActiveUnder(((Component)val5).transform, transform)) { Matrix4x4 val6 = worldToLocalMatrix * ((Component)val5).transform.localToWorldMatrix; for (int num = 0; num < 8; num++) { Vector3 val7 = val5.center + Vector3.Scale(val5.size * 0.5f, new Vector3((float)(((num & 1) != 0) ? 1 : (-1)), (float)(((num & 2) != 0) ? 1 : (-1)), (float)(((num & 4) != 0) ? 1 : (-1)))); Vector3 val8 = ((Matrix4x4)(ref val6)).MultiplyPoint3x4(val7); val3 = Vector3.Min(val3, val8); val4 = Vector3.Max(val4, val8); } } } if (val3.x <= val4.x && Finite(val3) && Finite(val4)) { stringBuilder.Append(",\"box\":[" + R(val3.x) + "," + R(val4.x) + "," + R(val3.z) + "," + R(val4.z) + "," + R(val3.y) + "," + R(val4.y) + "]"); } if (tool != null) { stringBuilder.Append(",\"tool\":").Append(Json(tool)); } return stringBuilder.Append('}').ToString(); } private static List<GameObject> AllPrefabs() { Dictionary<string, GameObject> byName = new Dictionary<string, GameObject>(); foreach (GameObject prefab in ZNetScene.instance.m_prefabs) { Add(prefab); } if (NamedPrefabs?.GetValue(ZNetScene.instance) is Dictionary<int, GameObject> dictionary) { foreach (GameObject value in dictionary.Values) { Add(value); } } if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { foreach (GameObject item in ObjectDB.instance.m_items) { Add(item); } } return byName.Values.ToList(); void Add(GameObject go) { if (Object.op_Implicit((Object)(object)go) && !byName.ContainsKey(((Object)go).name)) { byName[((Object)go).name] = go; } } } private static string PrefabEntry(GameObject go) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected I4, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected I4, but got Unknown StringBuilder stringBuilder = new StringBuilder("{"); ZNetView component = go.GetComponent<ZNetView>(); stringBuilder.Append($"\"p\":{(component.m_persistent ? 1 : 0)},\"d\":{(component.m_distant ? 1 : 0)},\"t\":{(int)component.m_type}"); if (Object.op_Implicit((Object)(object)go.GetComponent<Character>())) { stringBuilder.Append(",\"c\":1"); } ItemDrop component2 = go.GetComponent<ItemDrop>(); if (component2 != null && Object.op_Implicit((Object)(object)component2)) { stringBuilder.Append($",\"i\":1,\"it\":{(int)(component2.m_itemData?.m_shared?.m_itemType).GetValueOrDefault()}"); } Container component3 = go.GetComponent<Container>(); if (component3 != null && Object.op_Implicit((Object)(object)component3)) { stringBuilder.Append($",\"cw\":{component3.m_width},\"ch\":{component3.m_height}"); } PrivateArea component4 = go.GetComponent<PrivateArea>(); if (component4 != null && Object.op_Implicit((Object)(object)component4)) { stringBuilder.Append(",\"ward\":" + F(component4.m_radius)); } CraftingStation component5 = go.GetComponent<CraftingStation>(); if (component5 != null && Object.op_Implicit((Object)(object)component5)) { stringBuilder.Append(",\"build\":" + F(component5.m_rangeBuild)); } return stringBuilder.Append('}').ToString(); } private static Dictionary<string, string> PieceTools() { Dictionary<string, string> dictionary = new Dictionary<string, string>(); if (!Object.op_Implicit((Object)(object)ObjectDB.instance)) { return dictionary; } foreach (GameObject item in ObjectDB.instance.m_items) { ItemDrop val = (Object.op_Implicit((Object)(object)item) ? item.GetComponent<ItemDrop>() : null); PieceTable val2 = ((!Object.op_Implicit((Object)(object)val)) ? null : val.m_itemData?.m_shared?.m_buildPieces); if (!Object.op_Implicit((Object)(object)val2)) { continue; } string value2; string value = (ToolTables.TryGetValue(((Object)val2).name, out value2) ? value2 : ((Object)item).name); foreach (GameObject piece in val2.m_pieces) { if (Object.op_Implicit((Object)(object)piece) && !dictionary.ContainsKey(((Object)piece).name)) { dictionary[((Object)piece).name] = value; } } } return dictionary; } private void CheckDestroyed(List<AppliedObject> gone, List<AppliedObject> made) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) if (ZDOMan.instance == null) { return; } Dictionary<ZDOID, ZDO> dictionary = AllZdos(); HashSet<ZDOID> hashSet = new HashSet<ZDOID>(); foreach (AppliedObject item in made) { hashSet.Add(new ZDOID(item.User, item.Id)); } Dictionary<(int Prefab, int X, int Z), List<Vector3>> cells = new Dictionary<(int, int, int), List<Vector3>>(); HashSet<int> hashSet2 = new HashSet<int>(); int num = 0; ZDOID val = default(ZDOID); Vector3 val2 = default(Vector3); foreach (AppliedObject item2 in gone) { ((ZDOID)(ref val))..ctor(item2.User, item2.Id); hashSet.Add(val); if (dictionary.ContainsKey(val)) { num++; } ((Vector3)(ref val2))..ctor(item2.X, item2.Y, item2.Z); (int, int, int) key = (item2.Prefab, Mathf.FloorToInt(val2.x), Mathf.FloorToInt(val2.z)); if (!cells.TryGetValue(key, out var value)) { value = (cells[key] = new List<Vector3>()); } value.Add(val2); hashSet2.Add(item2.Prefab); } int num2 = 0; foreach (ZDO value3 in dictionary.Values) { if (!hashSet.Contains(value3.m_uid) && hashSet2.Contains(value3.GetPrefab()) && Near(value3.GetPrefab(), value3.GetPosition())) { num2++; } } ((BaseUnityPlugin)this).Logger.LogInfo((object)$"WorldEditorBridge: 1 s after the apply: {num} of {gone.Count} destroyed object(s) still exist, {num2} other object(s) of their prefab within 10 cm of their place (made again, or there all along); {dictionary.Count} object(s), {Peers()} peer(s)"); bool Near(int prefab, Vector3 p) { //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) int num3 = Mathf.FloorToInt(p.x); int num4 = Mathf.FloorToInt(p.z); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (cells.TryGetValue((prefab, num3 + i, num4 + j), out var value2)) { int num5 = value2.FindIndex(delegate(Vector3 w) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Vector3 val3 = w - p; return ((Vector3)(ref val3)).sqrMagnitude < 0.01f; }); if (num5 >= 0) { value2.RemoveAt(num5); return true; } } } } return false; } } private void Awake() { string text = Path.Combine(Paths.ConfigPath, "local.worldeditorbridge.cfg"); if (File.Exists(text) && !File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { try { File.Move(text, ((BaseUnityPlugin)this).Config.ConfigFilePath); ((BaseUnityPlugin)this).Config.Reload(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"Settings moved from local.worldeditorbridge.cfg to Tie.WorldEditorBridge.cfg"); } catch (IOException e) { Caught(e, "moving the settings from local.worldeditorbridge.cfg to Tie.WorldEditorBridge.cfg (the old file is left)", brief: false, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.cs", 158, "Awake"); } } _bind = ((BaseUnityPlugin)this).Config.Bind<string>("Http", "BindAddress", "127.0.0.1", "Address to listen on. Keep 127.0.0.1 and reach it through an SSH tunnel (ssh -L 5182:127.0.0.1:5182 user@server). Another address lets this machine's local networks and VPNs in (never the internet), and the token then travels unencrypted."); _port = ((BaseUnityPlugin)this).Config.Bind<int>("Http", "Port", 5182, "TCP port of the bridge."); _token = ((BaseUnityPlugin)this).Config.Bind<string>("Http", "Token", "", "Secret the editor must send (X-Bridge-Token header). Generated on first start when empty."); if (string.IsNullOrWhiteSpace(_token.Value)) { byte[] array = new byte[18]; using (RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create()) { randomNumberGenerator.GetBytes(array); } _token.Value = Convert.ToBase64String(array).Replace('+', 'A').Replace('/', 'B') .TrimEnd(new char[1] { '=' }); ((BaseUnityPlugin)this).Config.Save(); } EnableModQuery(); try { _listener = new HttpListener(); _listener.Prefixes.Add($"http://{_bind.Value}:{_port.Value}/"); if (_bind.Value == "127.0.0.1") { _listener.Prefixes.Add($"http://localhost:{_port.Value}/"); } _listener.Start(); _running = true; _thread = new Thread(Serve) { IsBackground = true, Name = "WorldEditorBridge" }; _thread.Start(); ((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("WorldEditorBridge {0} listening on http://{1}:{2}/ (token in BepInEx/config/{3}.cfg)", "1.127.0", _bind.Value, _port.Value, "Tie.WorldEditorBridge")); string text2 = BridgeAccess.BindWarning(_bind.Value); if (text2 != null) { ((BaseUnityPlugin)this).Logger.LogWarning((object)text2); } } catch (Exception e2) { Caught(e2, $"listening on {_bind.Value}:{_port.Value} (the bridge does not answer)", brief: false, (LogLevel)2, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.cs", 197, "Awake"); } } private void OnDestroy() { _running = false; try { _listener?.Stop(); } catch (Exception e) { Caught(e, "stopping the listener (the game is closing anyway)", brief: true, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.cs", 212, "OnDestroy"); } } private void Update() { KeepDiscsFirst(); if (_destroyChecks.Count > 0 && Time.realtimeSinceStartup >= _destroyChecks.Peek().Due) { (float Due, List<AppliedObject> Gone, List<AppliedObject> Made) tuple = _destroyChecks.Dequeue(); List<AppliedObject> item = tuple.Gone; List<AppliedObject> item2 = tuple.Made; CheckDestroyed(item, item2); } for (int i = 0; i < 4; i++) { if (!_jobs.TryDequeue(out var result)) { break; } if (Interlocked.CompareExchange(ref result.State, 1, 0) == 0) { try { result.Result = result.Work(); } catch (Exception error) { result.Error = error; } result.Done.Set(); } } } private static bool IsDisc(ZDO zdo) { if (zdo.GetPrefab() == LocationProxyPrefab) { return zdo.GetInt(ZDOVars.s_location, 0) == DiscLocation; } return false; } private void NoteDiscs(List<AppliedObject> made) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) foreach (AppliedObject item in made) { if (item.Prefab == LocationProxyPrefab) { ZDO zDO = ZDOMan.instance.GetZDO(new ZDOID(item.User, item.Id)); if (zDO != null && IsDisc(zDO)) { _discs.Add(zDO.m_uid); } } } } private void KeepDiscsFirst() { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Invalid comparison between Unknown and I4 //IL_0113: 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) if (Time.realtimeSinceStartup < _discsDue || (Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null || ZNet.m_loadError) { return; } _discsDue = Time.realtimeSinceStartup + 5f; if (_discsOf != ZDOMan.instance) { Dictionary<ZDOID, ZDO> dictionary = AllZdos(); if (dictionary.Count == 0) { return; } _discs.Clear(); foreach (ZDO value in dictionary.Values) { if (IsDisc(value)) { _discs.Add(value.m_uid); } } _discsOf = ZDOMan.instance; ((BaseUnityPlugin)this).Logger.LogInfo((object)$"WorldEditorBridge: {_discs.Count} ground disc(s) in the world, kept first in line"); } int num = 0; List<ZDOID> list = new List<ZDOID>(); foreach (ZDOID disc in _discs) { ZDO zDO = ZDOMan.instance.GetZDO(disc); if (zDO == null) { list.Add(disc); } else if ((int)zDO.Type != 3) { zDO.SetType((ObjectType)3); num++; } } _discs.ExceptWith(list); if (num > 0) { ((BaseUnityPlugin)this).Logger.LogInfo((object)$"WorldEditorBridge: {num} ground disc(s) put back first in line"); } } private static byte[] Plugins() { StringBuilder stringBuilder = new StringBuilder("{\"plugins\":["); bool flag = true; foreach (PluginInfo value in Chainloader.PluginInfos.Values) { if (!flag) { stringBuilder.Append(','); } flag = false; stringBuilder.Append("{\"guid\":" + Json(value.Metadata.GUID) + ",\"name\":" + Json(value.Metadata.Name) + ",\"version\":" + Json(value.Metadata.Version.ToString()) + "}"); } return Encoding.UTF8.GetBytes(stringBuilder.Append("]}").ToString()); } private static void ServeConfig(HttpListenerContext ctx) { HttpListenerResponse response = ctx.Response; string root = Path.GetFullPath(Paths.ConfigPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); string[] array = ConfigPartsOf(ctx.Request.QueryString["path"] ?? ""); string text; bool flag; if (array != null) { (text, flag) = Resolve(root, array); } else { text = null; flag = true; } if (flag) { Reply(response, 400, "text/plain", Encoding.UTF8.GetBytes("the path must name a file or folder inside BepInEx/config")); } else if (text != null && Directory.Exists(text)) { ServeFolder(response, root, array, text); } else if (text != null && File.Exists(text)) { ServeFile(response, root, array, text); } else { Reply(response, 404, "text/plain", Encoding.UTF8.GetBytes("no such file or folder under BepInEx/config")); } } private static (string Full, bool Linked) Resolve(string root, string[] parts) { StringComparison names = ((Path.DirectorySeparatorChar == '\\') ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); string text = root; foreach (string part in parts) { string text2 = (Directory.Exists(text) ? Directory.EnumerateFileSystemEntries(text).FirstOrDefault((string e) => string.Equals(Path.GetFileName(e), part, names)) : null); if (text2 == null) { return (Full: null, Linked: false); } if ((File.GetAttributes(text2) & FileAttributes.ReparsePoint) != FileAttributes.None) { return (Full: null, Linked: true); } text = text2; } return (Full: text, Linked: false); } private static void ServeFolder(HttpListenerResponse res, string root, string[] parts, string full) { string s = FolderJson(full); if (Linked(root, parts)) { Reply(res, 400, "text/plain", Encoding.UTF8.GetBytes("the path must name a file or folder inside BepInEx/config")); } else { Reply(res, 200, "application/json", Encoding.UTF8.GetBytes(s)); } } private static void ServeFile(HttpListenerResponse res, string root, string[] parts, string full) { using FileStream fileStream = new FileStream(full, FileMode.Open, FileAccess.Read, FileShare.Read); if (Linked(root, parts)) { Reply(res, 400, "text/plain", Encoding.UTF8.GetBytes("the path must name a file or folder inside BepInEx/config")); return; } if (fileStream.Length > 4194304) { Reply(res, 413, "text/plain", Encoding.UTF8.GetBytes("the file is larger than 4 MB")); return; } using MemoryStream memoryStream = new MemoryStream(); fileStream.CopyTo(memoryStream); Reply(res, 200, "application/octet-stream", memoryStream.ToArray()); } private static string[] ConfigPartsOf(string wanted) { if (wanted.Length == 0) { return Array.Empty<string>(); } char c = wanted[0]; bool flag = ((c == '/' || c == '\\') ? true : false); if (flag || Path.IsPathRooted(wanted)) { return null; } string[] array = wanted.Replace('\\', '/').TrimEnd(new char[1] { '/' }).Split(new char[1] { '/' }); if (!Array.Exists(array, (string p) => ((p != null && p.Length == 0) || p == "." || p == "..") ? true : false)) { return array; } return null; } private static bool Linked(string root, string[] parts) { string text = root; foreach (string path in parts) { text = Path.Combine(text, path); if (!File.Exists(text) && !Directory.Exists(text)) { return false; } if ((File.GetAttributes(text) & FileAttributes.ReparsePoint) != FileAttributes.None) { return true; } } return false; } private static string FolderJson(string folder) { StringBuilder stringBuilder = new StringBuilder("{\"folder\":true,\"entries\":["); bool flag = true; foreach (FileSystemInfo item in new DirectoryInfo(folder).EnumerateFileSystemInfos()) { if (!flag) { stringBuilder.Append(','); } flag = false; bool flag2 = (item.Attributes & FileAttributes.Directory) != 0; long num = (flag2 ? 0 : ((FileInfo)item).Length); stringBuilder.Append("{\"name\":" + Json(item.Name) + ",\"folder\":" + (flag2 ? "true" : "false") + ",\"size\":" + num.ToString(CultureInfo.InvariantCulture) + ",\"modified\":" + Json(item.LastWriteTimeUtc.ToString("o", CultureInfo.InvariantCulture)) + "}"); } return stringBuilder.Append("]}").ToString(); } private static byte[] WorldMeta() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) World world = ZNet.World; if (world == null) { return null; } string text = world.GetSaveFWLPath(); if (!FileHelpers.Exists(text, world.m_fileSource)) { text = ((MetaPath == null) ? null : ((string)MetaPath.Invoke(world, null))); if (text == null || !FileHelpers.Exists(text, world.m_fileSource)) { return null; } } FileReader val = new FileReader(text, world.m_fileSource, (FileHelperType)0); using (val.m_binary) { using MemoryStream memoryStream = new MemoryStream(); val.m_binary.BaseStream.CopyTo(memoryStream); return memoryStream.ToArray(); } } private void ReplyBytesOr404(HttpListenerResponse res, Func<byte[]> work) { byte[] array = OnMainThread(work); if (array == null) { Reply(res, 404, "text/plain", Encoding.UTF8.GetBytes("the game has no world file")); } else { Reply(res, 200, "application/octet-stream", array); } } private void Serve() { while (_running) { HttpListenerContext ctx; try { ctx = _listener.GetContext(); } catch (Exception e) { if (!_running) { ((BaseUnityPlugin)this).Logger.LogInfo((object)"WorldEditorBridge: stopped listening."); break; } Caught(e, "waiting for the next request (waited for again)", brief: true, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.Http.cs", 30, "Serve"); continue; } ThreadPool.QueueUserWorkItem(delegate { Handle(ctx); }); } } private void Handle(HttpListenerContext ctx) { HttpListenerResponse response = ctx.Response; try { (int, string)? tuple = BridgeAccess.Refusal(ctx.Request.RemoteEndPoint?.Address, ctx.Request.Headers, _token.Value); if (tuple.HasValue) { (int, string) valueOrDefault = tuple.GetValueOrDefault(); Reply(response, valueOrDefault.Item1, "text/plain", Encoding.UTF8.GetBytes(valueOrDefault.Item2)); return; } if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null || (Object)(object)ZoneSystem.instance == (Object)null) { Reply(response, 503, "text/plain", Encoding.UTF8.GetBytes("no world loaded yet")); return; } if (!ZNet.instance.IsServer()) { Reply(response, 409, "text/plain", Encoding.UTF8.GetBytes("this game is connected to a server: install WorldEditorBridge on that server, or host the world yourself")); return; } string absolutePath = ctx.Request.Url.AbsolutePath; if (absolutePath.StartsWith("/mods/", StringComparison.Ordinal)) { if (RequirePost(ctx)) { byte[] array = ((ctx.Request.ContentLength64 > 16777216) ? null : ReadAtMost(ctx.Request.InputStream, 16777216)); if (array == null) { Reply(response, 413, "text/plain", Encoding.UTF8.GetBytes("the body is too large")); } else { CallMod(response, absolutePath, array); } } } else { Route(ctx, absolutePath); } } catch (Exception ex) { string text = ctx.Request.Url.AbsolutePath.Replace("\r", "").Replace("\n", ""); Caught(ex, "answering the request " + text, brief: false, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.Http.cs", 87, "Handle"); try { Reply(response, 500, "text/plain", Encoding.UTF8.GetBytes(ex.Message)); } catch (Exception e) { Caught(e, "sending the error answer to the request " + text + " (its client has gone)", brief: true, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.Http.cs", 94, "Handle"); } } } private void Caught(Exception e, string doing, bool brief = false, LogLevel level = (LogLevel)4, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0, [CallerMemberName] string member = "") { //IL_0114: Unknown result type (might be due to invalid IL or missing references) string text = file.Substring(file.LastIndexOfAny(new char[2] { '/', '\\' }) + 1); StringBuilder stringBuilder = new StringBuilder(string.Format("WorldEditorBridge: caught at {0}:{1} ({2}) while {3}: {4}: {5}", text, line, member, doing, e.GetType().FullName, e.Message.Replace("\r", " ").Replace("\n", " "))); if (!brief) { stringBuilder.AppendLine().Append(e.StackTrace); for (Exception innerException = e.InnerException; innerException != null; innerException = innerException.InnerException) { stringBuilder.AppendLine().Append(" ---> ").Append(innerException.GetType().FullName) .Append(": ") .Append(innerException.Message) .AppendLine() .Append(innerException.StackTrace); } } string text2 = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile).TrimEnd('/', '\\'); ((BaseUnityPlugin)this).Logger.Log(level, (object)((text2.Length > 1) ? stringBuilder.Replace(text2, "~").ToString() : stringBuilder.ToString())); } private static byte[] ReadAll(Stream s) { using MemoryStream memoryStream = new MemoryStream(); s.CopyTo(memoryStream); return memoryStream.ToArray(); } private static byte[] ReadAtMost(Stream s, int limit) { using MemoryStream memoryStream = new MemoryStream(); byte[] array = new byte[65536]; int num; while ((num = s.Read(array, 0, array.Length)) > 0) { if (memoryStream.Length + num > limit) { return null; } memoryStream.Write(array, 0, num); } return memoryStream.ToArray(); } private static void Reply(HttpListenerResponse res, int code, string type, byte[] body) { res.StatusCode = code; res.ContentType = type; res.Headers["X-Content-Type-Options"] = "nosniff"; res.ContentLength64 = body.Length; res.OutputStream.Write(body, 0, body.Length); res.OutputStream.Close(); } private static Dictionary<ZDOID, ZDO> AllZdos() { return (Dictionary<ZDOID, ZDO>)ObjectsById.GetValue(ZDOMan.instance); } private static byte[] Gzip(byte[] raw) { using MemoryStream memoryStream = new MemoryStream(); using (GZipStream gZipStream = new GZipStream(memoryStream, CompressionLevel.Fastest, leaveOpen: true)) { gZipStream.Write(raw, 0, raw.Length); } return memoryStream.ToArray(); } private static bool RequirePost(HttpListenerContext ctx) { if (ctx.Request.HttpMethod == "POST") { return true; } Reply(ctx.Response, 405, "text/plain", Encoding.UTF8.GetBytes("POST only")); return false; } private void ReplyJson(HttpListenerResponse res, Func<byte[]> work, int timeoutMs = 30000) { Reply(res, 200, "application/json", OnMainThread(work, timeoutMs)); } private void PostJson(HttpListenerContext ctx, Func<byte[], byte[]> work, int timeoutMs = 30000) { if (RequirePost(ctx)) { byte[] body = ReadAll(ctx.Request.InputStream); ReplyJson(ctx.Response, () => work(body), timeoutMs); } } private void ReplyGzip(HttpListenerResponse res, Func<byte[]> work, int timeoutMs = 30000) { byte[] raw = OnMainThread(work, timeoutMs); Reply(res, 200, "application/octet-stream", Gzip(raw)); } private void PostGzip(HttpListenerContext ctx, Func<byte[], byte[]> work) { if (RequirePost(ctx)) { byte[] body = ReadAll(ctx.Request.InputStream); ReplyGzip(ctx.Response, () => work(body)); } } private static int LinkHash(ZDOID source) { return (int)(((uint)(int)(((ZDOID)(ref source)).UserID * 486187739) ^ (((ZDOID)(ref source)).ID * 16777619)) | 1); } private static Dictionary<ZDOID, (ConnectionType Type, int Hash)> SnapshotLinks() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: 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_00f8: Unknown result type (might be due to invalid IL or missing references) Dictionary<ZDOID, (ConnectionType, int)> dictionary = new Dictionary<ZDOID, (ConnectionType, int)>(); List<(ZDOID, ConnectionType, int)> list = new List<(ZDOID, ConnectionType, int)>(); foreach (ZDOID allConnectionZDOID in ZDOExtraData.GetAllConnectionZDOIDs()) { ZDOConnection connection = ZDOExtraData.GetConnection(allConnectionZDOID); if (connection != null && (int)connection.m_type != 0) { int num = LinkHash(allConnectionZDOID); Links[num] = (connection.m_type, allConnectionZDOID, connection.m_target); dictionary[allConnectionZDOID] = (connection.m_type, num); if (connection.m_target != ZDOID.None) { list.Add((connection.m_target, (ConnectionType)(connection.m_type | 0x10), num)); } } } foreach (var (key, item, item2) in list) { if (!dictionary.ContainsKey(key)) { dictionary[key] = (item, item2); } } return dictionary; } private static void Relink(ZDO made, ConnectionType type, int hash) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 //IL_0024: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) if (!Links.TryGetValue(hash, out (ConnectionType, ZDOID, ZDOID) value)) { return; } bool flag = (type & 0x10) == 0; ZDOID val = (flag ? value.Item2 : value.Item3); if (ZDOMan.instance.GetZDO(val) != null) { return; } if (flag) { if (value.Item3 == ZDOID.None || ZDOMan.instance.GetZDO(value.Item3) != null) { made.SetConnection(value.Item1, value.Item3); } Links[hash] = (value.Item1, made.m_uid, value.Item3); } else { Links[hash] = (value.Item1, value.Item2, made.m_uid); } foreach (ZDOID allConnectionZDOID in ZDOExtraData.GetAllConnectionZDOIDs()) { ZDOConnection connection = ZDOExtraData.GetConnection(allConnectionZDOID); if (connection != null && connection.m_target == val) { ZDO zDO = ZDOMan.instance.GetZDO(allConnectionZDOID); if (zDO != null) { zDO.UpdateConnection(connection.m_type, made.m_uid); } } } } private static HashSet<GameObject> SkippedLooks(GameObject go) { HashSet<GameObject> hashSet = new HashSet<GameObject>(); WearNTear[] componentsInChildren = go.GetComponentsInChildren<WearNTear>(true); foreach (WearNTear val in componentsInChildren) { GameObject[] array = (GameObject[])(object)new GameObject[2] { val.m_worn, val.m_broken }; foreach (GameObject val2 in array) { if (Object.op_Implicit((Object)(object)val2) && (Object)(object)val2 != (Object)(object)val.m_new) { hashSet.Add(val2); } } } return hashSet; } private static HashSet<Renderer> LowerLodRenderers(GameObject go) { HashSet<Renderer> hashSet = new HashSet<Renderer>(); LODGroup[] componentsInChildren = go.GetComponentsInChildren<LODGroup>(true); for (int i = 0; i < componentsInChildren.Length; i++) { LOD[] lODs = componentsInChildren[i].GetLODs(); for (int j = 1; j < lODs.Length; j++) { hashSet.UnionWith(lODs[j].renderers.Where((Renderer r) => Object.op_Implicit((Object)(object)r))); } if (lODs.Length != 0) { hashSet.ExceptWith(lODs[0].renderers.Where((Renderer r) => Object.op_Implicit((Object)(object)r))); } } return hashSet; } private static bool Skipped(Transform t, Transform root, HashSet<GameObject> skip) { while (Object.op_Implicit((Object)(object)t) && (Object)(object)t != (Object)(object)root) { if (skip.Contains(((Component)t).gameObject)) { return true; } t = t.parent; } return false; } private static Mesh MeshOf(Renderer r) { SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((r is SkinnedMeshRenderer) ? r : null); if (val == null) { if (r is MeshRenderer) { MeshFilter component = ((Component)r).GetComponent<MeshFilter>(); if (component != null && Object.op_Implicit((Object)(object)component)) { return component.sharedMesh; } } return null; } return val.sharedMesh; } private static void AppendMaterial(StringBuilder part, Material mat) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)mat)) { return; } part.Append(",\"mat\":").Append(Json(((Object)mat).name)); if (mat.HasProperty("_MainTex")) { Texture texture = mat.GetTexture("_MainTex"); if (texture != null && Object.op_Implicit((Object)(object)texture)) { part.Append(",\"tex\":").Append(Json(((Object)texture).name)); } } if (mat.HasProperty("_Color")) { Color color = mat.GetColor("_Color"); if (Finite(color.r) && Finite(color.g) && Finite(color.b) && Finite(color.a)) { part.Append(",\"col\":[" + R6(color.r) + "," + R6(color.g) + "," + R6(color.b) + "," + R6(color.a) + "]"); } } } private static byte[] Models(byte[] body) { Dictionary<string, GameObject> dictionary = new Dictionary<string, GameObject>(); foreach (GameObject item in AllPrefabs()) { dictionary[((Object)item).name] = item; } StringBuilder stringBuilder = new StringBuilder("{"); foreach (string item2 in (from n in Encoding.UTF8.GetString(body).Split(new char[1] { '\n' }) select n.Trim() into n where n.Length > 0 select n).Distinct()) { if (dictionary.TryGetValue(item2, out var value)) { if (stringBuilder.Length > 1) { stringBuilder.Append(','); } stringBuilder.Append(Json(item2)).Append(':').Append(ModelOf(value)); } } return Encoding.UTF8.GetBytes(stringBuilder.Append('}').ToString()); } private static string ModelOf(GameObject go) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_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_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) Transform transform = go.transform; HashSet<GameObject> skip = SkippedLooks(go); HashSet<Renderer> hashSet = LowerLodRenderers(go); Matrix4x4 worldToLocalMatrix = transform.worldToLocalMatrix; List<string> list = new List<string>(); Renderer[] componentsInChildren = go.GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { Mesh val2 = MeshOf(val); if (!Object.op_Implicit((Object)(object)val2) || !val.enabled || hashSet.Contains(val) || !ActiveUnder(((Component)val).transform, transform) || Skipped(((Component)val).transform, transform, skip)) { continue; } Matrix4x4 m = worldToLocalMatrix * ((Component)val).transform.localToWorldMatrix; Bounds bounds = val2.bounds; if (Enumerable.Range(0, 16).All((int num2) => Finite(((Matrix4x4)(ref m))[num2 / 4, num2 % 4])) && Finite(((Bounds)(ref bounds)).center) && Finite(((Bounds)(ref bounds)).extents)) { string text = string.Join(",", from num2 in Enumerable.Range(0, 16) select R6(((Matrix4x4)(ref m))[num2 / 4, num2 % 4])); Material[] sharedMaterials = val.sharedMaterials; for (int num = 0; num < val2.subMeshCount && num < sharedMaterials.Length; num++) { StringBuilder stringBuilder = new StringBuilder($"{{\"mesh\":{Json(((Object)val2).name)},\"v\":{val2.vertexCount},\"b\":[{R6(((Bounds)(ref bounds)).center.x)},{R6(((Bounds)(ref bounds)).center.y)},{R6(((Bounds)(ref bounds)).center.z)},{R6(((Bounds)(ref bounds)).extents.x)},{R6(((Bounds)(ref bounds)).extents.y)},{R6(((Bounds)(ref bounds)).extents.z)}],\"sub\":{num}"); AppendMaterial(stringBuilder, sharedMaterials[num]); list.Add(stringBuilder.Append(",\"m\":[" + text + "]}").ToString()); } } } Vector3 localScale = transform.localScale; return "{\"s\":[" + R6(localScale.x) + "," + R6(localScale.y) + "," + R6(localScale.z) + "],\"p\":[" + string.Join(",", list) + "]}"; } private static string R6(float v) { return Math.Round(v, 6).ToString("R", CultureInfo.InvariantCulture); } private static string Mods() { StringBuilder stringBuilder = new StringBuilder("{\"api\":"); stringBuilder.Append(1).Append(",\"mods\":["); bool flag = true; foreach (string modId in BridgeApi.ModIds) { if (!flag) { stringBuilder.Append(','); } flag = false; stringBuilder.Append(Json(modId)); } return stringBuilder.Append("]}").ToString(); } private void CallMod(HttpListenerResponse res, string path, byte[] body) { string[] array = path.Split(new char[1] { '/' }); if (array.Length != 4 || !BridgeApi.IsValidId(array[2]) || !BridgeApi.IsValidId(array[3])) { Reply(res, 404, "text/plain", Encoding.UTF8.GetBytes("a mod's route is /mods/<mod id>/<route name>")); return; } string text = array[2]; string name = array[3]; IBridgeRoutes routes = BridgeApi.RoutesOf(text); if (routes == null) { Reply(res, 404, "text/plain", Encoding.UTF8.GetBytes("no mod of that id is registered with the bridge (GET /mods lists them)")); return; } byte[] array2 = OnMainThread(() => routes.Handle(name, body)); if (array2 == null) { Reply(res, 404, "text/plain", Encoding.UTF8.GetBytes("the mod has no route of that name")); } else { Reply(res, 200, "application/octet-stream", array2); } } private byte[] Applied((byte[] Json, AppliedChanges Changes) result) { foreach (KeyValuePair<string, IBridgeListener> listener in BridgeApi.Listeners) { try { listener.Value.OnApplied(result.Changes); } catch (Exception e) { Caught(e, "telling the mod " + listener.Key + " what the editor applied", brief: false, (LogLevel)4, "/root/project/editor/plugin/WorldEditorBridge/WorldEditorBridgePlugin.Mods.cs", 77, "Applied"); } } return result.Json; } private static AppliedObject Applied(ZDO zdo) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown Vector3 position = zdo.GetPosition(); return new AppliedObject(((ZDOID)(ref zdo.m_uid)).UserID, ((ZDOID)(ref zdo.m_uid)).ID, zdo.GetPrefab(), position.x, position.y, position.z); } private static (string Json, List<AppliedMove> Moved, int InPlace, int Missing) Move(List<ObjectMove> moves, long session, List<AppliedObject> gone, List<AppliedObject> made) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Expected O, but got Unknown ZDO[] array = (ZDO[])(object)new ZDO[moves.Count]; List<int> list = new List<int>(); for (int i = 0; i < moves.Count; i++) { array[i] = ZDOMan.instance.GetZDO(moves[i].Id); if (array[i] == null) { list.Add(i); } } if (list.Count > 0) { ZDO[] array2 = FindAtPlace(list.Select((int index) => (Prefab: moves[index].Prefab, From: moves[index].From)).ToList()); for (int num = 0; num < list.Count; num++) { array[list[num]] = array2[num]; } } StringBuilder stringBuilder = new StringBuilder(); List<AppliedMove> list2 = new List<AppliedMove>(); int num2 = 0; for (int num3 = 0; num3 < moves.Count; num3++) { ZDO val = array[num3]; ObjectMove objectMove = moves[num3]; Vector3 to = objectMove.To; int num4; if (val != null) { Vector3 val2 = val.GetPosition() - to; num4 = ((((Vector3)(ref val2)).sqrMagnitude < 1E-06f || !LoadedAtBoth(val.GetPosition(), to, val.Distant)) ? 1 : 0); } else { num4 = 0; } bool flag = (byte)num4 != 0; ZDO val4; if (flag) { AppliedObject val3 = Applied(val); val.SetOwner(session); val.SetPosition(to); val.SetRotation(Quaternion.Euler(objectMove.Rotation)); if (objectMove.Data) { objectMove.Fallback.PutOn(val); } Announce(val); ZDOMan.instance.ForceSendZDO(val.m_uid); list2.Add(new AppliedMove(val3, Applied(val))); val4 = val; } else { val4 = objectMove.Fallback.Make(); made.Add(Applied(val4)); if (val != null) { gone.Add(Applied(val)); val.SetOwner(session); ZDOMan.instance.DestroyZDO(val); } else { num2++; } } if (num3 > 0) { stringBuilder.Append(','); } stringBuilder.Append("{\"id\":\"").Append(((ZDOID)(ref val4.m_uid)).UserID.ToString(CultureInfo.InvariantCulture)).Append(':') .Append(((ZDOID)(ref val4.m_uid)).ID.ToString(CultureInfo.InvariantCulture)) .Append("\",\"inPlace\":") .Append(flag ? "true" : "false") .Append('}'); } return (Json: stringBuilder.ToString(), Moved: list2, InPlace: list2.Count, Missing: num2); } private static bool LoadedAtBoth(Vector3 from, Vector3 to, bool distant) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) SimulationDistance syncedSimulationDistance = ZNet.instance.GetSyncedSimulationDistance(); int area = (distant ? ((SimulationDistance)(ref syncedSimulationDistance)).TotalSimulationDistance : ((SimulationDistance)(ref syncedSimulationDistance)).NearSimulationDistance); Vector2s a = ZoneSystem.GetZone(from); Vector2s b = ZoneSystem.GetZone(to); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (Both(peer.GetRefPos())) { return true; } } if (!ZNet.instance.IsDedicated()) { return Both(ZNet.instance.GetReferencePosition()); } return false; bool Both(Vector3 at) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) Vector2s zone = ZoneSystem.GetZone(at); if (Near(a, zone)) { return Near(b, zone); } return false; } bool Near(Vector2s zone, Vector2s at) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (Math.Abs(zone.x - at.x) <= area) { return Math.Abs(zone.y - at.y) <= area; } return false; } } private (byte[] Json, AppliedChanges Changes) ApplyObjects(byte[] body) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_010f: 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_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d6: Expected O, but got Unknown ZPackage val = new ZPackage(body); long sessionID = ZDOMan.GetSessionID(); Dictionary<ZDOID, ZDO> dictionary = AllZdos(); int count = dictionary.Count; int num = val.ReadInt(); ZDOID[] array = (ZDOID[])(object)new ZDOID[num]; for (int i = 0; i < num; i++) { array[i] = new ZDOID(val.ReadLong(), val.ReadUInt()); } int num2 = val.ReadInt(); SavedObject[] array2 = new SavedObject[num2]; for (int j = 0; j < num2; j++) { array2[j] = ReadSaveFormat(new ZPackage(val.ReadByteArray())); } (int Prefab, Vector3 Position)[] where = null; if (val.GetPos() < val.Size()) { where = new(int, Vector3)[num]; for (int k = 0; k < num; k++) { where[k] = (Prefab: val.ReadInt(), Position: val.ReadVector3()); } } List<ObjectMove> list = ReadMoves(val); int num3 = 0; int num4 = 0; List<int> list2 = new List<int>(); List<AppliedObject> list3 = new List<AppliedObject>(); for (int l = 0; l < num; l++) { ZDO zDO = ZDOMan.instance.GetZDO(array[l]); if (zDO == null) { list2.Add(l); continue; } list3.Add(Applied(zDO)); zDO.SetOwner(sessionID); ZDOMan.instance.DestroyZDO(zDO); num3++; } if (list2.Count > 0 && where != null) { num4 = DestroyAtPlace(list2.Select((int num8) => where[num8]).ToList(), sessionID, list3); } int num5 = list2.Count - num4; List<AppliedObject> list4 = new List<AppliedObject>(); (string Json, List<AppliedMove> Moved, int InPlace, int Missing) tuple = Move(list, sessionID, list3, list4); string item = tuple.Json; List<AppliedMove> item2 = tuple.Moved; int item3 = tuple.InPlace; int item4 = tuple.Missing; int num6 = list.Count((ObjectMove m) => m.Data); num5 += item4; StringBuilder stringBuilder = new StringBuilder(); for (int num7 = 0; num7 < num2; num7++) { ZDO val2 = array2[num7].Make(); list4.Add(Applied(val2)); if (num7 > 0) { stringBuilder.Append(','); } stringBuilder.Append('"').Append(((ZDOID)(ref val2.m_uid)).UserID.ToString(CultureInfo.InvariantCulture)).Append(':') .Append(((ZDOID)(ref val2.m_uid)).ID.ToString(CultureInfo.InvariantCulture)) .Append('"'); } NoteDiscs(list4); string text = ((list.Count > 0) ? $", moved {item3} in place and {list.Count - item3} by making it again (a player had both places loaded, or it was gone; {num6} with new data)" : ""); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"WorldEditorBridge: destroyed {num3 + num4} object(s) ({num4} found again at their place under a new id, {num5} already gone), created {num2}{text}; {count} -> {dictionary.Count} object(s) known, {Peers()} peer(s)"); if (list3.Count > 0) { _destroyChecks.Enqueue((Time.realtimeSinceStartup + 1f, list3, list4)); } return (Json: Encoding.UTF8.GetBytes($"{{\"destroyed\":{num3 + num4},\"refound\":{num4},\"missing\":{num5},\"created\":[{stringBuilder}],\"moves\":[{item}]}}"), Changes: new AppliedChanges((IReadOnlyList<AppliedObject>)list4, (IReadOnlyList<AppliedObject>)list3, (IReadOnlyList<Zone>)Array.Empty<Zone>(), (IReadOnlyList<Zone>)Array.Empty<Zone>(), (IReadOnlyList<AppliedMove>)item2)); } private static List<ObjectMove> ReadMoves(ZPackage pkg) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown List<ObjectMove> list = new List<ObjectMove>(); if (pkg.GetPos() >= pkg.Size()) { return list; } int num = pkg.ReadInt(); for (int i = 0; i < num; i++) { list.Add(new ObjectMove(new ZDOID(pkg.ReadLong(), pkg.ReadUInt()), pkg.ReadInt(), pkg.ReadVector3(), pkg.ReadVector3(), pkg.ReadVector3(), ReadSaveFormat(new ZPackage(pkg.ReadByteArray())))); } int num2 = ((pkg.GetPos() < pkg.Size()) ? pkg.ReadInt() : 0); for (int j = 0; j < num2; j++) { bool data = pkg.ReadBool(); if (j < list.Count) { list[j].Data = data; } } return list; } private static ZDO[] FindAtPlace(List<(int Prefab, Vector3 Position)> wanted) { //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) ZDO[] array = (ZDO[])(object)new ZDO[wanted.Count]; Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>(); for (int i = 0; i < wanted.Count; i++) { if (!dictionary.TryGetValue(wanted[i].Prefab, out var value)) { value = (dictionary[wanted[i].Prefab] = new List<int>()); } value.Add(i); } foreach (ZDO value3 in AllZdos().Values) { if (dictionary.TryGetValue(value3.GetPrefab(), out var value2) && value2.Count != 0) { Vector3 p = value3.GetPosition(); int num = value2.FindIndex(delegate(int index) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) Vector3 val = wanted[index].Position - p; return ((Vector3)(ref val)).sqrMagnitude < 0.01f; }); if (num >= 0) { array[value2[num]] = value3; value2.RemoveAt(num); } } } return array; } private static int Peers() { ZNet instance = ZNet.instance; if (instance == null) { return 0; } return instance.GetPeers().Count; } private static int DestroyAtPlace(List<(int Prefab, Vector3 Position)> wanted, long session, List<AppliedObject> gone) { //IL_001d: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) Dictionary<int, List<Vector3>> dictionary = new Dictionary<int, List<Vector3>>(); foreach (var (key, item) in wanted) { if (!dictionary.TryGetValue(key, out var value)) { value = (dictionary[key] = new List<Vector3>()); } value.Add(item); } Dictionary<ZDOID, ZDO> dictionary2 = AllZdos(); int num = 0; foreach (ZDO item2 in new List<ZDO>(dictionary2.Values)) { if (dictionary.TryGetValue(item2.GetPrefab(), out var value2) && value2.Count != 0) { Vector3 p = item2.GetPosition(); int num2 = value2.FindIndex(delegate(Vector3 w) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = w - p; return ((Vector3)(ref val)).sqrMagnitude < 0.01f; }); if (num2 >= 0) { value2.RemoveAt(num2); gone.Add(Applied(item2)); item2.SetOwner(session); ZDOMan.instance.DestroyZDO(item2); num++; } } } return num; } private static SavedObject ReadSaveFormat(ZPackage p) { //IL_0075: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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) SavedObject o = new SavedObject { Flags = p.ReadUShort() }; if ((o.Flags & 0x2000) != 0) { Vector2s val = p.ReadVector2s(); o.Position = new Vector3((float)val.x, 0f, (float)val.y); } else { o.Position = p.ReadVector3(); } o.Prefab = p.ReadInt(); o.Euler = (((o.Flags & 0x1000) != 0) ? p.ReadSmallRotation() : Vector3.zero); if ((o.Flags & 0xFF) == 0) { return o; } if ((o.Flags & 1) != 0) { o.LinkType = (ConnectionType)p.ReadByte(); o.LinkHash = p.ReadInt(); } Each<float>(2, o.Floats, p.ReadSingle); Each<Vector3>(4, o.Vec3s, p.ReadVector3); Each<Quaternion>(8, o.Quats, p.ReadQuaternion); Each<int>(16, o.Ints, p.ReadInt); Each<long>(32, o.Longs, p.ReadLong); Each<string>(64, o.Strings, p.ReadString); Each<byte[]>(128, o.Bytes, p.ReadByteArray); return o; void Each<T>(int flag, List<KeyValuePair<int, T>> into, Func<T> read) { if ((o.Flags & flag) != 0) { int num = p.ReadNumItems(); for (int i = 0; i < num; i++) { int key = p.ReadInt(); into.Add(new KeyValuePair<int, T>(key, read())); } } } } private (byte[] Json, AppliedChanges Changes) ResetZones(byte[] body) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Expected O, but got Unknown ZPackage val = new ZPackage(body); int num = val.ReadInt(); Dictionary<Vector2s, (bool, bool)> dictionary = new Dictionary<Vector2s, (bool, bool)>(); Vector2s key = default(Vector2s); for (int i = 0; i < num; i++) { ((Vector2s)(ref key))..ctor((short)val.ReadInt(), (short)val.ReadInt()); dictionary[key] = (val.ReadBool(), val.ReadBool()); } HashSet<int> hashSet = new HashSet<int>(); if (val.GetPos() < val.Size()) { int num2 = val.ReadInt(); for (int j = 0; j < num2; j++) { hashSet.Add(val.ReadInt()); } } Dictionary<ZDOID, ZDO> dictionary2 = AllZdos(); long sessionID = ZDOMan.GetSessionID(); int num3 = 0; foreach (ZDO item in new List<ZDO>(dictionary2.Values)) { if (item.Persistent && dictionary.TryGetValue(ZoneSystem.GetZone(item.GetPosition()), out var value)) { int prefab = item.GetPrefab(); bool flag = prefab == TerrainCompilerPrefab; if (prefab != TombstonePrefab && (!flag || value.Item2) && (flag || !value.Item1 || (item.GetLong(ZDOVars.s_creator, 0L) == 0L && !hashSet.Contains(prefab)))) { item.SetOwner(sessionID); ZDOMan.instance.DestroyZDO(item); num3++; } } } ZoneSystem instance = ZoneSystem.instance; HashSet<Vector2s> hashSet2 = (HashSet<Vector2s>)GeneratedZones.GetValue(instance); int num4 = 0; foreach (Vector2s key2 in dictionary.Keys) { hashSet2.Remove(key2); if (instance.m_locationInstances.TryGetValue(key2, out var value2) && value2.m_placed) { value2.m_placed = false; instance.m_locationInstances[key2] = value2; num4++; } } ((BaseUnityPlugin)this).Logger.LogInfo((object)$"WorldEditorBridge: reset {dictionary.Count} zone(s): {num3} object(s) removed, {num4} location(s) to place again"); byte[] bytes = Encoding.UTF8.GetBytes($"{{\"zones\":{dictionary.Count},\"destroyed\":{num3},\"locations\":{num4}}}"); AppliedObject[] array = Array.Empty<AppliedObject>(); AppliedObject[] array2 = Array.Empty<AppliedObject>(); Zone[] array3 = Array.Empty<Zone>(); List<Zone> list = new List<Zone>(); list.AddRange(((IEnumerable<Vector2s>)dictionary.Keys).Select((Func<Vector2s, Zone>)((Vector2s z) => new Zone((int)z.x, (int)z.y)))); return (Json: bytes, Changes: new AppliedChanges((IReadOnlyList<AppliedObject>)array, (IReadOnlyList<AppliedObject>)array2, (IReadOnlyList<Zone>)array3, (IReadOnlyList<Zone>)new <>z__ReadOnlyList<Zone>(list))); } private byte[] OnMainThread(Func<byte[]> work, int timeoutMs = 30000) { Job job = new Job { Work = work }; _jobs.Enqueue(job); if (!job.Done.Wait(timeoutMs)) { if (Interlocked.CompareExchange(ref job.State, 2, 0) == 0) { throw new TimeoutException("the game did not answer in time"); } job.Done.Wait(); } if (job.Error != null) { ExceptionDispatchInfo.Capture(job.Error).Throw(); } return job.Result; } private void Route(HttpListenerContext ctx, string path) { HttpListenerResponse response = ctx.Response; switch (path) { case "/mods": Reply(response, 200, "application/json", Encoding.UTF8.GetBytes(Mods())); break; case "/plugins": Reply(response, 200, "application/json", Plugins()); break; case "/config": ServeConfig(ctx); break; case "/world/meta": ReplyBytesOr404(response, WorldMeta); break; case "/status": ReplyJson(response, Status); break; case "/players": ReplyJson(response, Players); break; case "/catalogue": ReplyJson(response, Catalogue, 120000); break; case "/terrain": PostJson(ctx, (byte[] body) => Applied(ApplyTerrain(body))); break; case "/objects": { string call = ctx.Request.Headers["X-Call-Id"]; PostJson(ctx, (byte[] body) => ApplyObjectsOnce(call, body)); break; } case "/models": PostJson(ctx, Models, 120000); break; case "/zones/reset": PostJson(ctx, (byte[] body) => Applied(ResetZones(body))); break; case "/watch": PostJson(ctx, Watch); break; case "/zone": PostGzip(ctx, ZoneObjects); break; case "/zone/movers": PostGzip(ctx, MovingObjects); break; case "/snapshot": ReplyGzip(response, Snapshot, 120000); break; default: Reply(response, 404, "text/plain", Encoding.UTF8.GetBytes("unknown path")); break; } } private byte[] Snapshot() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown World world = ZNet.World; ZPackage val = new ZPackage(); val.Write((byte)86); val.Write((byte)87); val.Write((byte)69); val.Write((byte)66); val.Write(1); val.Write(world.m_name); val.Write(world.m_seedName); val.Write(world.m_seed); val.Write(world.m_worldGenVersion); val.Write(ZNet.instance.GetTimeSeconds()); byte[] array = ZoneSystemData(); val.Write(array.Length); byte[] array2 = array; foreach (byte b in array2) { val.Write(b); } Dictionary<ZDOID, ZDO> dictionary = AllZdos(); List<ZDO> list = new List<ZDO>(dictionary.Count); foreach (ZDO value in dictionary.Values) { if (value.Persistent) { list.Add(value); } } Dictionary<ZDOID, (ConnectionType, int)> links = SnapshotLinks(); val.Write((short)41); val.Write(list.Count); foreach (ZDO item in list) { WriteZdo(val, item, links); } foreach (ZDO item2 in list) { val.Write(((ZDOID)(ref item2.m_uid)).UserID); val.Write(((ZDOID)(ref item2.m_uid)).ID); } return val.GetArray(); } private static byte[] ZoneSystemData() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) ZoneSystem instance = ZoneSystem.instance; ZPackage val = new ZPackage(); HashSet<Vector2s> hashSet = (HashSet<Vector2s>)GeneratedZones.GetValue(instance); val.Write(hashSet.Count); foreach (Vector2s item in hashSet) { val.Write(item); } val.Write(instance.m_locationVersion); HashSet<string> hashSet2 = (HashSet<string>)GlobalKeys.GetValue(instance); val.Write(hashSet2.Count); foreach (string item2 in hashSet2) { val.Write(item2); } val.Write(instance.LocationsGenerated); val.Write(instance.m_locationInstances.Count); foreach (LocationInstance value in instance.m_locationInstances.Values) { ZoneLocation location = value.m_location; val.Write((location != null) ? StringExtensionMethods.GetStableHashCode(location.m_prefabName) : 0); val.Write(value.m_position.x); val.Write(value.m_position.y); val.Write(value.m_position.z); val.Write(value.m_placed); } return val.GetArray(); } private static string Json(string s) { StringBuilder stringBuilder = new StringBuilder("\""); foreach (char c in s) { if (c >= ' ') { switch (c) { case '\\': stringBuilder.Append("\\\\"); break; case '"': stringBuilder.Append("\\\""); break; default: stringBuilder.Append(c); break; } } else { StringBuilder stringBuilder2 = stringBuilder.Append("\\u"); int num = c; stringBuilder2.Append(num.ToString("x4", CultureInfo.InvariantCulture)); } } return stringBuilder.Append('"').ToString(); } private static string F(float v) { return v.ToString("R", CultureInfo.InvariantCulture); } private byte[] Status() { World world = ZNet.World; Dictionary<ZDOID, ZDO> dictionary = AllZdos(); string s = string.Format("{{\"plugin\":{0},\"world\":{1},\"seedName\":{2},\"objects\":{3},\"players\":{4},\"netTime\":{5},\"features\":[\"move\",\"once\",\"files\",\"update\"],\"run\":{6}}}", Json("1.127.0"), Json(world?.m_name ?? ""), Json(world?.m_seedName ?? ""), dictionary.Count, ZNet.instance.GetPlayerList().Count, ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture), Json(_run)); return Encoding.UTF8.GetBytes(s); } private byte[] Players() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing refe
plugins/WorldEditorBridge.Api.dll
Decompiled 4 days agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("WorldEditorBridge.Api")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.127.0+32cdcbe34fb2b6e5ae8227b001c7868aa225cec4")] [assembly: AssemblyProduct("WorldEditorBridge.Api")] [assembly: AssemblyTitle("WorldEditorBridge.Api")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace WorldEditorBridge.Api { public sealed class AppliedChanges { public IReadOnlyList<AppliedObject> Created { get; } public IReadOnlyList<AppliedObject> Destroyed { get; } public IReadOnlyList<Zone> TerrainZones { get; } public IReadOnlyList<Zone> ResetZones { get; } public IReadOnlyList<AppliedMove> Moved { get; } public AppliedChanges(IReadOnlyList<AppliedObject> created, IReadOnlyList<AppliedObject> destroyed, IReadOnlyList<Zone> terrainZones, IReadOnlyList<Zone> resetZones) : this(created, destroyed, terrainZones, resetZones, Array.Empty<AppliedMove>()) { } public AppliedChanges(IReadOnlyList<AppliedObject> created, IReadOnlyList<AppliedObject> destroyed, IReadOnlyList<Zone> terrainZones, IReadOnlyList<Zone> resetZones, IReadOnlyList<AppliedMove> moved) { Created = created; Destroyed = destroyed; TerrainZones = terrainZones; ResetZones = resetZones; Moved = moved; } } public sealed class AppliedMove { public AppliedObject From { get; } public AppliedObject To { get; } public AppliedMove(AppliedObject from, AppliedObject to) { From = from; To = to; } } public sealed class AppliedObject { public long User { get; } public uint Id { get; } public int Prefab { get; } public float X { get; } public float Y { get; } public float Z { get; } public AppliedObject(long user, uint id, int prefab, float x, float y, float z) { User = user; Id = id; Prefab = prefab; X = x; Y = y; Z = z; } } public sealed class Zone { public int X { get; } public int Z { get; } public Zone(int x, int z) { X = x; Z = z; } } public static class BridgeApi { public const int Version = 1; public const string BridgeGuid = "Tie.WorldEditorBridge"; private static readonly object Lock = new object(); private static readonly Dictionary<string, IBridgeRoutes> RoutesById = new Dictionary<string, IBridgeRoutes>(StringComparer.Ordinal); private static readonly Dictionary<string, IBridgeListener> ListenersById = new Dictionary<string, IBridgeListener>(StringComparer.Ordinal); public static IReadOnlyList<string> ModIds { get { lock (Lock) { HashSet<string> hashSet = new HashSet<string>(RoutesById.Keys, StringComparer.Ordinal); hashSet.UnionWith(ListenersById.Keys); return new <>z__ReadOnlyArray<string>(hashSet.ToArray()); } } } public static IReadOnlyList<KeyValuePair<string, IBridgeListener>> Listeners { get { lock (Lock) { return new <>z__ReadOnlyArray<KeyValuePair<string, IBridgeListener>>(ListenersById.ToArray()); } } } public static void AddRoutes(string modId, IBridgeRoutes routes) { CheckId(modId); lock (Lock) { RoutesById[modId] = routes ?? throw new ArgumentNullException("routes"); } } public static void AddListener(string modId, IBridgeListener listener) { CheckId(modId); lock (Lock) { ListenersById[modId] = listener ?? throw new ArgumentNullException("listener"); } } public static void Remove(string modId) { lock (Lock) { RoutesById.Remove(modId); ListenersById.Remove(modId); } } public static IBridgeRoutes? RoutesOf(string modId) { lock (Lock) { IBridgeRoutes value; return RoutesById.TryGetValue(modId, out value) ? value : null; } } public static bool IsValidId(string? modId) { if (string.IsNullOrEmpty(modId) || modId.Length > 100) { return false; } foreach (char c in modId) { if (!char.IsLetterOrDigit(c) && c != '.' && c != '-' && c != '_') { return false; } } return true; } private static void CheckId(string modId) { if (!IsValidId(modId)) { throw new ArgumentException("a mod id is letters, digits, dots, dashes and underscores, 1 to 100 of them", "modId"); } } } public interface IBridgeListener { void OnApplied(AppliedChanges changes); } public interface IBridgeRoutes { byte[]? Handle(string name, byte[] body); } }