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 SeaDragon v0.1.6
plugins/SeaDragon.dll
Decompiled 17 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using Sansara.Admin; using Sansara.Chronicle; using Sansara.Clock; using Sansara.Deeds; using Sansara.Pings; using SeaDragon.Core; using Splatform; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("SeaDragon")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.6.0")] [assembly: AssemblyInformationalVersion("0.1.6+6cde3ca1e0e8ed2646ed67bfec6421864bf38ecc")] [assembly: AssemblyProduct("SeaDragon")] [assembly: AssemblyTitle("SeaDragon")] [assembly: AssemblyVersion("0.1.6.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Sansara.Clock { public static class RealClock { private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public const double WorldClockLimit = 1000000000.0; public static double Now => (DateTime.UtcNow - Epoch).TotalSeconds; public static bool IsWorldTime(double t) { if (t > 0.0) { return t < 1000000000.0; } return false; } public static double FromWorld(double t, double worldNow, double realNow) { if (!IsWorldTime(t)) { return t; } return realNow - (worldNow - t); } } } namespace Sansara.Pings { public static class PingChannels { private const ulong FnvOffset = 14695981039346656037uL; private const ulong FnvPrime = 1099511628211uL; private const ulong Golden = 11400714819323198485uL; private const int MaxSteps = 1000; public const string DistToken = "{dist}"; public const string Separator = " · "; private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; public static string Distance(double metres) { if (double.IsNaN(metres) || double.IsInfinity(metres) || metres < 0.0) { metres = 0.0; } double num = Math.Round(metres, MidpointRounding.AwayFromZero); if (num < 1000.0) { return num.ToString("0", Invariant) + " м"; } return Comma(Math.Round(metres / 1000.0, 1, MidpointRounding.AwayFromZero)) + " км"; } public static string Minutes(double seconds) { double num = Math.Max(0.0, seconds) / 60.0; if (num >= 120.0) { return Comma(Math.Round(num / 60.0, 1, MidpointRounding.AwayFromZero)) + " ч"; } return Math.Max(1.0, Math.Ceiling(num - 1E-09)).ToString("0", Invariant) + " мин"; } public static string Detail(params string[] parts) { if (parts == null) { return ""; } List<string> list = new List<string>(); foreach (string text in parts) { if (!string.IsNullOrWhiteSpace(text)) { list.Add(text.Trim()); } } return string.Join(" · ", list.ToArray()); } public static string Expand(string detail, double metres) { if (string.IsNullOrWhiteSpace(detail)) { return ""; } string newValue = (double.IsNaN(metres) ? "" : Distance(metres)); return Detail(detail.Replace("{dist}", newValue).Split(new string[1] { " · " }, StringSplitOptions.None)); } private static string Comma(double value) { return value.ToString("0.#", Invariant).Replace('.', ','); } public static string Key(string mod, string kind, string id) { return mod + "." + kind + ":" + id; } public static long SenderId(string channelKey, Func<long, bool> taken) { ulong num = Mix(Fnv(channelKey ?? "")); for (int i = 0; i < 1000; i++) { long num2 = (long)(num & 0x7FFFFFFFFFFFFFFFL); if (num2 != 0L && (taken == null || !taken(num2))) { return num2; } num = Mix(num + 11400714819323198485uL); } throw new InvalidOperationException($"Каналы пингов: для «{channelKey}» нет свободного id за {1000} шагов."); } private static ulong Fnv(string s) { ulong num = 14695981039346656037uL; foreach (char c in s) { num = (num ^ (byte)(c & 0xFF)) * 1099511628211L; num = (num ^ (byte)((int)c >> 8)) * 1099511628211L; } return num; } private static ulong Mix(ulong z) { z = (z ^ (z >> 30)) * 13787848793156543929uL; z = (z ^ (z >> 27)) * 10723151780598845931uL; return z ^ (z >> 31); } } public static class PingSender { private static readonly PlatformUserID ServerUser = new PlatformUserID("Steam_0"); private static readonly int ChatMessageHash = StringExtensionMethods.GetStableHashCode("ChatMessage"); private static int _msgCounter; private static bool _failLogged; public static ManualLogSource Log; public static void Send(string channelKey, string name, Vector3 pos, ZNetPeer peer, string detail = null) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) try { if (IsServer() && peer != null && peer.IsReady()) { Deliver(SenderId(channelKey), peer, Parameters(name, pos, detail)); } } catch (Exception e) { Fail(channelKey, e); } } public static void SendAll(string channelKey, string name, Vector3 pos, string detail = null) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) try { if (!IsServer()) { return; } long sender = SenderId(channelKey); ZPackage parameters = Parameters(name, pos, detail); foreach (ZNetPeer connectedPeer in ZNet.instance.GetConnectedPeers()) { if (connectedPeer != null && connectedPeer.IsReady()) { Deliver(sender, connectedPeer, parameters); } } } catch (Exception e) { Fail(channelKey, e); } } public static long SenderId(string channelKey) { long self = ZNet.GetUID(); return PingChannels.SenderId(channelKey, delegate(long id) { if (id == self) { return true; } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer != null && peer.m_uid == id) { return true; } } return false; }); } private static bool IsServer() { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { return ZRoutedRpc.instance != null; } return false; } private static ZPackage Parameters(string name, Vector3 pos, string detail) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown ZPackage val = new ZPackage(); ZRpc.Serialize(new object[4] { pos, 3, (object)new UserInfo { Name = (name ?? ""), UserId = ServerUser }, detail ?? "" }, ref val); val.SetPos(0); return val; } private static void Deliver(long sender, ZNetPeer peer, ZPackage parameters) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_0034: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown RoutedRPCData val = new RoutedRPCData { m_msgID = sender + ++_msgCounter, m_senderPeerID = sender, m_targetPeerID = peer.m_uid, m_targetZDO = ZDOID.None, m_methodHash = ChatMessageHash, m_parameters = parameters }; ZPackage val2 = new ZPackage(); val.Serialize(val2); peer.m_rpc.Invoke("RoutedRPC", new object[1] { val2 }); } private static void Fail(string channelKey, Exception e) { if (!_failLogged) { _failLogged = true; string text = $"Каналы пингов: пинг канала «{channelKey}» не отправлен (дальше такие ошибки не пишутся): {e}"; if (Log != null) { Log.LogError((object)text); } else { Debug.LogError((object)text); } } } } public static class PingTextPatch { public const string HarmonyId = "sansara.Pings.text"; public static ManualLogSource Log; private static bool _failLogged; public static void Ensure() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_008e: Expected O, but got Unknown try { if (!Application.isBatchMode && (int)SystemInfo.graphicsDeviceType != 4 && !Harmony.HasAnyPatches("sansara.Pings.text")) { MethodInfo methodInfo = AccessTools.Method(typeof(Chat), "AddInworldText", (Type[])null, (Type[])null); if (methodInfo == null) { Error("Каналы пингов: метода Chat.AddInworldText нет в игре — у пингов сервера останется подпись PING."); } else { new Harmony("sansara.Pings.text").Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(PingTextPatch), "Prefix", (Type[])null), new HarmonyMethod(typeof(PingTextPatch), "Postfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } catch (Exception ex) { Error("Каналы пингов: патч текста пинга не применён (останется PING): " + ex); } } private static void Prefix(Type type, string text, out string __state) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Invalid comparison between Unknown and I4 __state = (((int)type == 3) ? text : null); } private static void Postfix(Chat __instance, long senderID, Vector3 position, Type type, string __state) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_002f: 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) if ((int)type != 3 || string.IsNullOrWhiteSpace(__state)) { return; } try { Player localPlayer = Player.m_localPlayer; double metres = (((Object)(object)localPlayer != (Object)null) ? ((double)Utils.DistanceXZ(((Component)localPlayer).transform.position, position)) : double.NaN); string text = PingChannels.Expand(__state, metres); if (text == "") { return; } foreach (WorldTextInstance worldText in __instance.WorldTexts) { if (worldText.m_talkerID == senderID) { worldText.m_text = text; if ((Object)(object)worldText.m_textMeshField != (Object)null) { ((TMP_Text)worldText.m_textMeshField).text = worldText.m_name + ": " + text; } break; } } } catch (Exception ex) { if (!_failLogged) { _failLogged = true; Error("Каналы пингов: текст пинга не показан (дальше такие ошибки не пишутся): " + ex); } } } private static void Error(string text) { if (Log != null) { Log.LogError((object)text); } else { Debug.LogError((object)text); } } } } namespace Sansara.Chronicle { public sealed class ChroniclePlayer { public long Id { get; } public string Name { get; } public ChroniclePlayer(long id, string name) { Id = id; Name = name ?? ""; } } public sealed class ChronicleEntry { public double Time; public string Date = ""; public string Kind = ""; public string Id = ""; public string Result = ""; public List<ChroniclePlayer> Players = new List<ChroniclePlayer>(); public const string Victory = "victory"; public bool IsVictory { get { if (!(Result == "victory")) { return Result == "found"; } return true; } } public static string Clean(string s) { return new string((s ?? "").Where((char c) => c != '\t' && c != '\n' && c != '\r' && c != '|' && c != '=').ToArray()).Trim(); } public string ToLine() { string text = string.Join("|", Players.Select((ChroniclePlayer p) => p.Id.ToString(CultureInfo.InvariantCulture) + "=" + Clean(p.Name))); return string.Join("\t", Time.ToString("R", CultureInfo.InvariantCulture), Clean(Date), Clean(Kind), Clean(Id), Clean(Result), text); } public static ChronicleEntry Parse(string line) { if (string.IsNullOrWhiteSpace(line) || line.TrimStart(Array.Empty<char>()).StartsWith("#", StringComparison.Ordinal)) { return null; } string[] array = line.TrimEnd(new char[1] { '\r' }).Split(new char[1] { '\t' }); if (array.Length < 5 || !double.TryParse(array[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || array[2].Trim() == "" || array[3].Trim() == "") { return null; } ChronicleEntry chronicleEntry = new ChronicleEntry { Time = result, Date = array[1].Trim(), Kind = array[2].Trim(), Id = array[3].Trim(), Result = array[4].Trim() }; if (array.Length > 5) { string[] array2 = array[5].Split(new char[1] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text in array2) { int num = text.IndexOf('='); long.TryParse((num > 0) ? text.Substring(0, num) : "0", NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2); chronicleEntry.Players.Add(new ChroniclePlayer(result2, (num >= 0) ? text.Substring(num + 1) : text)); } } return chronicleEntry; } public static List<ChronicleEntry> ParseAll(string text, out int bad) { List<ChronicleEntry> list = new List<ChronicleEntry>(); bad = 0; string[] array = (text ?? "").Split(new char[1] { '\n' }); foreach (string text2 in array) { ChronicleEntry chronicleEntry = Parse(text2); if (chronicleEntry != null) { list.Add(chronicleEntry); } else if (!string.IsNullOrWhiteSpace(text2) && !text2.TrimStart(Array.Empty<char>()).StartsWith("#", StringComparison.Ordinal)) { bad++; } } return list; } } public static class ChronicleFile { public static string PathFor(string configDir, string world) { string text = string.Concat((world ?? "world").Split(Path.GetInvalidFileNameChars())); return Path.Combine(configDir, "sansara.Chronicle", text + ".tsv"); } public static void Append(string path, ChronicleEntry entry) { Directory.CreateDirectory(Path.GetDirectoryName(path)); File.AppendAllText(path, entry.ToLine() + "\n", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } public static List<ChronicleEntry> Read(string path, out int bad) { bad = 0; if (!File.Exists(path)) { return new List<ChronicleEntry>(); } return ChronicleEntry.ParseAll(File.ReadAllText(path), out bad); } } public sealed class FirstVictory { public string Id; public string Date; public List<string> Names = new List<string>(); public int Count; } public sealed class Leader { public string Name; public int Count; } public static class ChronicleStats { public static Dictionary<string, FirstVictory> Firsts(IEnumerable<ChronicleEntry> all, string kind) { Dictionary<string, FirstVictory> dictionary = new Dictionary<string, FirstVictory>(); foreach (ChronicleEntry item in from e in all where e.Kind == kind && e.IsVictory orderby e.Time select e) { if (!dictionary.TryGetValue(item.Id, out var value)) { value = new FirstVictory { Id = item.Id, Date = item.Date, Names = (from p in item.Players select p.Name into n where n != "" select n).Distinct().ToList() }; dictionary[item.Id] = value; } value.Count++; } return dictionary; } public static List<Leader> Leaders(IEnumerable<ChronicleEntry> all, string kind) { Dictionary<long, int> dictionary = new Dictionary<long, int>(); Dictionary<long, string> names = new Dictionary<long, string>(); foreach (ChronicleEntry item in from e in all where e.Kind == kind && e.IsVictory orderby e.Time select e) { foreach (ChroniclePlayer item2 in from p in item.Players group p by (p.Id == 0L) ? p.Name : p.Id.ToString() into g select g.First()) { long key = ((item2.Id != 0L) ? item2.Id : item2.Name.GetHashCode()); dictionary[key] = ((!dictionary.TryGetValue(key, out var value)) ? 1 : (value + 1)); if (item2.Name != "") { names[key] = item2.Name; } } } string value2; return (from kv in dictionary select new Leader { Name = (names.TryGetValue(kv.Key, out value2) ? value2 : "?"), Count = kv.Value } into l orderby l.Count descending select l).ThenBy<Leader, string>((Leader l) => l.Name, StringComparer.Ordinal).ToList(); } public static string Names(IList<string> names, int max) { if (names.Count == 0) { return ""; } for (int num = names.Count; num >= 1; num--) { string text = string.Join(", ", names.Take(num)) + ((num < names.Count) ? $" +{names.Count - num}" : ""); if (text.Length <= max) { return text; } } string text2 = names[0]; if (text2.Length <= max) { return text2; } return text2.Substring(0, Math.Max(1, max - 1)) + "…"; } } } namespace Sansara.Deeds { public static class DeedBus { public const string Key = "sansara.Deeds.v1"; private static Dictionary<string, Action<string, string, int, string, long[], string[]>> Table { get { object data = AppDomain.CurrentDomain.GetData("sansara.Deeds.v1"); if (data == null) { Dictionary<string, Action<string, string, int, string, long[], string[]>> dictionary = new Dictionary<string, Action<string, string, int, string, long[], string[]>>(StringComparer.Ordinal); AppDomain.CurrentDomain.SetData("sansara.Deeds.v1", dictionary); return dictionary; } return (data as Dictionary<string, Action<string, string, int, string, long[], string[]>>) ?? throw new InvalidOperationException("данные sansara.Deeds.v1 другого формата"); } } public static bool Subscribe(string owner, Action<string, string, int, string, long[], string[]> handler) { try { Table[owner] = handler ?? throw new ArgumentNullException("handler"); return true; } catch (Exception) { return false; } } public static bool Unsubscribe(string owner) { try { Table.Remove(owner); return true; } catch (Exception) { return false; } } public static int Publish(string kind, string id, int tier, string result, long[] playerIds, string[] playerNames, Action<string> log) { if (playerIds == null || playerNames == null || playerIds.Length == 0 || playerIds.Length != playerNames.Length) { return 0; } KeyValuePair<string, Action<string, string, int, string, long[], string[]>>[] array; try { array = Table.ToArray(); } catch (Exception ex) { log?.Invoke("Шина подвигов: " + ex.Message); return 0; } KeyValuePair<string, Action<string, string, int, string, long[], string[]>>[] array2 = array; for (int i = 0; i < array2.Length; i++) { KeyValuePair<string, Action<string, string, int, string, long[], string[]>> keyValuePair = array2[i]; try { keyValuePair.Value(kind, id, tier, result, playerIds, playerNames); } catch (Exception arg) { log?.Invoke($"Шина подвигов: подписчик {keyValuePair.Key}: {arg}"); } } return array.Length; } } } namespace Sansara.Admin { internal static class AdminChannel { private const float ScanSeconds = 1f; private const float DenialLogSeconds = 30f; private static ManualLogSource _log; private static bool _owner; private static bool _announced; private static float _nextScan; private static readonly HashSet<ZRpc> Registered = new HashSet<ZRpc>(); private static readonly Dictionary<ZRpc, float> LastDenial = new Dictionary<ZRpc, float>(); public static void Register(string module, string[] verbs, Func<string, string, string, string> handler, ManualLogSource log) { _log = log; if (AdminRegistry.Shared.Register(module, verbs, handler)) { log.LogWarning((object)("Админ-канал: модуль " + module + " зарегистрирован повторно — обработчик заменён.")); } if (AdminRegistry.Shared.ClaimOwner(typeof(AdminChannel).Assembly.GetName().Name)) { _owner = true; } } public static void Tick() { if (!_owner || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || Time.realtimeSinceStartup < _nextScan) { return; } _nextScan = Time.realtimeSinceStartup + 1f; try { Scan(); } catch (Exception ex) { _log.LogError((object)("Админ-канал: ошибка: " + ex)); } } public static void CheckFile(string guid, string logPrefix, Func<string, string, string, string> handler) { string path = Path.Combine(Paths.ConfigPath, guid + ".command"); if (!File.Exists(path)) { return; } string text; try { text = File.ReadAllText(path).Trim(); File.Delete(path); } catch (Exception ex) { _log.LogWarning((object)(logPrefix + ": файл команды не прочитан: " + ex.Message)); return; } _log.LogInfo((object)(logPrefix + ": команда «" + AdminProtocol.ForLog(text) + "».")); try { _log.LogInfo((object)(logPrefix + ": " + handler(text, "файл команд", "").Replace("\n", "; "))); } catch (Exception ex2) { _log.LogError((object)(logPrefix + ": ошибка команды: " + ex2)); } } private static void Scan() { if (!_announced) { _announced = true; _log.LogInfo((object)("Админ-канал: владелец " + AdminRegistry.Shared.Owner + ", модули: " + string.Join(", ", AdminRegistry.Shared.Modules().ToArray()) + ".")); } HashSet<ZRpc> live = new HashSet<ZRpc>(); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer != null && peer.m_rpc != null) { live.Add(peer.m_rpc); if (Registered.Add(peer.m_rpc)) { peer.m_rpc.Register<ZPackage>("Sansara_Admin", (Action<ZRpc, ZPackage>)OnRequest); } } } Registered.RemoveWhere((ZRpc r) => !live.Contains(r)); foreach (ZRpc item in new List<ZRpc>(LastDenial.Keys)) { if (!live.Contains(item)) { LastDenial.Remove(item); } } } private static void OnRequest(ZRpc rpc, ZPackage pkg) { //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown int num = 0; AdminReply adminReply; try { int protocol = pkg.ReadInt(); num = pkg.ReadInt(); string module = pkg.ReadString(); string line = pkg.ReadString(); adminReply = Handle(rpc, protocol, module, line); } catch (Exception ex) { ZNetPeer val = ZNet.instance.GetPeers().Find((ZNetPeer p) => p.m_rpc == rpc); if (val == null || !val.IsReady()) { return; } LogThrottled(rpc, "Админ-канал: неверный запрос от " + AdminProtocol.ForLog(val.m_playerName) + ": " + AdminProtocol.ForLog(ex.Message)); adminReply = new AdminReply(4, "неверный запрос"); } if (adminReply != null) { ZPackage val2 = new ZPackage(); val2.Write(1); val2.Write(num); val2.Write(adminReply.Code); val2.Write(AdminProtocol.Truncate(adminReply.Text)); rpc.Invoke("Sansara_AdminReply", new object[1] { val2 }); } } private static void LogThrottled(ZRpc rpc, string message) { float realtimeSinceStartup = Time.realtimeSinceStartup; if (!LastDenial.TryGetValue(rpc, out var value) || realtimeSinceStartup - value >= 30f) { LastDenial[rpc] = realtimeSinceStartup; _log.LogWarning((object)message); } } private static AdminReply Handle(ZRpc rpc, int protocol, string module, string line) { ZNetPeer val = ZNet.instance.GetPeers().Find((ZNetPeer p) => p.m_rpc == rpc); if (val == null || !val.IsReady()) { return null; } AdminReply adminReply = AdminProtocol.Check(protocol, module, line); if (adminReply != null) { return adminReply; } string text = AdminProtocol.ForLog(val.m_playerName); string text2 = AdminProtocol.ForLog(val.m_socket.GetHostName()); string text3 = AdminProtocol.ForLog(AdminProtocol.Shown(module, line)); bool flag = ((ZDOID)(ref val.m_characterID)).IsNone(); if (flag || !ZNet.instance.IsAdmin(val.m_socket.GetHostName())) { LogThrottled(rpc, "Админ-канал: отказано " + text + " (" + text2 + "): " + text3); return new AdminReply(1, flag ? "отказано: персонаж не в мире (ещё не вошёл или погиб)" : "отказано: нужны права администратора"); } Exception error; AdminReply adminReply2 = AdminRegistry.Shared.Dispatch(module, line, val.m_playerName, val.m_socket.GetHostName(), out error); if (error != null) { _log.LogError((object)("Админ-канал: " + text + " (" + text2 + ") → " + text3 + ": " + AdminProtocol.ForLog(error.Message) + Environment.NewLine + error.StackTrace)); } else { _log.LogInfo((object)("Админ-канал: " + text + " (" + text2 + ") → " + text3 + ": " + AdminProtocol.ForLog(AdminProtocol.FirstLine(adminReply2.Text)))); } return adminReply2; } } public sealed class AdminCommand { public string Verb = ""; public readonly List<string> Args = new List<string>(); public string Argument => string.Join(" ", Args); public static AdminCommand Parse(string text) { AdminCommand adminCommand = new AdminCommand(); List<string> list = Tokens(text); if (list.Count == 0) { return adminCommand; } adminCommand.Verb = list[0].ToLowerInvariant(); adminCommand.Args.AddRange(list.GetRange(1, list.Count - 1)); return adminCommand; } public static List<string> Tokens(string text) { List<string> list = new List<string>(); StringBuilder stringBuilder = new StringBuilder(); bool flag = false; bool flag2 = false; string text2 = text ?? ""; foreach (char c in text2) { if (c == '"') { flag = !flag; flag2 = true; } else if (!flag && char.IsWhiteSpace(c)) { if (flag2) { list.Add(stringBuilder.ToString()); stringBuilder.Clear(); flag2 = false; } } else { stringBuilder.Append(c); flag2 = true; } } if (flag2) { list.Add(stringBuilder.ToString()); } return list; } public static bool TryId(string argument, out string id) { string text = (argument ?? "").Trim(); id = ((text.Length > 1 && text[0] == '@') ? text.Substring(1).Trim() : null); if (id == "") { id = null; } return id != null; } } public sealed class AdminReply { public readonly int Code; public readonly string Text; public AdminReply(int code, string text) { Code = code; Text = text ?? ""; } } public static class AdminProtocol { public const int Version = 1; public const string RequestRpc = "Sansara_Admin"; public const string ReplyRpc = "Sansara_AdminReply"; public const int MaxLine = 256; public const int MaxReply = 4000; public const int Done = 0; public const int Denied = 1; public const int NoModule = 2; public const int Failed = 3; public const int Invalid = 4; public const int MaxLogText = 300; public static string Truncate(string text) { string text2 = text ?? ""; if (text2.Length > 4000) { return text2.Substring(0, 3999) + "…"; } return text2; } public static AdminReply Check(int protocol, string module, string line) { if (protocol != 1) { return new AdminReply(4, $"неверный запрос: обновите Sansara Admin (протокол сервера {1})"); } if (module == null || line == null) { return new AdminReply(4, "неверный запрос"); } if (Shown(module, line).Length > 256) { return new AdminReply(4, $"строка длиннее {256} символов"); } return null; } public static string Shown(string module, string line) { string text = (module ?? "").Trim(); if (!(text == "")) { return (text + " " + (line ?? "").Trim()).Trim(); } return "help"; } public static string ForLog(string s) { char[] array = (s ?? "").ToCharArray(); for (int i = 0; i < array.Length; i++) { if (char.IsControl(array[i])) { array[i] = ' '; } } if (array.Length > 300) { return new string(array, 0, 300); } return new string(array); } public static string FirstLine(string text) { string text2 = (text ?? "").Replace("\r", ""); int num = text2.IndexOf('\n'); if (num >= 0) { return text2.Substring(0, num); } return text2; } public static string HelpLine(string module, IEnumerable<string> verbs) { return module + ": " + string.Join(", ", verbs); } public static Dictionary<string, string[]> ParseHelp(string text) { Dictionary<string, string[]> dictionary = new Dictionary<string, string[]>(StringComparer.Ordinal); string[] array = (text ?? "").Replace("\r", "").Split(new char[1] { '\n' }); foreach (string text2 in array) { int num = text2.IndexOf(':'); if (num <= 0) { continue; } string text3 = text2.Substring(0, num).Trim(); if (IsName(text3)) { dictionary[text3] = (from v in text2.Substring(num + 1).Split(new char[1] { ',' }) select v.Trim()).Where(IsName).ToArray(); } } return dictionary; } public static bool IsName(string s) { if (!string.IsNullOrEmpty(s)) { return s.All((char c) => c >= 'a' && c <= 'z'); } return false; } public static string Unknown(string verb, IEnumerable<string> verbs) { return (string.IsNullOrEmpty(verb) ? "укажите действие" : ("неизвестное действие «" + verb + "»")) + "; есть: " + string.Join(", ", verbs); } } public sealed class AdminRegistry { public const string SharedKey = "sansara.Admin.v1"; public static readonly AdminRegistry Shared = new AdminRegistry("sansara.Admin.v1"); private readonly string _key; private Dictionary<string, Tuple<string[], Func<string, string, string, string>>> Table { get { object data = AppDomain.CurrentDomain.GetData(_key); if (data == null) { Dictionary<string, Tuple<string[], Func<string, string, string, string>>> dictionary = new Dictionary<string, Tuple<string[], Func<string, string, string, string>>>(StringComparer.Ordinal); AppDomain.CurrentDomain.SetData(_key, dictionary); return dictionary; } return (data as Dictionary<string, Tuple<string[], Func<string, string, string, string>>>) ?? throw new InvalidOperationException("данные " + _key + " другого формата"); } } public string Owner => (AppDomain.CurrentDomain.GetData(_key + ".owner") as string) ?? ""; public AdminRegistry(string key) { _key = key; } public bool Register(string module, string[] verbs, Func<string, string, string, string> handler) { string text = (module ?? "").Trim().ToLowerInvariant(); if (!AdminProtocol.IsName(text)) { throw new ArgumentException("имя модуля — латинские буквы: " + module); } string[] array = verbs ?? new string[0]; foreach (string text2 in array) { if (!AdminProtocol.IsName(text2)) { throw new ArgumentException("глагол — латинские буквы: " + text2); } } if (handler == null) { throw new ArgumentNullException("handler"); } Dictionary<string, Tuple<string[], Func<string, string, string, string>>> table = Table; bool result = table.ContainsKey(text); table[text] = Tuple.Create(verbs ?? new string[0], handler); return result; } public bool ClaimOwner(string assembly) { if (string.IsNullOrEmpty(assembly)) { throw new ArgumentException("пустое имя сборки", "assembly"); } string name = _key + ".owner"; if (!(AppDomain.CurrentDomain.GetData(name) is string text)) { AppDomain.CurrentDomain.SetData(name, assembly); return true; } return text == assembly; } public List<string> Modules() { return Table.Keys.OrderBy<string, string>((string k) => k, StringComparer.Ordinal).ToList(); } public string HelpText() { Dictionary<string, Tuple<string[], Func<string, string, string, string>>> table = Table; if (table.Count != 0) { return string.Join("\n", from k in Modules() select AdminProtocol.HelpLine(k, table[k].Item1)); } return "на сервере нет модулей Sansara Admin"; } public AdminReply Dispatch(string module, string line, string adminName, string adminId, out Exception error) { error = null; try { string text = (module ?? "").Trim().ToLowerInvariant(); if (text == "") { return new AdminReply(0, AdminProtocol.Truncate(HelpText())); } Dictionary<string, Tuple<string[], Func<string, string, string, string>>> table = Table; if (!table.TryGetValue(text, out var value)) { return new AdminReply(2, "модуля " + text + " нет на сервере; есть: " + ((table.Count == 0) ? "ничего" : string.Join(", ", Modules()))); } string text2 = value.Item2((line ?? "").Trim(), adminName ?? "", adminId ?? ""); return new AdminReply(0, AdminProtocol.Truncate(string.IsNullOrEmpty(text2) ? "готово" : text2)); } catch (Exception ex) { return new AdminReply(3, AdminProtocol.Truncate("ошибка: " + (error = ex).Message)); } } } public static class AdminUi { public const string Verb = "ui"; public const string Head = "ui=1"; public const string NoteKey = "note"; public const string MoreKey = "more"; private const int Reserve = 16; public static string Field(object value) { char[] array = ((!(value is bool)) ? (Convert.ToString(value, CultureInfo.InvariantCulture) ?? "") : (((bool)value) ? "1" : "0")).ToCharArray(); for (int i = 0; i < array.Length; i++) { if (array[i] == ';') { array[i] = ','; } else if (char.IsControl(array[i])) { array[i] = ' '; } } return new string(array).Trim(); } public static string Row(string key, params object[] fields) { if (!AdminProtocol.IsName(key)) { throw new ArgumentException("ключ строки ui — латинские буквы в нижнем регистре: " + key); } return key + "=" + string.Join(";", (fields ?? new object[0]).Select(Field)); } public static string Note(string text) { return Text(new string[1] { Row("note", text) }); } public static string Text(IEnumerable<string> rows) { List<string> list = (rows ?? Enumerable.Empty<string>()).ToList(); StringBuilder stringBuilder = new StringBuilder("ui=1"); for (int i = 0; i < list.Count; i++) { if (stringBuilder.Length + 1 + list[i].Length > 3984) { stringBuilder.Append('\n').Append("more").Append('=') .Append((list.Count - i).ToString(CultureInfo.InvariantCulture)); break; } stringBuilder.Append('\n').Append(list[i]); } return stringBuilder.ToString(); } } } namespace SeaDragon { internal static class DragonConfig { internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<float> Health; internal static ConfigEntry<float> FlyHeight; internal static ConfigEntry<float> PassRadius; internal static ConfigEntry<float> LeaveDistance; internal static ConfigEntry<float> EngageDistance; internal static ConfigEntry<string> Drops; internal static ConfigEntry<float> CheckMinutes; internal static ConfigEntry<float> Chance; internal static ConfigEntry<float> ApproachDistance; internal static ConfigEntry<float> FlybySeconds; internal static ConfigEntry<float> MinDepth; internal static ConfigEntry<float> GlideSpeed; internal static ConfigEntry<float> DelayMinMinutes; internal static ConfigEntry<float> DelayMaxMinutes; internal static ConfigEntry<float> MarkHours; internal static ConfigEntry<float> CooldownHours; internal static ConfigEntry<float> FightMinutes; internal static ConfigEntry<float> OffShipMinutes; internal static ConfigEntry<float> SpawnDistance; internal static ConfigEntry<float> LeaveSeconds; internal static ConfigEntry<float> PingSeconds; internal static ConfigEntry<bool> LoseInventoryOnDeath; internal static ConfigEntry<string> RewardPool; internal static ConfigEntry<int> RewardCount; internal static ConfigEntry<float> MinDamageShare; internal static ConfigEntry<float> CreditDistance; internal static ConfigEntry<int> MinHealthSteps; internal static ConfigEntry<float> MinFightSeconds; private static ConfigEntry<float> Synced(ConfigFile cfg, string section, string key, float value, float min, float max, string text) { //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_0024: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown return cfg.Bind<float>(section, key, value, new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); } private static ConfigEntry<float> Server(ConfigFile cfg, string section, string key, float value, float min, float max, string text) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown return cfg.Bind<float>(section, key, value, new ConfigDescription(text, (AcceptableValueBase)(object)new AcceptableValueRange<float>(min, max), Array.Empty<object>())); } internal static void Bind(ConfigFile cfg) { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown //IL_03a3: Unknown result type (might be due to invalid IL or missing references) //IL_03a8: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Expected O, but got Unknown //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03ba: Expected O, but got Unknown //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_0406: Expected O, but got Unknown //IL_047b: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Expected O, but got Unknown Enabled = cfg.Bind<bool>("General", "Enabled", false, "Сервер устраивает пролёты дракона и месть (читает сервер). false — новых драконов нет, живой убирается; префаб регистрируется всегда, иначе игра удалит уже созданного. Админ-команды dragon работают и при false, кроме flyby/revenge."); Health = Synced(cfg, "Dragon", "Health", 3000f, 100f, 50000f, "Здоровье «Ледяной вдовы» (у Модер 7500). Отряду с луками 3000 — несколько минут боя; больше — бой упрётся в предел FightMinutes."); FlyHeight = Synced(cfg, "Dragon", "FlyHeight", 18f, 8f, 60f, "Высота пролёта над водой или палубой, м. Игра сама держит не ниже 10 м над тем, что под драконом."); PassRadius = Synced(cfg, "Dragon", "PassRadius", 12f, 4f, 60f, "Расстояние по горизонтали до корабля, на котором пролёт считается «над кораблём» и дракон поворачивает к выходу, м."); LeaveDistance = Synced(cfg, "Dragon", "LeaveDistance", 250f, 100f, 1000f, "Улёт: точка выхода в стольких метрах от корабля (или от обидчика); там дракон убирается."); EngageDistance = Synced(cfg, "Dragon", "EngageDistance", 40f, 15f, 150f, "Мстящий дракон летит к обидчику сам и включает ванильный бой ближе этого расстояния, м (плевок бьёт на 5–25 м)."); Drops = cfg.Bind<string>("Dragon", "Drops", "TrophySeaDragon:1:1:1,DragonTear:3:3:1", new ConfigDescription("Добыча мстящего дракона: Префаб:мин:макс:шанс через запятую (TrophySeaDragon — трофей «Голова ледяной вдовы»). Мирный дракон не роняет ничего (иначе — ферма слёз Модер).", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); CheckMinutes = Server(cfg, "Flyby", "CheckMinutes", 60f, 1f, 1440f, "Как часто сервер пробует устроить пролёт, мин реального времени."); Chance = Server(cfg, "Flyby", "Chance", 0.5f, 0f, 1f, "Шанс пролёта на каждой проверке, если в открытом океане есть игрок на корабле (0.5 — в среднем раз в два часа)."); ApproachDistance = Server(cfg, "Flyby", "ApproachDistance", 150f, 60f, 400f, "С какого расстояния от корабля дракон заходит, м."); FlybySeconds = Server(cfg, "Flyby", "TimeLimitSeconds", 180f, 30f, 900f, "Предел пролёта: по нему мирный дракон убирается, где бы ни был."); MinDepth = Server(cfg, "Flyby", "MinDepth", 10f, 2f, 100f, "Открытый океан: биом Ocean, не воды Пепельных земель и Дальнего Севера, глубина по генератору не меньше стольких м под кораблём и в 20 м вокруг."); GlideSpeed = Server(cfg, "Flyby", "GlideSpeed", 12f, 2f, 40f, "Скорость, м/с, с которой сервер сам ведёт дракона, пока им не владеет ни один клиент (дальше ~100 м от игроков). Своим ИИ дракон летит 10–20 м/с."); DelayMinMinutes = Server(cfg, "Revenge", "DelayMinMinutes", 10f, 0f, 1440f, "Месть приходит не раньше стольких минут после удара."); DelayMaxMinutes = Server(cfg, "Revenge", "DelayMaxMinutes", 20f, 0f, 1440f, "…и не позже (случайно между Min и Max), если обидчик в это время на корабле в открытом океане."); MarkHours = Server(cfg, "Revenge", "MarkHours", 24f, 0.1f, 720f, "Метка мести снимается, если обидчик за столько часов реального времени ни разу не вышел в открытый океан."); CooldownHours = Server(cfg, "Revenge", "CooldownHours", 24f, 0f, 720f, "Не больше одной мести на игрока за столько часов: удары в это время новую метку не ставят."); FightMinutes = Server(cfg, "Revenge", "FightMinutes", 10f, 1f, 120f, "Бой дольше — дракон улетает без награды."); OffShipMinutes = Server(cfg, "Revenge", "OffShipMinutes", 2f, 0.1f, 60f, "Обидчик сошёл с корабля дольше чем на столько минут — дракон улетает."); SpawnDistance = Server(cfg, "Revenge", "SpawnDistance", 150f, 40f, 400f, "Мстящий дракон появляется в стольких метрах от обидчика, м."); LeaveSeconds = Server(cfg, "Revenge", "LeaveSeconds", 60f, 5f, 600f, "Улетающий дракон убирается не позже чем через столько секунд."); PingSeconds = Server(cfg, "Revenge", "PingSeconds", 10f, 0f, 120f, "Пинг мстящего дракона на карте обидчика каждые столько секунд; 0 — без пинга."); LoseInventoryOnDeath = cfg.Bind<bool>("Revenge", "LoseInventoryOnDeath", true, new ConfigDescription("С 0.1.3: цель мести, которую убила мстящая вдова (последний удар — её), теряет всё, что было при ней, включая надетое и награды Event Rewards (даже «не выпадает при смерти»), надгробия нет; остаются только квестовые предметы игры. Смерть от утопления, падения или другого врага после удара вдовы, гибель других членов экипажа — обычные. Баланс: месть становится смертельно опасной — в бой с ней идут без лишнего, проигрыш стоит всего снаряжения. Решает клиент погибшего (приходит с сервера). false — смерть от вдовы обычная, с надгробием.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); RewardPool = cfg.Bind<string>("Rewards", "RewardPool", "", "Награды Event Rewards каждому ударившему мстящего дракона (отметки атакующих), id через запятую. Высший пул, как [Tier8] RewardPool «Охоты за головами»: ивент крайне сложный (решение пользователя 2026-11-27). Пусто — без награды Event Rewards."); RewardCount = cfg.Bind<int>("Rewards", "RewardCount", 4, new ConfigDescription("Сколько наград из пула получает каждый участник (по умолчанию 4); у одного участника без повторов, пока хватает пула.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>())); MinDamageShare = Server(cfg, "Rewards", "MinDamageShare", 0.5f, 0f, 1f, "Победа над мстящим драконом засчитывается, только если сервер видел, что дракон потерял не меньше такой доли здоровья (по последнему здоровью в объекте; 0 — без этой проверки). Кроме неё нужна подтверждённая смерть: отчёт клиента-владельца о гибели или нулевое здоровье. Удаление объекта без смерти (модифицированный клиент) — уборка без награды."); CreditDistance = Server(cfg, "Rewards", "CreditDistance", 100f, 0f, 2000f, "Награду и запись в летописи получают ударившие, которые в момент смерти дракона в игре, живы и не дальше стольких м по горизонтали от него; 0 — без предела расстояния."); MinHealthSteps = cfg.Bind<int>("Rewards", "MinHealthSteps", 3, new ConfigDescription("Победа засчитывается, только если сервер в своей копии объекта видел, как здоровье дракона снижалось хотя бы столько раз (каждое новое наименьшее значение; сервер получает данные владельца примерно 20 раз в секунду). Одна запись «0» (killall, подделка) — одно снижение. 0 — без этой проверки.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); MinFightSeconds = Server(cfg, "Rewards", "MinFightSeconds", 10f, 0f, 600f, "…и бой длился не меньше стольких секунд от первого урона, который увидел сервер, до смерти. Отряду с луками на 3000 здоровья нужно несколько минут; 0 — без этой проверки."); } internal static FlightNumbers Flight() { return new FlightNumbers { Height = FlyHeight.Value, PassRadius = PassRadius.Value, LeaveDistance = LeaveDistance.Value, Water = (((Object)(object)ZoneSystem.instance != (Object)null) ? ZoneSystem.instance.m_waterLevel : 30f) }; } internal static DragonSettings Settings() { return new DragonSettings { CheckMinutes = CheckMinutes.Value, Chance = Chance.Value, FlybySeconds = FlybySeconds.Value, DelayMinMinutes = DelayMinMinutes.Value, DelayMaxMinutes = DelayMaxMinutes.Value, MarkHours = MarkHours.Value, CooldownHours = CooldownHours.Value, FightMinutes = FightMinutes.Value, OffShipMinutes = OffShipMinutes.Value, LeaveSeconds = LeaveSeconds.Value }; } internal static string Describe() { return $"Enabled={Enabled.Value}, проверка каждые {CheckMinutes.Value:0.#} мин, шанс {Chance.Value:0.##}, здоровье {Health.Value:0}, " + $"месть через {DelayMinMinutes.Value:0.#}–{DelayMaxMinutes.Value:0.#} мин, потеря инвентаря от мести {LoseInventoryOnDeath.Value}, наград в пуле {DragonRules.Pool(RewardPool.Value).Length}, " + $"зачёт: урон ≥ {MinDamageShare.Value:P0}, снижений здоровья ≥ {MinHealthSteps.Value}, бой ≥ {MinFightSeconds.Value:0.#} с"; } } internal static class DragonHost { private sealed class Active { public ZDOID Uid; public DragonMode Kind; public string Tag = ""; public double StartedAt; public long TargetId; public string TargetName = ""; public double LeftAt; public double OffShipSince; public float NextPing; public float NextLeaveRpc; public bool TestPoint; public float MaxHealth; public HealthTrack Track; public double ReportAt; public string ReportBy = ""; public bool ReportCheated; public float NextConfirm; public long ConfirmPeer; public bool Revoked; public readonly Dictionary<string, long> Strikers = new Dictionary<string, long>(StringComparer.Ordinal); public float Lowest { get { if (Track != null && !double.IsNaN(Track.Lowest)) { return (float)Track.Lowest; } return float.NaN; } } } private sealed class PlayerInfo { public ZNetPeer Peer; public long Id; public string Name = ""; public Vector3 Pos; public ZDO Ship; public bool Dead; } private const float TickSeconds = 1f; private const float RemoveIfNobodyMeters = 600f; private const float LeaveRpcSeconds = 5f; private const double DeathReportSeconds = 10.0; private static readonly Random Rng = new Random(); private static readonly List<ZDO> Found = new List<ZDO>(); private static readonly Dictionary<int, HullBox> Hulls = new Dictionary<int, HullBox>(); private static readonly HashSet<int> ShipHashes = new HashSet<int>(Hull.ShipPrefabs.Select((string n) => StringExtensionMethods.GetStableHashCode(n))); private static DragonState _state; private static string _path; private static bool _hooked; private static bool _booted; private static float _nextTick; private static float _lastFrame; private static Active _active; private static string _lastWait = ""; private static FieldInfo _ewpSkip; private static bool _ewpChecked; private static MethodInfo _enqueue; private static bool _enqueueChecked; private static readonly HashSet<ZRpc> Registered = new HashSet<ZRpc>(); private static ZDOID _endedUid = ZDOID.None; private static long _endedTarget; private static double _endedAt; internal static readonly string[] Verbs = new string[9] { "status", "flyby", "revenge", "leave", "clear", "test", "seized", "restore", "testgrave" }; private static double Now => RealClock.Now; internal static bool Ready { get { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && ZDOMan.instance != null && (Object)(object)ZNetScene.instance != (Object)null && (Object)(object)ZoneSystem.instance != (Object)null) { return WorldGenerator.instance != null; } return false; } } private static FieldInfo EwpSkip { get { if (!_ewpChecked) { _ewpChecked = true; Type type = AccessTools.TypeByName("ExpandWorld.Prefab.HandleCreated"); _ewpSkip = ((type == null) ? null : AccessTools.Field(type, "Skip")); } return _ewpSkip; } } internal static void Tick() { if (!Ready) { return; } try { if (!_hooked) { ZDOMan instance = ZDOMan.instance; instance.m_onZDODestroyed = (Action<ZDO>)Delegate.Remove(instance.m_onZDODestroyed, new Action<ZDO>(OnDestroyed)); ZDOMan instance2 = ZDOMan.instance; instance2.m_onZDODestroyed = (Action<ZDO>)Delegate.Combine(instance2.m_onZDODestroyed, new Action<ZDO>(OnDestroyed)); _hooked = true; } if (_state == null) { Load(); } BootSweep(); RegisterPeers(); try { Seizure.Tick(); } catch (Exception ex) { Plugin.Log.LogError((object)("Морской дракон: изъятие надгробий: " + ex)); } float realtimeSinceStartup = Time.realtimeSinceStartup; float dt = ((_lastFrame > 0f) ? Mathf.Min(2f, realtimeSinceStartup - _lastFrame) : 0f); _lastFrame = realtimeSinceStartup; if (_active != null) { Glide(dt); } if (!(Time.realtimeSinceStartup < _nextTick)) { _nextTick = Time.realtimeSinceStartup + 1f; Logic(Now); } } catch (Exception ex2) { Plugin.Log.LogError((object)("Морской дракон: " + ex2)); _nextTick = Time.realtimeSinceStartup + 10f; } } private static void Load() { string text = Path.Combine(Paths.ConfigPath, "sansara.SeaDragon"); Directory.CreateDirectory(text); string text2 = string.Concat(ZNet.instance.GetWorldName().Split(Path.GetInvalidFileNameChars())); _path = Path.Combine(text, text2 + ".state.txt"); List<string> list = new List<string>(); _state = (File.Exists(_path) ? DragonState.Parse(File.ReadAllText(_path), list) : new DragonState()); foreach (string item in list) { Plugin.Log.LogWarning((object)("Морской дракон: файл состояния: " + item)); } double now = Now; _state.NextCheckAt = DragonRules.Sane(now, _state.NextCheckAt, DragonConfig.Settings()); Save(); Plugin.Log.LogInfo((object)("Морской дракон: состояние " + Path.GetFileName(_path) + " — следующая проверка пролёта через " + $"{DragonRules.Minutes(_state.NextCheckAt - now)} мин, меток мести {_state.Marks.Count}, откатов {_state.LastRevenge.Count}; {DragonConfig.Describe()}.")); } private static void Save() { try { File.WriteAllText(_path, _state.Serialize()); } catch (Exception ex) { Plugin.Log.LogError((object)("Морской дракон: состояние не сохранено: " + ex.Message)); } } private static void BootSweep() { if (_booted || ZDOMan.instance.NrOfObjects() == 0) { return; } _booted = true; List<ZDO> list = AllDragons(); foreach (ZDO item in list) { Remove(item); } Plugin.Log.LogInfo((object)((list.Count == 0) ? "Морской дракон: после загрузки мира драконов нет." : $"Морской дракон: после загрузки мира убрано драконов: {list.Count}.")); } private static List<ZDO> AllDragons() { List<ZDO> list = new List<ZDO>(); int num = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative("SansaraSeaDragon", list, ref num)) { } return list; } private static void Logic(double now) { //IL_0100: Unknown result type (might be due to invalid IL or missing references) DragonSettings dragonSettings = DragonConfig.Settings(); List<RevengeMark> list = DragonRules.Expire(_state, now, dragonSettings); foreach (RevengeMark item in list) { Plugin.Log.LogInfo((object)$"Морской дракон: метка мести {item.Name} ({item.PlayerId}) снята — {DragonConfig.MarkHours.Value:0.#} ч без выхода в океан."); } if (list.Count > 0) { Save(); } if (_active != null) { Watch(now, dragonSettings); } else { if (!DragonConfig.Enabled.Value) { return; } List<PlayerInfo> source = Players(); foreach (RevengeMark mark in DragonRules.Due(_state, now)) { PlayerInfo playerInfo = source.FirstOrDefault((PlayerInfo x) => x.Id == mark.PlayerId); if (playerInfo != null && !playerInfo.Dead && playerInfo.Ship != null && OpenOcean(playerInfo.Ship.GetPosition())) { SpawnRevenge(now, playerInfo, "срок метки"); return; } } if (DragonRules.CheckDue(now, _state.NextCheckAt)) { _state.NextCheckAt = DragonRules.NextCheck(now, dragonSettings); Save(); List<PlayerInfo> list2 = source.Where((PlayerInfo p) => !p.Dead && p.Ship != null && OpenOcean(p.Ship.GetPosition())).ToList(); if (list2.Count == 0) { Wait("нет игроков на корабле в открытом океане"); } else if (!DragonRules.Roll(Rng.NextDouble(), dragonSettings.Chance)) { Wait($"шанс {dragonSettings.Chance:0.##} не выпал"); } else { SpawnFlyby(now, list2[DragonRules.Pick(list2.Count, Rng.NextDouble())], null); } } } } private static void Wait(string why) { if (why != _lastWait) { _lastWait = why; } Plugin.Log.LogInfo((object)$"Морской дракон: пролёта нет — {why}; следующая проверка через {DragonConfig.CheckMinutes.Value:0.#} мин."); } private static void Watch(double now, DragonSettings s) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03e1: Unknown result type (might be due to invalid IL or missing references) //IL_035a: 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_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) Active a = _active; ZDO zDO = ZDOMan.instance.GetZDO(a.Uid); if (zDO == null) { Plugin.Log.LogInfo((object)("Морской дракон: " + a.Tag + " пропал из мира.")); _active = null; Revoke(a); return; } if (!DragonConfig.Enabled.Value) { End(zDO, "выключен в настройках ([General] Enabled = false)"); return; } List<PlayerInfo> list = Players(); DragonMode dragonMode = DragonKeys.ModeOf(zDO); Vector3 pos = zDO.GetPosition(); NoteStrikers(zDO, a, list, now, s, dragonMode); if (!a.TestPoint && !list.Any((PlayerInfo p) => Utils.DistanceXZ(p.Pos, pos) <= 600f)) { End(zDO, $"рядом нет игроков ({600f:0} м)"); return; } switch (dragonMode) { case DragonMode.Revenge: { PlayerInfo playerInfo = list.FirstOrDefault((PlayerInfo p) => p.Id == a.TargetId); if (playerInfo?.Peer != null) { Seizure.Revenges.Peer(Loss.Ref(a.Uid), playerInfo.Peer.m_uid); } if (a.LeftAt > 0.0) { if (DragonRules.LeaveExpired(now, a.LeftAt, s)) { End(zDO, $"не улетел за {s.LeaveSeconds:0} с"); } else { OrderLeave(zDO, a, now, playerInfo?.Pos ?? pos); } return; } double offShipSince = a.OffShipSince; RevengeEnd revengeEnd = DragonRules.Verdict(now, a.StartedAt, playerInfo != null, playerInfo?.Dead ?? false, playerInfo != null && playerInfo.Ship != null, ref offShipSince, s); a.OffShipSince = offShipSince; if (revengeEnd != RevengeEnd.None) { Plugin.Log.LogInfo((object)("Морской дракон: месть " + a.TargetName + " окончена без победы — " + DragonRules.EndText(revengeEnd) + "; дракон улетает.")); if (playerInfo != null) { Message(playerInfo.Peer, "Ледяная вдова улетает: " + DragonRules.EndText(revengeEnd) + ".", (MessageType)((revengeEnd == RevengeEnd.OffenderDead) ? 1 : 2)); } OrderLeave(zDO, a, now, playerInfo?.Pos ?? pos); } else { if (playerInfo != null) { Confirm(a, playerInfo.Peer); } if (playerInfo != null && DragonConfig.PingSeconds.Value > 0f && Time.realtimeSinceStartup >= a.NextPing) { a.NextPing = Time.realtimeSinceStartup + DragonConfig.PingSeconds.Value; PingSender.Send(PingChannels.Key("seadragon", "revenge", a.Tag), "Ледяная вдова", pos, playerInfo.Peer, PingChannels.Detail("{dist}", "месть")); } } return; } case DragonMode.Flyby: if (a.Strikers.Count > 0 || zDO.GetBool(ZDOVars.s_aggravated, false)) { OrderLeave(zDO, a, now, DragonKeys.AnchorOf(zDO)); } break; } if (dragonMode == DragonMode.Leaving && a.LeftAt <= 0.0) { a.LeftAt = now; Plugin.Log.LogInfo((object)$"Морской дракон: {a.Tag} улетает (режим «улёт» в объекте, владелец {zDO.GetOwner()})."); } FlightNumbers n = DragonConfig.Flight(); Vec vec = DragonKeys.V(pos); Vec vec2 = DragonKeys.V(DragonKeys.AnchorOf(zDO)); Vec exit = DragonKeys.V(zDO.GetVec3(DragonKeys.Exit, pos)); if (FlightPlan.Done(dragonMode, zDO.GetInt(DragonKeys.Phase, 0), vec, vec2, exit, n)) { End(zDO, $"улетел ({Vec.DistXZ(vec, vec2):0} м от корабля)"); } else if (a.Kind == DragonMode.Flyby && DragonRules.FlybyExpired(now, a.StartedAt, s)) { End(zDO, $"предел пролёта {s.FlybySeconds:0} с"); } else if (DragonRules.LeaveExpired(now, a.LeftAt, s)) { End(zDO, $"улетает дольше {s.LeaveSeconds:0} с"); } } private static void NoteStrikers(ZDO zdo, Active a, List<PlayerInfo> players, double now, DragonSettings s, DragonMode mode) { foreach (PlayerInfo player in players) { if (player.Id == 0L || a.Strikers.ContainsKey(player.Name)) { continue; } int s_attackers = ZDOVars.s_attackers; if (zdo.GetBool(s_attackers + player.Name, false)) { a.Strikers[player.Name] = player.Id; if (a.Kind == DragonMode.Revenge) { Plugin.Log.LogInfo((object)("Морской дракон: " + player.Name + " ранил мстящего дракона (" + a.Tag + ").")); } else { OffenceResult offenceResult = DragonRules.Offend(_state, player.Id, player.Name, now, s, Rng.NextDouble()); Save(); RevengeMark revengeMark = _state.Mark(player.Id); Plugin.Log.LogInfo(offenceResult switch { OffenceResult.AlreadyMarked => "Морской дракон: " + player.Name + " ударил мирного дракона — метка мести уже есть.", OffenceResult.Marked => $"Морской дракон: {player.Name} ({player.Id}) ударил мирного дракона — месть через {DragonRules.Minutes(revengeMark.DueAt - now)} мин.", _ => $"Морской дракон: {player.Name} ударил мирного дракона — месть уже была за последние {s.CooldownHours:0.#} ч, метки нет.", }); } } } } private static void OrderLeave(ZDO zdo, Active a, double now, Vector3 away) { //IL_0045: 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_007f: Unknown result type (might be due to invalid IL or missing references) if (a.LeftAt <= 0.0) { a.LeftAt = now; } Revoke(a); long owner = zdo.GetOwner(); if (owner == 0L || owner == ZDOMan.GetSessionID() || !IsPeer(owner)) { zdo.SetOwner(ZDOMan.GetSessionID()); DragonKeys.SetLeaving(zdo, zdo.GetPosition(), away); } else if (Time.realtimeSinceStartup >= a.NextLeaveRpc && DragonKeys.ModeOf(zdo) != DragonMode.Leaving) { a.NextLeaveRpc = Time.realtimeSinceStartup + 5f; ZRoutedRpc.instance.InvokeRoutedRPC(owner, zdo.m_uid, "SansaraSeaDragon_Leave", Array.Empty<object>()); } } private static bool IsPeer(long uid) { return ZNet.instance.GetPeers().Any((ZNetPeer p) => p != null && p.m_uid == uid); } private static void Glide(float dt) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_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_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: 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_018d: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) Active active = _active; ZDO zDO = ZDOMan.instance.GetZDO(active.Uid); if (zDO == null) { return; } Observe(active, zDO); if (dt <= 0f) { return; } long owner = zDO.GetOwner(); long sessionID = ZDOMan.GetSessionID(); if (owner != 0L && owner != sessionID && IsPeer(owner)) { return; } if (owner != sessionID) { zDO.SetOwner(sessionID); } FlightNumbers n = DragonConfig.Flight(); Vector3 position = zDO.GetPosition(); Vec vec = DragonKeys.V(position); DragonMode dragonMode = DragonKeys.ModeOf(zDO); Vec target; if (dragonMode == DragonMode.Revenge) { ZDO val = OffenderCharacter(active.TargetId); if (val == null) { return; } Vector3 position2 = val.GetPosition(); if (Utils.DistanceXZ(position2, position) <= DragonConfig.EngageDistance.Value) { return; } target = FlightPlan.Above(DragonKeys.V(position2), n); } else { Vec anchor = DragonKeys.V(DragonKeys.AnchorOf(zDO)); int num = zDO.GetInt(DragonKeys.Phase, 0); if (dragonMode == DragonMode.Flyby && num == 0 && FlightPlan.Passed(vec, anchor, n)) { num = 1; zDO.Set(DragonKeys.Phase, 1, false); zDO.Set(DragonKeys.Exit, DragonKeys.U(FlightPlan.Exit(DragonKeys.V(zDO.GetVec3(DragonKeys.Start, position)), anchor, vec, n))); } target = FlightPlan.Target(dragonMode, num, anchor, DragonKeys.V(zDO.GetVec3(DragonKeys.Exit, position)), n); } Vec vec2 = FlightPlan.Glide(vec, target, DragonConfig.GlideSpeed.Value, dt); if (Vec.DistXZ(vec, vec2) > 0.01) { zDO.SetRotation(Quaternion.Euler(0f, (float)FlightPlan.Yaw(vec, vec2), 0f)); } zDO.SetPosition(DragonKeys.U(vec2)); } private static ZDO OffenderCharacter(long playerId) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { ZDO val = ((peer == null || ((ZDOID)(ref peer.m_characterID)).IsNone()) ? null : ZDOMan.instance.GetZDO(peer.m_characterID)); if (val != null && val.GetLong(ZDOVars.s_playerID, 0L) == playerId) { return val; } } return null; } private static void End(ZDO zdo, string why) { Active active = _active; _active = null; Revoke(active); Remove(zdo); Plugin.Log.LogInfo((object)("Морской дракон: " + active?.Tag + " убран — " + why + ".")); } private static void Remove(ZDO zdo) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) SilentRemovePatch.Silent.Add(zdo.m_uid); zdo.SetOwner(ZDOMan.GetSessionID()); ZDOMan.instance.DestroyZDO(zdo); } private static void OnDestroyed(ZDO zdo) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_02ed: Unknown result type (might be due to invalid IL or missing references) try { if (zdo == null || zdo.GetPrefab() != Prefab.Hash) { return; } bool num = SilentRemovePatch.Silent.Remove(zdo.m_uid); Active active = _active; if (num || active == null || zdo.m_uid != active.Uid) { return; } _active = null; Revoke(active); double now = Now; List<PlayerInfo> list = Players(); foreach (PlayerInfo item in list) { if (item.Id != 0L) { int s_attackers = ZDOVars.s_attackers; if (zdo.GetBool(s_attackers + item.Name, false)) { active.Strikers[item.Name] = item.Id; } } } DragonMode dragonMode = DragonKeys.ModeOf(zdo); Plugin.Log.LogInfo((object)($"Морской дракон: {active.Tag} уничтожен не сервером (режим {dragonMode}, здоровье {zdo.GetFloat(ZDOVars.s_health, -1f):0}, " + string.Format("ударивших {0}): {1}.", zdo.GetInt(ZDOVars.s_attackers, 0), string.Join(", ", active.Strikers.Keys.ToArray())))); if (active.Kind != DragonMode.Revenge) { DragonSettings s = DragonConfig.Settings(); foreach (KeyValuePair<string, long> striker in active.Strikers) { DragonRules.Offend(_state, striker.Value, striker.Key, now, s, Rng.NextDouble()); } Save(); Plugin.Log.LogInfo((object)"Морской дракон: убит мирный дракон — без награды, ударившим поставлены метки мести."); return; } if (active.Strikers.Count == 0) { Plugin.Log.LogInfo((object)"Морской дракон: мстящий дракон пропал без отметок атакующих — награды нет."); return; } Observe(active, zdo); bool flag = !float.IsNaN(active.Lowest) && active.Lowest <= 0f; bool confirmed = DragonRules.DeathConfirmed(now, active.ReportAt, 10.0, flag); double num2 = DragonRules.DamageShare(active.MaxHealth, float.IsNaN(active.Lowest) ? active.MaxHealth : active.Lowest); Vector3 position = zdo.GetPosition(); float value = DragonConfig.CreditDistance.Value; List<KeyValuePair<string, long>> list2 = new List<KeyValuePair<string, long>>(); List<string> list3 = new List<string>(); foreach (KeyValuePair<string, long> st in active.Strikers.OrderBy<KeyValuePair<string, long>, string>((KeyValuePair<string, long> h) => h.Key, StringComparer.Ordinal)) { PlayerInfo playerInfo = list.FirstOrDefault((PlayerInfo x) => x.Id == st.Value); float num3 = ((playerInfo != null) ? Utils.DistanceXZ(playerInfo.Pos, position) : float.PositiveInfinity); if (DragonRules.Credited(playerInfo != null, playerInfo?.Dead ?? false, num3, value)) { list2.Add(st); } else { list3.Add(st.Key + ((playerInfo == null) ? " (не в игре)" : (playerInfo.Dead ? " (мёртв)" : $" ({num3:0} м)"))); } } bool cheated = active.ReportCheated || zdo.GetInt(ZDOVars.s_cheated, 0) == 2; int value2 = DragonConfig.MinHealthSteps.Value; float value3 = DragonConfig.MinFightSeconds.Value; string text = DragonRules.NotGradualReason(active.Track, now, value2, value3); KillVerdict killVerdict = DragonRules.Judge(confirmed, cheated, text == null, num2, DragonConfig.MinDamageShare.Value, list2.Count); int num4 = ((active.Track != null) ? active.Track.Steps : 0); double num5 = ((active.Track != null) ? active.Track.FightSeconds(now) : 0.0); Plugin.Log.LogInfo((object)("Морской дракон: зачёт " + active.Tag + " — " + DragonRules.VerdictText(killVerdict) + ((killVerdict == KillVerdict.NotGradual) ? (" (" + text + ")") : "") + ": отчёт о гибели " + ((active.ReportAt > 0.0) ? $"от {active.ReportBy} за {now - active.ReportAt:0.#} с до удаления" : "нет") + string.Format(", нулевое здоровье {0}, урон по данным сервера {1:P0} (наименьшее здоровье ", flag ? "видно" : "не видно", num2) + string.Format("{0} из {1:0}, порог {2:P0}), ", float.IsNaN(active.Lowest) ? "—" : active.Lowest.ToString("0"), active.MaxHealth, DragonConfig.MinDamageShare.Value) + $"снижений здоровья {num4} (нужно {value2}) за {num5:0.#} с от первого урона (нужно {value3:0.#}), " + $"в зачёт {list2.Count} из {active.Strikers.Count}" + ((list3.Count > 0) ? string.Format(", не в зачёт (предел {0:0} м): {1}", value, string.Join(", ", list3.ToArray())) : "") + ".")); if (killVerdict != KillVerdict.Victory) { Plugin.Log.LogInfo((object)("Морской дракон: месть " + active.TargetName + " — дракон убран без награды (" + DragonRules.VerdictText(killVerdict) + ").")); } else { Victory(active, now, list2); } } catch (Exception ex) { Plugin.Log.LogError((object)("Морской дракон: удаление объекта: " + ex)); } } private static void Victory(Active a, double now, List<KeyValuePair<string, long>> hunters) { List<string> list = new List<string>(); foreach (KeyValuePair<string, long> hunter in hunters) { if (Reward(hunter.Value, a.StartedAt)) { list.Add(hunter.Key); } } string text = string.Join(", ", hunters.Select((KeyValuePair<string, long> h) => h.Key).ToArray()); MessageAll("Месть отражена: Ледяная вдова повержена! (" + text + ")"); Plugin.Log.LogInfo((object)("Морской дракон: месть " + a.TargetName + " отражена — дракон убит; участники " + text + "; награждены " + string.Join(", ", list.ToArray()) + ".")); WriteChronicle(now, hunters); int num = DeedBus.Publish("seadragon", "SansaraSeaDragon", 4, "victory", hunters.Select((KeyValuePair<string, long> h) => h.Value).ToArray(), hunters.Select((KeyValuePair<string, long> h) => h.Key).ToArray(), delegate(string m) { Plugin.Log.LogWarning((object)m); }); Plugin.Log.LogInfo((object)$"Морской дракон: деяние «Месть отражена» опубликовано, подписчиков {num}."); } private static void WriteChronicle(double now, List<KeyValuePair<string, long>> hunters) { try { ChronicleEntry chronicleEntry = new ChronicleEntry { Time = now, Date = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), Kind = "hunt", Id = "SansaraSeaDragon", Result = "victory", Players = hunters.Select((KeyValuePair<string, long> h) => new ChroniclePlayer(h.Value, h.Key)).ToList() }; ChronicleFile.Append(ChronicleFile.PathFor(Paths.ConfigPath, ZNet.instance.GetWorldName()), chronicleEntry); Plugin.Log.LogInfo((object)$"Морской дракон: летопись — «месть отражена» ({chronicleEntry.Kind}/{chronicleEntry.Id}, участников {chronicleEntry.Players.Count})."); } catch (Exception ex) { Plugin.Log.LogWarning((object)("Морской дракон: летопись не записана: " + ex.Message)); } } private static bool Reward(long playerId, double startedAt) { string[] array = DragonRules.Pool(DragonConfig.RewardPool.Value); int num = Mathf.Clamp(DragonConfig.RewardCount.Value, 0, 10); if (array.Length == 0 || num == 0) { Plugin.Log.LogWarning((object)$"Морской дракон: награда игроку {playerId} не выдана — [Rewards] RewardPool пуст или RewardCount = 0."); return false; } if (!_enqueueChecked) { _enqueueChecked = true; Type type = AccessTools.TypeByName("EventRewards.ExternalRewards"); _enqueue = ((type == null) ? null : AccessTools.Method(type, "Enqueue", new Type[3] { typeof(long), typeof(string), typeof(string) }, (Type[])null)); } if (_enqueue == null) { Plugin.Log.LogError((object)$"Морской дракон: награда игроку {playerId} не выдана — нет Event Rewards (ExternalRewards.Enqueue)."); return false; } bool result = false; int[] array2 = DragonRules.PickDistinct(array.Length, num, Rng.Next); for (int i = 1; i <= num; i++) { string text = array[array2[i - 1]]; string text2 = DragonRules.Reason(startedAt, i); string text3 = (string)_enqueue.Invoke(null, new object[3] { playerId, text, text2 }); if (text3 != null) { Plugin.Log.LogError((object)$"Морской дракон: награда {text} игроку {playerId} не выдана: {text3}."); continue; } result = true; Plugin.Log.LogInfo((object)$"Морской дракон: игроку {playerId} поставлена награда {text} ({text2})."); } return result; } private static void Observe(Active a, ZDO zdo) { if (a.Track == null) { a.Track = new HealthTrack(a.MaxHealth); } a.Track.Observe(zdo.GetFloat(ZDOVars.s_health, float.NaN), Now); } private static void RegisterPeers() { HashSet<ZRpc> live = new HashSet<ZRpc>(); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer?.m_rpc != null) { live.Add(peer.m_rpc); if (Registered.Add(peer.m_rpc)) { peer.m_rpc.Register<ZPackage>("SansaraSeaDragon_Death", (Action<ZRpc, ZPackage>)OnDeathRpc); peer.m_rpc.Register<ZPackage>("SansaraSeaDragon_Loss", (Action<ZRpc, ZPackage>)OnLossRpc); } } } Registered.RemoveWhere((ZRpc r) => !live.Contains(r)); } private static void OnDeathRpc(ZRpc rpc, ZPackage pkg) { try { ZNetPeer val = ZNet.instance.GetPeers().Find((ZNetPeer p) => p != null && p.m_rpc == rpc); if (val != null) { OnDeathReport(val.m_uid, val.m_playerName ?? "?", pkg); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Морской дракон: отчёт о гибели: " + ex.Message)); } } private static void OnLossRpc(ZRpc rpc, ZPackage pkg) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) try { ZNetPeer val = ZNet.instance.GetPeers().Find((ZNetPeer p) => p != null && p.m_rpc == rpc); if (val != null) { ZDO val2 = (((ZDOID)(ref val.m_characterID)).IsNone() ? null : ZDOMan.instance.GetZDO(val.m_characterID)); OnLossReport(val.m_playerName ?? "?", (val2 != null) ? val2.GetLong(ZDOVars.s_playerID, 0L) : 0, pkg); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Морской дракон: отчёт об утрате: " + ex.Message)); } } internal unsafe static void OnLossReport(string playerName, long playerId, ZPackage pkg) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: 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) int num = pkg.ReadInt(); if (num != 2 && num != 1) { Plugin.Log.LogInfo((object)$"Морской дракон: отчёт {playerName} об утрате инвентаря отклонён — версия {num}."); return; } ZDOID id = pkg.ReadZDOID(); int items = Math.Max(0, pkg.ReadInt()); int rewards = Math.Max(0, pkg.ReadInt()); string doubt = RevengeDoubt(Loss.Ref(id), playerId); if (num == 1) { Plugin.Log.LogInfo((object)(LossRules.LogLine(playerName, items, rewards, doubt) + " Клиент до 0.1.5: вещи удалены, надгробия нет.")); return; } ZDOID grave = pkg.ReadZDOID(); Plugin.Log.LogInfo((object)LossRules.SeizeReportLine(playerName, items, rewards, ((object)(*(ZDOID*)(&grave))/*cast due to .constrained prefix*/).ToString(), doubt)); Seizure.Expect(grave, playerName, playerId); } internal static string RevengeDoubt(DragonRef dragon, long playerId) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) Active active = _active; bool flag = active != null && active.Kind == DragonMode.Revenge; ZDOID id = (flag ? active.Uid : _endedUid); long revengeTarget = (flag ? active.TargetId : _endedTarget); double endedAgo = ((flag || ((ZDOID)(ref _endedUid)).IsNone()) ? (-1.0) : (Now - _endedAt)); return LossRules.ReportDoubt(dragon, Loss.Ref(id), revengeTarget, flag, endedAgo, playerId); } internal static void OnDeathReport(long sender, string senderName, ZPackage pkg) { //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_0082: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) if (!Ready || _state == null) { return; } int num = pkg.ReadInt(); ZDOID val = pkg.ReadZDOID(); float num2 = pkg.ReadSingle(); bool flag = pkg.ReadBool(); int num3 = Math.Max(0, Math.Min(64, pkg.ReadInt())); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); for (int i = 0; i < num3; i++) { hashSet.Add(pkg.ReadString()); } Active a = _active; ZDO zDO = ZDOMan.instance.GetZDO(val); string text = ((num != 1) ? $"версия отчёта {num}" : ((a == null || val != a.Uid || zDO == null) ? "не текущий дракон" : ((zDO.GetOwner() != sender) ? $"отправитель не владелец (владелец {zDO.GetOwner()})" : ((num2 > 0f) ? $"здоровье {num2:0} > 0" : null)))); if (text != null) { Plugin.Log.LogInfo((object)$"Морской дракон: отчёт {senderName} о гибели {val} отклонён — {text}."); return; } Observe(a, zDO); a.ReportAt = Now; a.ReportBy = senderName; a.ReportCheated = a.ReportCheated || flag; string[] array = hashSet.Where((string x) => !a.Strikers.ContainsKey(x)).OrderBy<string, string>((string x) => x, StringComparer.Ordinal).ToArray(); Plugin.Log.LogInfo((object)($"Морской дракон: {senderName} (владелец) сообщил о гибели {a.Tag}: здоровье {num2:0}, флаг читов {flag}, " + $"ударивших в отчёте {hashSet.Count} (не учитываются; сервер видел {a.Strikers.Count}" + ((array.Length != 0) ? (", нет в отметках сервера: " + string.Join(", ", array)) : "") + ").")); } private static void Confirm(Active a, ZNetPeer peer) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) if (a != null && a.Kind == DragonMode.Revenge && !a.Revoked && peer?.m_rpc != null && !(Time.realtimeSinceStartup < a.NextConfirm)) { a.NextConfirm = Time.realtimeSinceStartup + 5f; Send(peer, a.Uid, a.TargetId); if (a.ConfirmPeer != peer.m_uid) { Plugin.Log.LogInfo((object)($"Морской дракон: {a.TargetName} — подтверждение мести {a.Uid} отправлено" + ((a.ConfirmPeer != 0L) ? " (новое соединение)" : "") + $", повтор каждые {5.0:0} с.")); a.ConfirmPeer = peer.m_uid; } } } private static void Revoke(Active a) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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) if (a == null || a.Kind != DragonMode.Revenge || a.Revoked) { return; } a.Revoked = true; _endedUid = a.Uid; _endedTarget = a.TargetId; _endedAt = Now; Seizure.Revenges.End(Loss.Ref(a.Uid), Now, ZNet.instance.GetTime().Ticks); try { ZNetPeer val = Players().FirstOrDefault((PlayerInfo p) => p.Id == a.TargetId)?.Peer; if (val?.m_rpc != null) { Send(val, ZDOID.None, a.TargetId); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Морской дракон: конец подтверждения мести: " + ex.Message)); } } private static void Send(ZNetPeer peer, ZDOID dragon, long target) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000e: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(1); val.Write(dragon); val.Write(target); peer.m_rpc.Invoke("SansaraSeaDragon_Revenge", new object[1] { val }); } internal static ZDO NewZdo(Vector3 pos, int hash, string name) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) GameObject prefab = ZNetScene.instance.GetPrefab(hash); ZNetView val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ZNetView>() : null); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("префаба " + name + " нет в ZNetScene"); } object obj = EwpSkip?.GetValue(null); ZDO val2; try { EwpSkip?.SetValue(null, true); val2 = ZDOMan.instance.CreateNewZDO(pos, hash); } finally { if (obj != null) { EwpSkip.SetValue(null, obj); } } val2.Persistent = true; val2.Type = val.m_type; val2.Distant = val.m_distant; val2.SetPrefab(hash); return val2; } private static ZDO Create(Vector3 pos, Vector3 lookAt, DragonMode mode, string tag) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_00cd: Unknown result type (might be due to invalid IL or missing references) ZDO obj = NewZdo(pos, Prefab.Hash, "SansaraSeaDragon"); obj.SetRotation(Quaternion.Euler(0f, (float)FlightPlan.Yaw(DragonKeys.V(pos), DragonKeys.V(lookAt)), 0f)); obj.Set(ZDOVars.s_level, 1, false); float num = DragonConfig.Health.Value; if (Game.m_worldLevel > 0 && (Object)(object)Game.instance != (Object)null) { num *= (float)Game.m_worldLevel * Game.instance.m_worldLevelEnemyHPMultiplier; } obj.Set(ZDOVars.s_maxHealth, num); obj.Set(ZDOVars.s_health, num); obj.Set(ZDOVars.s_spawnTime, ZNet.instance.GetTime().Ticks); obj.Set(DragonKeys.Mode, (int)mode, false); obj.Set(DragonKeys.Phase, 0, false); obj.Set(DragonKeys.Start, pos); obj.Set(DragonKeys.Tag, tag); return obj; } private static string NewTag(string kind, double now) { return kind + ":" + ((long)now).ToString(CultureInfo.InvariantCulture); } private static string SpawnFlyby(double now, PlayerInfo p, Vector3? testAnchor) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_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_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_0221: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) FlightNumbers n = DragonConfig.Flight(); Vector3 val = (Vector3)(((??)testAnchor) ?? p.Ship.GetPosition()); Vec anchor = DragonKeys.V(val); Vec vec = FlightPlan.StartPoint(anchor, Rng.NextDouble() * 2.0 * Math.PI, DragonConfig.ApproachDistance.Value, n); string text = NewTag("flyby", now); ZDO val2 = Create(DragonKeys.U(vec), val, DragonMode.Flyby, text); val2.Set(DragonKeys.Anchor, val); if (p != null && p.Ship != null && !testAnchor.HasValue) { val2.Set(DragonKeys.ShipUser, ((ZDOID)(ref p.Ship.m_uid)).UserID); val2.Set(DragonKeys.ShipId, (int)((ZDOID)(ref p.Ship.m_uid)).ID, false); } val2.Set(DragonKeys.Exit, DragonKeys.U(FlightPlan.Exit(vec, anchor, vec, n))); _active = new Active { Uid = val2.m_uid, Kind = DragonMode.Flyby, Tag = text, StartedAt = now, TargetId = (p?.Id ?? 0), TargetName = (p?.Name ?? ""), TestPoint = testAnchor.HasValue, MaxHealth = val2.GetFloat(ZDOVars.s_maxHealth, 0f) }; string text2 = ((p != null) ? p.Name : "точка"); Plugin.Log.LogInfo((object)("Морской дракон: пролёт " + text + " — над " + ((!testAnchor.HasValue) ? ("кораблём " + SeaPrefabName(p.Ship) + " игрока " + text2) : "точкой") + " " + $"({val.x:0}, {val.z:0}), заход с {DragonConfig.ApproachDistance.Value:0} м из {vec}, объект {val2.m_uid}.")); if (p != null) { Message(p.Peer, "Над морем показалась Ледяная вдова…", (MessageType)2); } return string.Format("пролёт {0} над {1} ({2:0}, {3:0}), объект {4}", text, (p != null) ? text2 : "точкой", val.x, val.z, val2.m_uid); } private static string SpawnRevenge(double now, PlayerInfo p, string why) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) FlightNumbers n = DragonConfig.Flight(); Vec vec = FlightPlan.StartPoint(DragonKeys.V(p.Pos), Rng.NextDouble() * 2.0 * Math.PI, DragonConfig.SpawnDistance.Value, n); string text = NewTag("revenge", now); ZDO val = Create(DragonKeys.U(vec), p.Pos, DragonMode.Revenge, text); val.Set(DragonKeys.Anchor, p.Pos); val.Set(DragonKeys.Target, p.Id); val.Set(ZDOVars.s_aggravated, true); val.Set(ZDOVars.s_huntPlayer, true); DragonRules.Started(_state, p.Id, now); Save(); _active = new Active { Uid = val.m_uid, Kind = DragonMode.Revenge, Tag = text, StartedAt = now, TargetId = p.Id, TargetName = p.Name, MaxHealth = val.GetFloat(ZDOVars.s_maxHealth, 0f) }; Plugin.Log.LogInfo((object)($"Морской дракон: месть {text} ({why}) — {p.Name} ({p.Id}) на корабле в ({p.Pos.x:0}, {p.Pos.z:0}), дракон в {vec}, объект {val.m_uid}; " + $"следующая месть этому игроку не раньше чем через {DragonConfig.CooldownHours.Value:0.#} ч.")); Seizure.Revenges.Start(Loss.Ref(val.m_uid), p.Id, p.Name, now, ZNet.instance.GetTime().Ticks); if (p.Peer != null) { Seizure.Revenges.Peer(Loss.Ref(val.m_uid), p.Peer.m_uid); } Confirm(_active, p.Peer); Message(p.Peer, "Ледяная вдова вернулась за тобой — месть за удар!", (MessageType)2); return $"месть {text}: {p.Name}, дракон в {vec}, объект {val.m_uid}"; } private static string SeaPrefabName(ZDO ship) { GameObject val = ((ship != null) ? ZNetScene.instance.GetPrefab(ship.GetPrefab()) : null); if (!((Object)(object)val != (Object)null)) { return "?"; } return ((Object)val).name; } private static List<PlayerInfo> Players() { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) List<PlayerInfo> list = new List<PlayerInfo>(); foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer?.m_socket != null && !string.IsNullOrEmpty(peer.m_playerName) && !((ZDOID)(ref peer.m_characterID)).IsNone()) { ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); if (zDO != null) { Vector3 position = zDO.GetPosition(); list.Add(new PlayerInfo { Peer = peer, Id = zDO.GetLong(ZDOVars.s_playerID, 0L), Name = peer.m_playerName, Pos = position, Ship = ShipUnder(position), Dead = zDO.GetBool(ZDOVars.s_dead, false) }); } } } return list; } private static ZDO ShipUnder(Vector3 pos) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) Found.Clear(); ZDOMan.instance.FindSectorObjects(ZoneSystem.GetZone(pos), new SimulationDistance(1, 0, true), Found, (List<ZDO>)null); foreach (ZDO item in Found) { if (ShipHashes.Contains(item.GetPrefab())) { HullBox hull = HullOf(item.GetPrefab()); Vector3 val = pos - item.GetPosition(); float x = val.x; float y = val.y; float z = val.z; Quaternion rotation = item.GetRotation(); if (Hull.OnBoard(hull, x, y, z, ((Quaternion)(ref rotation)).eulerAngles.y)) { return item; } } } return null; } private static HullBox HullOf(int prefabHash) { //IL_005c: Unknown result type (might be due to inva