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 ALIVE Server v0.61.0
plugins/ALIVE.Core.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core.Abstractions; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content; using ALIVE.Core.Content.Conditions; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Currencies; using ALIVE.Core.Content.Dialogue; using ALIVE.Core.Content.Economy; using ALIVE.Core.Content.Effects; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Json; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Content.Packs; using ALIVE.Core.Content.Pricing; using ALIVE.Core.Content.Quests; using ALIVE.Core.Content.Schema; using ALIVE.Core.Content.Shops; using ALIVE.Core.Content.Trades; using ALIVE.Core.Content.Validation; using ALIVE.Core.Diagnostics; using ALIVE.Core.Economy; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [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("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Core")] [assembly: InternalsVisibleTo("ALIVE.Core.Tests")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } } namespace ALIVE.Core { public static class AliveCoreVersion { public static readonly string Value = ReadFromAssembly(); private static string ReadFromAssembly() { return typeof(AliveCoreVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0"; } } public static class AliveGuid { public const string Server = "com.imaginaryrealms.alive.server"; public const string Player = "com.imaginaryrealms.alive.client.player"; public const string Admin = "com.imaginaryrealms.alive.client.admin"; public static bool IsPlayer(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.player"); } return true; } public static bool IsAdmin(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.admin")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } public static bool IsAlive(string? id) { if (!IsPlayer(id) && !IsAdmin(id) && !Is(id, "com.imaginaryrealms.alive.server")) { return Is(id, "net.winterwolf.alive.server"); } return true; } public static bool IsOld(string? id) { if (!Is(id, "net.winterwolf.alive.server") && !Is(id, "net.winterwolf.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } private static bool Is(string? id, string guid) { return string.Equals(id, guid, StringComparison.Ordinal); } } public static class AliveOldGuid { public const string Server = "net.winterwolf.alive.server"; public const string Player = "net.winterwolf.alive.client.player"; public const string Admin = "net.winterwolf.alive.client.admin"; } public static class SettingsCarry { public static string? FromOldId(string configFolder, string oldId, string newId) { if (string.IsNullOrEmpty(configFolder) || string.IsNullOrEmpty(oldId) || string.IsNullOrEmpty(newId)) { return null; } string text = Path.Combine(configFolder, newId + ".cfg"); string text2 = Path.Combine(configFolder, oldId + ".cfg"); if (File.Exists(text) || !File.Exists(text2)) { return null; } File.Copy(text2, text, overwrite: false); return "settings carried over from " + oldId + ".cfg to " + newId + ".cfg, as ALIVE's id changed in 0.61.0. The old file is no longer read and may be deleted."; } } public static class OldCopies { public static readonly Version FirstWithNewIds = new Version(0, 61, 0); private static readonly string[] PluginFiles = new string[3] { "ALIVE.Server.dll", "ALIVE.Client.Player.dll", "ALIVE.Client.Admin.dll" }; public static IReadOnlyList<string> Find(string pluginFolder, Func<string, Version?> versionOf) { if (versionOf == null) { throw new ArgumentNullException("versionOf"); } List<string> list = new List<string>(); if (string.IsNullOrEmpty(pluginFolder) || !Directory.Exists(pluginFolder)) { return list; } string[] pluginFiles = PluginFiles; foreach (string searchPattern in pluginFiles) { IEnumerable<string> files; try { files = Directory.GetFiles(pluginFolder, searchPattern, SearchOption.AllDirectories); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { continue; } foreach (string item in files) { Version version = versionOf(item); if (version != null && version < FirstWithNewIds) { list.Add(item); } } } list.Sort(StringComparer.OrdinalIgnoreCase); return list; } public static Version? VersionOfFile(string path) { try { return AssemblyName.GetAssemblyName(path).Version; } catch (Exception ex) when (ex is IOException || ex is BadImageFormatException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is SecurityException) { return null; } } public static string Refusal(string plugin, string version, IReadOnlyList<string> copies) { return plugin + " " + version + " is not starting: an older copy of ALIVE (from before 0.61.0, when its id was net.winterwolf.alive.*) is still in BepInEx/plugins: " + string.Join("; ", copies ?? Array.Empty<string>()) + ". Delete that copy's folder, keep the one your mod manager installed, and start again."; } } public static class AliveNames { public const string Server = "ALIVE Server"; public const string Player = "ALIVE Player"; public const string Admin = "ALIVE Admin"; } public static class AliveWorld { public const string Prefab = "ALIVE_Signpost"; public const string BasePrefab = "piece_banner01"; public const string FallbackPrefab = "sign"; public const string PersonPrefab = "ALIVE_Villager"; public const string PersonBase = "Player"; public const string ModelPrefab = "ALIVE_Model"; public const string ModelBase = "piece_chest_wood"; public const string DvergrShape = "Dverger"; public const string ShapeKey = "alive_shape"; public const string TillPrefab = "ALIVE_Till"; public const string TillBase = "piece_chest_wood"; public const string TillKey = "alive_till"; public const int TillWidth = 8; public const int TillHeight = 4; public const string SubtitleKey = "alive_subtitle"; public const string ModelKey = "alive_model"; public const string HairKey = "alive_hair"; public const string BeardKey = "alive_beard"; public const string SkinKey = "alive_skin"; public const string HairColorKey = "alive_hair_color"; public const string ScaleKey = "alive_scale"; public const string FaceKey = "alive_face"; public const string EquipmentKeyPrefix = "alive_eq_"; public const string EquipmentColorKeyPrefix = "alive_eqc_"; public const string NpcKey = "alive_npc"; public const string NameKey = "alive_name"; public const string PromptKey = "alive_prompt"; public const string HoverKey = "alive_hover"; public const string NoUseKey = "alive_nouse"; public const string LifeKey = "alive_life"; public const string LifeKey2 = "alive_life2"; public const string LifeKey3 = "alive_life3"; public const string LifeKey4 = "alive_life4"; public const string HomeKey = "alive_home"; public const string HomeTurnKey = "alive_home_turn"; public const string LabelShowKey = "alive_label"; public const string LabelTextKey = "alive_label_text"; public const string LabelSubKey = "alive_label_sub"; public const string LabelColorKey = "alive_label_color"; public const string LabelSubColorKey = "alive_label_subcolor"; public const string LabelSizeKey = "alive_label_size"; public const string LabelHeightKey = "alive_label_height"; public const string LabelRangeKey = "alive_label_range"; public const string LabelStyleKey = "alive_label_style"; public const int LabelBold = 1; public const int LabelItalic = 2; public const int LabelOutline = 4; public const string PlacementKey = "alive_placement"; public const string HammerPrefab = "ALIVE_NpcHammer"; public const string HammerBase = "Hammer"; public const string BoardPiecePrefab = "ALIVE_JobBoard"; public const string BoardPieceBase = "sign"; public const string CreatureKey = "alive_creature"; public const string CreatureSpawnKey = "alive_spawn"; public const string CreatureFirstKey = "alive_cr_uid"; public const string CreatureDamageKey = "alive_cr_damage"; public const string CreatureScaleKey = "alive_cr_scale"; public const string CreatureResistKey = "alive_cr_resist"; public const string CreatureFactionKey = "alive_cr_faction"; public const string CreaturePassiveKey = "alive_cr_passive"; public const string CreatureAngryKey = "alive_cr_angry"; public const string CreatureNoDropsKey = "alive_cr_nodrops"; public const string CreatureColorsKey = "alive_cr_colors"; public const string AltarKey = "alive_altar"; public const string SentryKey = "alive_sentry"; public const string FightKey = "alive_fight"; public const string FightWithKey = "alive_fight_with"; public const string DownKey = "alive_down_until"; public const string SentryHealthKey = "alive_sentry_hp"; public const string SentryRestKey = "alive_sentry_rest"; public const string SentryPrefab = "ALIVE_Sentry"; public const string CreatureNoEliteKey = "alive_cr_noelite"; public const string SentryOfKey = "alive_sentry_of"; public const string FightFromKey = "alive_fight_from"; public const string FightKitKey = "alive_fight_kit"; public const string FightDoneKey = "alive_fight_done"; } } namespace ALIVE.Core.Web { public sealed class LocalHttpServer : IDisposable { public const int MaxHeadBytes = 16384; public const int MaxBodyBytes = 4194304; public const int MaxConnections = 8; private const int TimeoutMs = 15000; private readonly Func<LocalRequest, LocalResponse> _handle; private readonly IAliveLog _log; private TcpListener? _listener; private int _open; private volatile bool _stopping; private static readonly string[] LineBreak = new string[1] { "\r\n" }; public int Port { get; private set; } public LocalHttpServer(Func<LocalRequest, LocalResponse> handle, IAliveLog log) { _handle = handle ?? throw new ArgumentNullException("handle"); _log = log ?? throw new ArgumentNullException("log"); } public void Start(int port) { if (_listener != null) { throw new InvalidOperationException("The editor's server is already listening."); } TcpListener tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(16); _listener = tcpListener; Port = ((IPEndPoint)tcpListener.LocalEndpoint).Port; Thread thread = new Thread(AcceptLoop); thread.IsBackground = true; thread.Name = "ALIVE web editor"; thread.Start(); } public void Dispose() { _stopping = true; try { _listener?.Stop(); } catch (SocketException) { } _listener = null; } private void AcceptLoop() { while (!_stopping) { TcpClient client; try { TcpListener listener = _listener; if (listener == null) { break; } client = listener.AcceptTcpClient(); } catch (Exception) when (_stopping) { break; } catch (Exception ex2) { _log.Warning("ALIVE web editor: a connection could not be taken: " + ex2.Message); continue; } if (Interlocked.Increment(ref _open) > 8) { Interlocked.Decrement(ref _open); client.Close(); } else { ThreadPool.QueueUserWorkItem(delegate { Serve(client); }); } } } private void Serve(TcpClient client) { try { client.ReceiveTimeout = 15000; client.SendTimeout = 15000; using (client) { using NetworkStream stream = client.GetStream(); string refusal; LocalRequest localRequest = Read(stream, out refusal); LocalResponse response; if (localRequest == null) { response = LocalResponse.Text(400, refusal ?? "That request could not be read."); } else { try { response = _handle(localRequest); } catch (Exception exception) { _log.Failure("ALIVE web editor: answering " + localRequest.Method + " " + localRequest.Path + " failed.", exception); response = LocalResponse.Text(500, "Something went wrong on the server; its log says what."); } } Write(stream, response); } } catch (IOException) { } catch (SocketException) { } catch (ObjectDisposedException) { } finally { Interlocked.Decrement(ref _open); } } public static LocalRequest? Read(Stream stream, out string? refusal) { refusal = null; List<byte> list = new List<byte>(1024); checked { while (!EndsTheHead(list)) { int num = stream.ReadByte(); if (num < 0) { refusal = "The request ended early."; return null; } list.Add((byte)num); if (list.Count > 16384) { refusal = "The request's headers are too long."; return null; } } string[] array = Encoding.ASCII.GetString(list.ToArray(), 0, list.Count - 4).Split(LineBreak, StringSplitOptions.None); string[] array2 = array[0].Split(new char[1] { ' ' }); if (array2.Length != 3 || !array2[2].StartsWith("HTTP/1.", StringComparison.Ordinal)) { refusal = "That is not an HTTP request."; return null; } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < array.Length; i++) { int num2 = array[i].IndexOf(':'); if (num2 > 0) { string key = array[i].Substring(0, num2).Trim(); string text = array[i].Substring(num2 + 1).Trim(); dictionary[key] = (dictionary.TryGetValue(key, out var value) ? (value + ", " + text) : text); } } int result = 0; if (dictionary.TryGetValue("Content-Length", out var value2) && (!int.TryParse(value2, NumberStyles.None, CultureInfo.InvariantCulture, out result) || result > 4194304)) { refusal = "The request's body is too large."; return null; } if (dictionary.ContainsKey("Transfer-Encoding")) { refusal = "Chunked requests are not taken; send a Content-Length."; return null; } byte[] array3 = new byte[result]; int num3; for (int j = 0; j < result; j += num3) { num3 = stream.Read(array3, j, result - j); if (num3 <= 0) { refusal = "The request's body ended early."; return null; } } string text2 = array2[1]; int num4 = text2.IndexOf('?'); string stringToUnescape = ((num4 < 0) ? text2 : text2.Substring(0, num4)); return new LocalRequest(array2[0].ToUpperInvariant(), Uri.UnescapeDataString(stringToUnescape), Query((num4 < 0) ? string.Empty : text2.Substring(num4 + 1)), dictionary, Encoding.UTF8.GetString(array3)); } } private static bool EndsTheHead(List<byte> head) { int count = head.Count; checked { if (count >= 4 && head[count - 4] == 13 && head[count - 3] == 10 && head[count - 2] == 13) { return head[count - 1] == 10; } return false; } } private static Dictionary<string, string> Query(string query) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); string[] array = query.Split(new char[1] { '&' }); foreach (string text in array) { if (text.Length != 0) { int num = text.IndexOf('='); string key = Uri.UnescapeDataString(((num < 0) ? text : text.Substring(0, num)).Replace('+', ' ')); string value = ((num < 0) ? string.Empty : Uri.UnescapeDataString(text.Substring(checked(num + 1)).Replace('+', ' '))); dictionary[key] = value; } } return dictionary; } private static void Write(Stream stream, LocalResponse response) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("HTTP/1.1 ").Append(response.Status.ToString(CultureInfo.InvariantCulture)).Append(' ') .Append(Reason(response.Status)) .Append("\r\n"); stringBuilder.Append("Content-Type: ").Append(response.ContentType).Append("\r\n"); stringBuilder.Append("Content-Length: ").Append(response.Bytes.Length.ToString(CultureInfo.InvariantCulture)).Append("\r\n"); stringBuilder.Append("Connection: close\r\n"); if (!response.Headers.ContainsKey("Cache-Control")) { stringBuilder.Append("Cache-Control: no-store\r\n"); } stringBuilder.Append("X-Content-Type-Options: nosniff\r\n"); stringBuilder.Append("X-Frame-Options: DENY\r\n"); stringBuilder.Append("Referrer-Policy: no-referrer\r\n"); stringBuilder.Append("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'\r\n"); foreach (KeyValuePair<string, string> header in response.Headers) { stringBuilder.Append(header.Key).Append(": ").Append(header.Value) .Append("\r\n"); } stringBuilder.Append("\r\n"); byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString()); stream.Write(bytes, 0, bytes.Length); stream.Write(response.Bytes, 0, response.Bytes.Length); stream.Flush(); } private static string Reason(int status) { return status switch { 200 => "OK", 303 => "See Other", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 409 => "Conflict", 413 => "Payload Too Large", 415 => "Unsupported Media Type", 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Error", }; } } public sealed class LocalRequest { public string Method { get; } public string Path { get; } public IReadOnlyDictionary<string, string> Query { get; } public IReadOnlyDictionary<string, string> Headers { get; } public string Body { get; } public LocalRequest(string method, string path, IReadOnlyDictionary<string, string> query, IReadOnlyDictionary<string, string> headers, string body) { Method = method; Path = path; Query = query; Headers = headers; Body = body; } public string Header(string name) { if (!Headers.TryGetValue(name, out string value)) { return string.Empty; } return value; } public string Cookie(string name) { string[] array = Header("Cookie").Split(new char[1] { ';' }); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && string.Equals(text.Substring(0, num).Trim(), name, StringComparison.Ordinal)) { return text.Substring(checked(num + 1)).Trim(); } } return string.Empty; } } public sealed class LocalResponse { public int Status { get; } public string ContentType { get; } public byte[] Bytes { get; } public Dictionary<string, string> Headers { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public LocalResponse(int status, string contentType, byte[] body) { Status = status; ContentType = contentType; Bytes = body ?? Array.Empty<byte>(); } public static LocalResponse Text(int status, string text) { return new LocalResponse(status, "text/plain; charset=utf-8", Encoding.UTF8.GetBytes(text ?? string.Empty)); } public static LocalResponse Json(int status, string json) { return new LocalResponse(status, "application/json; charset=utf-8", Encoding.UTF8.GetBytes(json ?? "{}")); } public static LocalResponse Html(int status, string html) { return new LocalResponse(status, "text/html; charset=utf-8", Encoding.UTF8.GetBytes(html ?? string.Empty)); } } public static class LoopbackGate { public enum Verdict { WrongHost, OtherOrigin, ChangeFromElsewhere, Opening, Locked, Through } public const string KeyCookie = "alive_key"; public const string OpeningPage = "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"; public static Verdict Check(LocalRequest request, int port, string key) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(key)) { return Verdict.Locked; } string text = port.ToString(CultureInfo.InvariantCulture); string a = request.Header("Host"); if (!string.Equals(a, "127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) && !string.Equals(a, "localhost:" + text, StringComparison.OrdinalIgnoreCase)) { return Verdict.WrongHost; } string text2 = request.Header("Origin"); bool flag = string.Equals(text2, "http://127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, "http://localhost:" + text, StringComparison.OrdinalIgnoreCase); if (text2.Length > 0 && !flag) { return Verdict.OtherOrigin; } if (!IsRead(request) && !flag) { return Verdict.ChangeFromElsewhere; } if (request.Path == "/" && request.Query.TryGetValue("key", out string value)) { if (!Same(value, key)) { return Verdict.Locked; } return Verdict.Opening; } if (!Same(request.Cookie("alive_key"), key)) { return Verdict.Locked; } return Verdict.Through; } public static bool IsRead(LocalRequest request) { if (request != null) { if (!(request.Method == "GET")) { return request.Method == "HEAD"; } return true; } return false; } public static LocalResponse Opened(string key) { LocalResponse localResponse = LocalResponse.Html(200, "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"); localResponse.Headers["Set-Cookie"] = "alive_key=" + key + "; Path=/; HttpOnly; SameSite=Strict"; return localResponse; } public static string Link(int port, string key) { return "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture) + "/?key=" + key; } public static bool Same(string? a, string b) { if (a == null || b == null || a.Length != b.Length) { return false; } int num = 0; for (int i = 0; i < a.Length; i = checked(i + 1)) { num |= a[i] ^ b[i]; } return num == 0; } } } namespace ALIVE.Core.Storage { public enum ActivityCategory { Session, Shop, Quest, Dialogue, Economy, Admin, Anticheat, Npc } public sealed class ActivityEntry { public const int MaxDetailChars = 512; public const int MaxSubjectChars = 128; public const int MaxEventChars = 64; public long AtUnixMs { get; init; } public string PlatformId { get; init; } = string.Empty; public ActivityCategory Category { get; init; } public string Event { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string SubjectSub { get; init; } = string.Empty; public string Detail { get; init; } = string.Empty; public int Outcome { get; init; } public int? PosX { get; init; } public int? PosZ { get; init; } public string Correlation { get; init; } = string.Empty; public int Severity { get; init; } } public sealed class ActivityRecord { public long ActivityId { get; } public ActivityEntry Entry { get; } public ActivityRecord(long activityId, ActivityEntry entry) { ActivityId = activityId; Entry = entry ?? throw new ArgumentNullException("entry"); } } public enum TextMatch { None, Exact, Prefix, Contains } public sealed class ActivityQuery { public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public string PlatformId { get; init; } = string.Empty; public uint Categories { get; init; } public string Text { get; init; } = string.Empty; public TextMatch Match { get; init; } public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public enum PendingOpState { Pending, Approved, Rejected, Expired, Applied } public sealed class NewPendingOp { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class PendingOpRecord { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public PendingOpState State { get; init; } public string Approver { get; init; } = string.Empty; public string DecideNote { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } public long? DecidedMs { get; init; } } public enum DecideOutcome { Ok, NotFound, AlreadyDecided, Expired, SelfApproval } public sealed class DecideResult { public DecideOutcome Outcome { get; } public PendingOpRecord? Op { get; } public DecideResult(DecideOutcome outcome, PendingOpRecord? op) { Outcome = outcome; Op = op; } } public sealed class QuestDenialRecord { public string PlatformId { get; } public string QuestId { get; } public long? UntilMs { get; } public string Reason { get; } public string Actor { get; } public long CreatedMs { get; } public QuestDenialRecord(string platformId, string questId, long? untilMs, string reason, string actor, long createdMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); QuestId = questId ?? throw new ArgumentNullException("questId"); UntilMs = untilMs; Reason = reason ?? string.Empty; Actor = actor ?? string.Empty; CreatedMs = createdMs; } public bool AppliesAt(long nowMs) { if (UntilMs.HasValue) { return UntilMs.Value > nowMs; } return true; } } public enum AuditTier { System, Super, Admin, Player } public sealed class AuditEntry { public const int MaxSnapshotChars = 4096; public DateTime AtUtc { get; init; } public string Actor { get; init; } = string.Empty; public AuditTier Tier { get; init; } public string Action { get; init; } = string.Empty; public string Permission { get; init; } = string.Empty; public bool Granted { get; init; } = true; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string Before { get; init; } = string.Empty; public string After { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public string CorrelationId { get; init; } = string.Empty; } public sealed class AuditRecord { public long AuditId { get; } public AuditEntry Entry { get; } public string RowHash { get; } public AuditRecord(long auditId, AuditEntry entry, string rowHash) { AuditId = auditId; Entry = entry ?? throw new ArgumentNullException("entry"); RowHash = rowHash ?? throw new ArgumentNullException("rowHash"); } } public sealed class AuditVerification { public bool Intact => !FirstBrokenId.HasValue; public long Rows { get; } public long? FirstBrokenId { get; } public string Detail { get; } public AuditVerification(long rows, long? firstBrokenId, string detail) { Rows = rows; FirstBrokenId = firstBrokenId; Detail = detail; } } public static class AuditHash { public static byte[] Genesis => new byte[32]; public static byte[] Compute(byte[] previous, long auditId, AuditEntry e) { if (previous == null || previous.Length != 32) { throw new ArgumentException("The previous hash must be 32 bytes.", "previous"); } if (e == null) { throw new ArgumentNullException("e"); } string[] array = new string[13] { auditId.ToString(CultureInfo.InvariantCulture), e.AtUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), e.Actor, TierName(e.Tier), e.Action, e.Permission, e.Granted ? "1" : "0", e.SubjectKind, e.SubjectId, e.Before, e.After, e.Reason, e.CorrelationId }; using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(previous, 0, 32, null, 0); string[] array2 = array; foreach (string s in array2) { byte[] bytes = Encoding.UTF8.GetBytes(s); byte[] bytes2 = BitConverter.GetBytes(checked((uint)bytes.Length)); if (!BitConverter.IsLittleEndian) { Array.Reverse((Array)bytes2); } sHA.TransformBlock(bytes2, 0, 4, null, 0); sHA.TransformBlock(bytes, 0, bytes.Length, null, 0); } sHA.TransformFinalBlock(Array.Empty<byte>(), 0, 0); return sHA.Hash; } public static string TierName(AuditTier tier) { return tier switch { AuditTier.Super => "SUPER", AuditTier.Admin => "ADMIN", AuditTier.Player => "PLAYER", _ => "SYSTEM", }; } public static bool TryParseTier(string name, out AuditTier tier) { switch (name) { case "SUPER": tier = AuditTier.Super; return true; case "ADMIN": tier = AuditTier.Admin; return true; case "SYSTEM": tier = AuditTier.System; return true; case "PLAYER": tier = AuditTier.Player; return true; default: tier = AuditTier.System; return false; } } } public sealed class SpawnerPlacementRecord { public long PlacementId { get; init; } public string SpawnerId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } public long LastSpawnMs { get; init; } public string SpotKey { get; init; } = string.Empty; } public static class CreatureSpawnKinds { public const string Hand = "hand"; public const string Spawner = "spawner"; public const string Altar = "altar"; public const string Encounter = "encounter"; } public static class CreatureStates { public const string Alive = "alive"; public const string Dead = "dead"; public const string Removed = "removed"; public const string Gone = "gone"; } public sealed class AliveCreatureRecord { public string Uid { get; init; } = string.Empty; public string CreatureId { get; init; } = string.Empty; public string SpawnKind { get; init; } = string.Empty; public long PlacementId { get; init; } public string QuestId { get; init; } = string.Empty; public string Step { get; init; } = string.Empty; public string OwnerPlatformId { get; init; } = string.Empty; public string State { get; init; } = "alive"; public long SpawnedMs { get; init; } public long LastNearMs { get; init; } public long ExpiresMs { get; init; } public double X { get; init; } public double Y { get; init; } public double Z { get; init; } } public enum GrantState { Pending = 1, Offered, Delivered, Mailbox, Stalled, Expired } public static class GrantReasons { public const byte QuestReward = 1; public const byte AdminGift = 2; public const byte Purchase = 3; public const byte Barter = 4; public const byte Withdrawal = 5; public const byte Returned = 6; public const byte Sale = 7; public const byte Effect = 8; } public sealed class GrantItem { public string Prefab { get; init; } = string.Empty; public int Count { get; init; } = 1; public int Quality { get; init; } = 1; public int Variant { get; init; } } public sealed class NewGrant { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class GrantRecord { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public GrantState State { get; init; } public int Attempts { get; init; } public long CreatedMs { get; init; } public long UpdatedMs { get; init; } public long ExpiresMs { get; init; } public string Detail { get; init; } = string.Empty; } public interface IAliveStore : IDisposable { int SchemaVersion { get; } string EngineDescription { get; } void RecordContentLoad(ContentLoadRecord record); IReadOnlyList<ContentLoadRecord> RecentContentLoads(int max); AuditRecord AppendAudit(AuditEntry entry); AuditVerification VerifyAudit(); IReadOnlyList<AuditRecord> RecentAudit(int max); PlayerRecord RecordSessionStart(string platformId, string characterName, long nowMs); void RecordSessionEnd(string platformId, long nowMs); PlayerRecord? FindPlayer(string platformId); IReadOnlyList<PlayerRecord> SearchPlayers(PlayerQuery query); long AppendActivity(ActivityEntry entry); IReadOnlyList<ActivityRecord> SearchActivity(ActivityQuery query); PostResult Post(IReadOnlyList<LedgerPosting> legs, IReadOnlyDictionary<string, LedgerBounds> bounds, IReadOnlyList<ActivityEntry> activity, long nowMs); long Balance(string platformId, string currencyId); IReadOnlyList<WalletRecord> Wallets(string platformId); (int Players, long Total) CurrencyHeld(string currencyId); IReadOnlyList<LedgerRecord> SearchLedger(LedgerQuery query); IReadOnlyList<LedgerRecord> LedgerGroup(string groupId); bool WalletReconciles(string platformId, string currencyId); ReconcileReport Reconcile(long nowMs); QuestInstanceRecord? CreateQuestInstance(NewQuestInstance instance); bool SaveJobPosting(JobPosting posting); JobPosting? LatestJobPosting(long placedId); bool MarkJobHanded(long instanceId, long morning); int JobsHandedSince(string platformId, long fromMorning); int JobsHandedOn(string platformId, long morning); IReadOnlyList<KeyValuePair<string, string>> JobTakers(long placedId, long posting); void RetireJobPostings(long placedId); void StartJobTravel(long instanceId); void SaveJobTravel(long instanceId, double countedMetres); void FreezeJobTravel(long instanceId, double countedMetres, long doneMs); JobTravelRow? JobTravel(long instanceId); IReadOnlyList<JobTravelRow> OpenJobTravel(); bool AddJobDone(string platformId, string boardKey, long nowMs); int JobsDone(string platformId, string boardKey); bool FillJobDoneOnce(IReadOnlyDictionary<long, string> boardKeyByPlacedId, long nowMs); QuestInstanceRecord? QuestInstance(long instanceId); QuestInstanceRecord? OpenQuestInstance(string platformId, string questId); IReadOnlyList<QuestInstanceRecord> SearchQuestInstances(QuestInstanceQuery query); QuestWipe WipeQuest(string platformId, string questId, string note, long nowMs); QuestInstanceRecord ApplyQuestTransition(QuestTransition transition); IReadOnlyList<QuestEventRecord> QuestEvents(long instanceId, int max); bool SetQuestClock(long instanceId, QuestClock clock); bool ClaimObjectiveEffects(string platformId, string questId, string objectiveId, long nowMs, long windowMs); NpcPlacementRecord AddPlacement(NewNpcPlacement placement); IReadOnlyList<NpcPlacementRecord> Placements(bool includeRemoved = false); NpcPlacementRecord? Placement(long placementId); void SetPlacementObject(long placementId, string zdoId, long nowMs); bool MovePlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemovePlacement(long placementId, long nowMs); SpawnerPlacementRecord AddSpawnerPlacement(string spawnerId, string label, double x, double y, double z, double rotY, string placedBy, long nowMs); IReadOnlyList<SpawnerPlacementRecord> SpawnerPlacements(); SpawnerPlacementRecord? SpawnerPlacement(long placementId); bool MoveSpawnerPlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemoveSpawnerPlacement(long placementId); int RemoveSpawnerPlacements(string spawnerId); void SetSpawnerPlacementObject(long placementId, string zdoId, long nowMs); void SetSpawnerPlacementSpawned(long placementId, long nowMs); bool SetSpawnerPlacementSpot(long placementId, string spotKey, long nowMs); void AddAliveCreature(AliveCreatureRecord creature); IReadOnlyList<AliveCreatureRecord> AliveCreatures(); AliveCreatureRecord? AliveCreature(string uid); void SeeAliveCreature(string uid, double x, double y, double z, long lastNearMs); bool RenameAliveCreature(string uid, string newUid); bool EndAliveCreature(string uid, string state, long nowMs); int PurgeEndedCreatures(long endedBeforeMs); GrantRecord AddGrant(NewGrant grant); GrantRecord? Grant(string grantId); IReadOnlyList<GrantRecord> Grants(string platformId, IReadOnlyList<GrantState> states, int limit = 200); int CountGrantsFrom(string sourceKind, string sourceIdPrefix); bool MoveGrant(string grantId, GrantState fromState, GrantState toState, long nowMs, bool countAttempt, string detail); ShopStockRecord? ShopStock(string shopId, string entryId); bool SetShopStock(ShopStockRecord stock, long? expectedRestockedMs); long ShopCredit(string platformId, string shopId); int ShopTradeCount(string platformId, ShopTradeKind kind, string refId, long sinceMs); long LastShopTradeMs(string platformId, ShopTradeKind kind, string refId); bool ApplyPlayerState(PlayerStateChange change); string? RewardRolls(string groupId); bool HasFlag(string platformId, string flagId); void AddCounters(string platformId, IReadOnlyDictionary<string, long> deltas, long atMs); IReadOnlyList<string> Flags(string platformId); IReadOnlyList<HeldFlag> FlagsHeld(string platformId); IReadOnlyList<string> ClearFlags(string platformId, IReadOnlyList<string>? flags); bool GiveFlag(string platformId, string flagId, long atMs); long SetCounter(string platformId, string counterId, long value); IReadOnlyList<KeyValuePair<string, long>> CountersOf(string platformId, string prefix, int most); IReadOnlyList<HeldName> HeldFlags(); IReadOnlyList<HeldName> HeldCounters(string prefix); int CountFlagHolders(string flagId); int CountCounterHolders(string counterId); IReadOnlyList<string> ClearFlagEverywhere(string flagId); IReadOnlyList<string> ClearCounterEverywhere(string counterId); bool DeleteServerSwitch(string switchId); int ForgetPlayerState(string platformId, IReadOnlyList<string> counters, IReadOnlyList<string> counterPrefixes, IReadOnlyList<string> flags); bool ServerSwitchOn(string switchId); IReadOnlyList<ServerSwitchRecord> ServerSwitches(); void SetServerSwitch(string switchId, bool isOn, string actor, long nowMs); IReadOnlyList<string> EditorFolders(); bool AddEditorFolder(string folder, string madeBy, long atMs); bool RemoveEditorFolder(string folder); void RenameEditorFolder(string oldFolder, string newFolder); string? PlayerVar(string platformId, string varId); void SetPlayerVar(string platformId, string varId, string value, long atMs); int CountVarHolders(string varId); IReadOnlyList<string> ClearVarEverywhere(string varId); long Counter(string platformId, string counterId); int Relationship(string platformId, string npcId); void SetRelationship(string platformId, string id, int value, long nowMs); IReadOnlyList<RelationshipRow> RelationshipsWith(string id); int CountRelationshipsWith(string id); int ForgetRelationshipsWith(string id); bool HasUnlock(string platformId, byte kind, string reference); void SetRewardChoice(long instanceId, string platformId, int choice, long atMs); int? RewardChoice(long instanceId); int ShopTradeCountSinceGameDay(string platformId, ShopTradeKind kind, string refId, long fromGameDay); ShopCommitOutcome CommitShopTrade(ShopCommit commit); IReadOnlyDictionary<string, int> SoldByItem(string platformId, SellWindow window); IReadOnlyDictionary<string, int> SoldByItemAt(string platformId, string shopId, SellWindow window); long SoldValue(string platformId, SellWindow window); long MerchantPaid(string shopId, SellWindow window); void SetShopTradeGrant(string tradeId, string grantId); IReadOnlyList<ShopTradeRecord> UngrantedShopTrades(int limit); PendingOpRecord CreatePendingOp(NewPendingOp op); PendingOpRecord? PendingOp(string opId); DecideResult DecidePendingOp(string opId, string approver, bool approve, string note, long nowMs); void MarkPendingOpApplied(string opId, long nowMs); int ExpirePendingOps(long nowMs); void SetQuestDenial(string platformId, string questId, long? untilMs, string reason, string actor, long nowMs); bool ClearQuestDenial(string platformId, string questId); QuestDenialRecord? QuestDenial(string platformId, string questId); IReadOnlyList<QuestDenialRecord> QuestDenials(string platformId); IReadOnlyList<WorldRow> WorldPlaces(); long SaveWorldPlace(long id, string key, string body, string by, long nowMs); bool RemoveWorldPlace(long id); IReadOnlyList<WorldRow> WorldLocks(); long SaveWorldLock(long id, string uid, string body, string by, long nowMs); bool RemoveWorldLock(long id); IReadOnlyList<WorldRow> WorldObjects(); long SaveWorldObject(long id, string uid, string body, string by, long nowMs); bool RemoveWorldObject(long id); IReadOnlyList<WorldRow> WorldSpots(); long SaveWorldSpot(long id, string key, string body, string by, long nowMs); bool RemoveWorldSpot(long id); void RenameWorldThings(bool objects, IReadOnlyList<KeyValuePair<long, string>> names); bool LockOpened(long lockId, string platformId); void MarkLockOpened(long lockId, string platformId, long nowMs); long PlaceSeen(long placeId, string platformId); void MarkPlaceSeen(long placeId, string platformId, long nowMs); } public sealed class ContentLoadRecord { public DateTime AtUtc { get; } public IReadOnlyList<string> Packs { get; } public IReadOnlyList<string> FailedPacks { get; } public int Published { get; } public int Quarantined { get; } public int Errors { get; } public int Warnings { get; } public string ContentHash { get; } public ContentLoadRecord(DateTime atUtc, IReadOnlyList<string> packs, IReadOnlyList<string> failedPacks, int published, int quarantined, int errors, int warnings, string contentHash) { AtUtc = atUtc; Packs = packs ?? throw new ArgumentNullException("packs"); FailedPacks = failedPacks ?? throw new ArgumentNullException("failedPacks"); Published = published; Quarantined = quarantined; Errors = errors; Warnings = warnings; ContentHash = contentHash ?? throw new ArgumentNullException("contentHash"); } } public enum LedgerReason { ShopBuy = 1, ShopSell, Barter, QuestReward, AdminGrant, Decay, Refund, Reconcile, StartingBalance, Deposit, Withdrawal, Penalty, Effect } public enum LedgerSourceKind { None, Shop, Quest, TradeRecipe, Admin, System, Bank } public sealed class LedgerPosting { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long DeltaMinor { get; init; } public LedgerReason Reason { get; init; } public LedgerSourceKind SourceKind { get; init; } public string SourceId { get; init; } = string.Empty; public string SourceSub { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Note { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; } public sealed class LedgerRecord { public long TxnId { get; } public LedgerPosting Posting { get; } public long BalanceAfterMinor { get; } public long AtUnixMs { get; } public LedgerRecord(long txnId, LedgerPosting posting, long balanceAfterMinor, long atUnixMs) { TxnId = txnId; Posting = posting ?? throw new ArgumentNullException("posting"); BalanceAfterMinor = balanceAfterMinor; AtUnixMs = atUnixMs; } } public sealed class WalletRecord { public string PlatformId { get; } public string CurrencyId { get; } public long BalanceMinor { get; } public long LifetimeInMinor { get; } public long LifetimeOutMinor { get; } public long UpdatedMs { get; } public WalletRecord(string platformId, string currencyId, long balanceMinor, long lifetimeInMinor, long lifetimeOutMinor, long updatedMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); BalanceMinor = balanceMinor; LifetimeInMinor = lifetimeInMinor; LifetimeOutMinor = lifetimeOutMinor; UpdatedMs = updatedMs; } } public sealed class LedgerBounds { public long MinMinor { get; } public long MaxMinor { get; } public LedgerBounds(long minMinor, long maxMinor) { if (maxMinor < minMinor) { throw new ArgumentOutOfRangeException("maxMinor", maxMinor, "The ceiling is below the floor."); } MinMinor = minMinor; MaxMinor = maxMinor; } } public enum PostOutcome { Posted, AlreadyPosted, BelowFloor, AboveCeiling, UnknownPlayer, UnknownCurrency } public sealed class PostResult { public PostOutcome Outcome { get; } public bool Accepted { get { if (Outcome != PostOutcome.Posted) { return Outcome == PostOutcome.AlreadyPosted; } return true; } } public IReadOnlyList<LedgerRecord> Legs { get; } public string Detail { get; } public PostResult(PostOutcome outcome, IReadOnlyList<LedgerRecord> legs, string detail) { Outcome = outcome; Legs = legs ?? throw new ArgumentNullException("legs"); Detail = detail ?? string.Empty; } } public sealed class LedgerQuery { public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public sealed class WalletDiscrepancy { public string PlatformId { get; } public string CurrencyId { get; } public long WalletMinor { get; } public long LedgerMinor { get; } public WalletDiscrepancy(string platformId, string currencyId, long walletMinor, long ledgerMinor) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); WalletMinor = walletMinor; LedgerMinor = ledgerMinor; } } public sealed class ReconcileReport { public int WalletsChecked { get; } public IReadOnlyList<WalletDiscrepancy> Repaired { get; } public bool Balanced => Repaired.Count == 0; public ReconcileReport(int walletsChecked, IReadOnlyList<WalletDiscrepancy> repaired) { WalletsChecked = walletsChecked; Repaired = repaired ?? throw new ArgumentNullException("repaired"); } } public sealed class NewNpcPlacement { public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } } public sealed class NpcPlacementRecord { public long PlacementId { get; init; } public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } } public sealed class PlayerRecord { public long PlayerId { get; } public string PlatformId { get; } public string CharacterName { get; } public long FirstSeenMs { get; } public long LastSeenMs { get; } public long SessionCount { get; } public PlayerRecord(long playerId, string platformId, string characterName, long firstSeenMs, long lastSeenMs, long sessionCount) { PlayerId = playerId; PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CharacterName = characterName ?? throw new ArgumentNullException("characterName"); FirstSeenMs = firstSeenMs; LastSeenMs = lastSeenMs; SessionCount = sessionCount; } } public enum PlayerQueryKind { PlatformId = 1, NamePrefix } public sealed class PlayerQuery { public PlayerQueryKind Kind { get; init; } = PlayerQueryKind.NamePrefix; public string Text { get; init; } = string.Empty; public string AlternateText { get; init; } = string.Empty; public string? AfterName { get; init; } public string AfterPlatformId { get; init; } = string.Empty; public int Limit { get; init; } = 50; } public static class UnlockKinds { public const byte Quest = 1; public const byte ShopEntry = 2; } public sealed class RelationshipRow { public string PlatformId { get; init; } = string.Empty; public int Value { get; init; } public long ChangedMs { get; init; } } public sealed class PlayerStateChange { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public IReadOnlyList<string> Flags { get; init; } = Array.Empty<string>(); public IReadOnlyList<string> ClearFlags { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, long> Counters { get; init; } = new Dictionary<string, long>(); public IReadOnlyDictionary<string, long> Relationships { get; init; } = new Dictionary<string, long>(); public IReadOnlyList<KeyValuePair<byte, string>> Unlocks { get; init; } = Array.Empty<KeyValuePair<byte, string>>(); public string Rolls { get; init; } = string.Empty; public long AtMs { get; init; } } public static class GrantPrefixes { public const string Skill = "@skill:"; public const string PovTree = "@pov:tree:"; public const string PovProfession = "@pov:prof:"; public static bool IsSkill(string? prefab) { return prefab?.StartsWith("@skill:", StringComparison.Ordinal) ?? false; } public static bool IsPov(string? prefab) { if (prefab != null) { if (!prefab.StartsWith("@pov:tree:", StringComparison.Ordinal)) { return prefab.StartsWith("@pov:prof:", StringComparison.Ordinal); } return true; } return false; } public static bool IsNotItem(string? prefab) { if (!IsSkill(prefab)) { return IsPov(prefab); } return true; } } public enum QuestState { NotOffered, Offered, Active, ReadyToTurnIn, Completed, Failed, Abandoned, Paused, Cooldown, Stale } public enum QuestEventKind { Offered, Accepted, Progress, ObjectiveDone, Ready, Completed, Failed, Abandoned, Paused, Resumed, Stale, Migrated, AdminAdjusted } public enum MigrationPolicy { Snapshot, FollowLive } public sealed class ObjectiveProgress { public string ObjectiveId { get; init; } = string.Empty; public long Current { get; init; } public long Required { get; init; } public long? CompletedMs { get; init; } public bool Optional { get; init; } public int OrderIndex { get; init; } public bool Revealed { get; init; } = true; public bool IsDone => CompletedMs.HasValue; } public static class QuestClockDomains { public const string None = ""; public const string Online = "online"; public const string Real = "real"; public const string World = "world"; } public static class QuestHolds { public const string None = ""; public const string Deadline = "deadline"; public const string Window = "window"; public const string Manual = "manual"; } public sealed class QuestClock { public static QuestClock Empty { get; } = new QuestClock(); public string Domain { get; init; } = ""; public long? DeadlineMs { get; init; } public long? LeftMs { get; init; } public long? WorldDeadlineS { get; init; } public string OnDeadline { get; init; } = string.Empty; public long GraceMs { get; init; } public long BudgetMs { get; init; } public string Hold { get; init; } = ""; public bool HasDeadline => Domain.Length > 0; public bool Running { get { if (!DeadlineMs.HasValue) { return WorldDeadlineS.HasValue; } return true; } } public QuestClock With(long? deadlineMs, long? leftMs, long? worldDeadlineS, string hold) { return new QuestClock { Domain = Domain, DeadlineMs = deadlineMs, LeftMs = leftMs, WorldDeadlineS = worldDeadlineS, OnDeadline = OnDeadline, GraceMs = GraceMs, BudgetMs = BudgetMs, Hold = (hold ?? "") }; } } public sealed class NewQuestInstance { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } = QuestState.Offered; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public QuestClock? Clock { get; init; } public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } } public sealed class JobTake { public string Board { get; init; } = string.Empty; public long PlacedId { get; init; } public long Posting { get; init; } public string BoardNpc { get; init; } = string.Empty; public string HandIn { get; init; } = string.Empty; public long? HandedMorning { get; init; } public string Rolled { get; init; } = string.Empty; } public sealed class JobPosting { public const long NeverDue = long.MinValue; public long PlacedId { get; init; } public long Number { get; init; } public long Due { get; init; } public long PostedMs { get; init; } public IReadOnlyList<string> Notices { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, string> Rolls { get; init; } = new Dictionary<string, string>(StringComparer.Ordinal); } public sealed class JobTravelRow { public long InstanceId { get; init; } public double CountedMetres { get; init; } public long? DoneMs { get; init; } } public sealed class QuestInstanceRecord { public long InstanceId { get; init; } public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } public int Attempt { get; init; } = 1; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long? OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? LastProgressMs { get; init; } public long? CooldownUntilMs { get; init; } public bool Tracked { get; init; } = true; public string RewardGroupId { get; init; } = string.Empty; public string StaleReason { get; init; } = string.Empty; public QuestClock Clock { get; init; } = QuestClock.Empty; public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } public bool IsOpen => QuestStates.IsOpen(State); } public sealed class QuestEventRecord { public long EventId { get; } public long InstanceId { get; } public QuestEventKind Kind { get; } public string Detail { get; } public string Actor { get; } public string Correlation { get; } public long AtUnixMs { get; } public QuestEventRecord(long eventId, long instanceId, QuestEventKind kind, string detail, string actor, string correlation, long atUnixMs) { EventId = eventId; InstanceId = instanceId; Kind = kind; Detail = detail ?? string.Empty; Actor = actor ?? string.Empty; Correlation = correlation ?? string.Empty; AtUnixMs = atUnixMs; } } public sealed class QuestTransition { public long InstanceId { get; init; } public QuestState State { get; init; } public QuestEventKind Kind { get; init; } public string Detail { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; public long AtUnixMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? CooldownUntilMs { get; init; } public string? RewardGroupId { get; init; } public string? StaleReason { get; init; } public bool ClearTimestamps { get; init; } public IReadOnlyDictionary<string, long>? Progress { get; init; } public IReadOnlyCollection<string>? Reveal { get; init; } public QuestClock? Clock { get; init; } public bool ClearCooldown { get; init; } } public sealed class QuestInstanceQuery { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public IReadOnlyList<QuestState> States { get; init; } = Array.Empty<QuestState>(); public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public static class QuestStates { public static bool IsOpen(QuestState state) { if (state != QuestState.Offered && state != QuestState.Active && state != QuestState.ReadyToTurnIn && state != QuestState.Paused) { return state == QuestState.Stale; } return true; } public static bool IsTerminal(QuestState state) { if (state != QuestState.Completed && state != QuestState.Failed && state != QuestState.Abandoned) { return state == QuestState.Cooldown; } return true; } public static string Name(QuestState state) { return state switch { QuestState.Offered => "offered", QuestState.Active => "active", QuestState.ReadyToTurnIn => "ready_to_turn_in", QuestState.Completed => "completed", QuestState.Failed => "failed", QuestState.Abandoned => "abandoned", QuestState.Paused => "paused", QuestState.Cooldown => "cooldown", QuestState.Stale => "stale", _ => throw new ArgumentOutOfRangeException("state", state, "NOT_OFFERED is the absence of a row and is never stored."), }; } public static QuestState Parse(string name) { return name switch { "offered" => QuestState.Offered, "active" => QuestState.Active, "ready_to_turn_in" => QuestState.ReadyToTurnIn, "completed" => QuestState.Completed, "failed" => QuestState.Failed, "abandoned" => QuestState.Abandoned, "paused" => QuestState.Paused, "cooldown" => QuestState.Cooldown, "stale" => QuestState.Stale, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest state."), }; } public static string EventName(QuestEventKind kind) { return kind switch { QuestEventKind.Offered => "offered", QuestEventKind.Accepted => "accepted", QuestEventKind.Progress => "progress", QuestEventKind.ObjectiveDone => "objective_done", QuestEventKind.Ready => "ready", QuestEventKind.Completed => "completed", QuestEventKind.Failed => "failed", QuestEventKind.Abandoned => "abandoned", QuestEventKind.Paused => "paused", QuestEventKind.Resumed => "resumed", QuestEventKind.Stale => "stale", QuestEventKind.Migrated => "migrated", QuestEventKind.AdminAdjusted => "admin_adjusted", _ => throw new ArgumentOutOfRangeException("kind", kind, "Unknown quest event kind."), }; } public static QuestEventKind ParseEvent(string name) { return name switch { "offered" => QuestEventKind.Offered, "accepted" => QuestEventKind.Accepted, "progress" => QuestEventKind.Progress, "objective_done" => QuestEventKind.ObjectiveDone, "ready" => QuestEventKind.Ready, "completed" => QuestEventKind.Completed, "failed" => QuestEventKind.Failed, "abandoned" => QuestEventKind.Abandoned, "paused" => QuestEventKind.Paused, "resumed" => QuestEventKind.Resumed, "stale" => QuestEventKind.Stale, "migrated" => QuestEventKind.Migrated, "admin_adjusted" => QuestEventKind.AdminAdjusted, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest event kind."), }; } } public enum ShopTradeKind { Buy = 1, Barter, Sell } public sealed class ShopStockRecord { public string ShopId { get; init; } = string.Empty; public string EntryId { get; init; } = string.Empty; public int Qty { get; init; } public long RestockedMs { get; init; } } public sealed class ShopTradePart { public byte Kind { get; init; } public string Id { get; init; } = string.Empty; public long Amount { get; init; } } public sealed class ShopTradeRecord { public const string NoGrant = "-"; public string TradeId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string ShopId { get; init; } = string.Empty; public string NpcId { get; init; } = string.Empty; public ShopTradeKind Kind { get; init; } public string RefId { get; init; } = string.Empty; public int Qty { get; init; } public IReadOnlyList<ShopTradePart> Paid { get; init; } = Array.Empty<ShopTradePart>(); public IReadOnlyList<ShopTradePart> Got { get; init; } = Array.Empty<ShopTradePart>(); public long CreditBefore { get; init; } public long CreditAfter { get; init; } public string GrantId { get; init; } = string.Empty; public long GameDay { get; init; } = -1L; public long ValueVu { get; init; } public long AtMs { get; init; } } public enum ShopCommitOutcome { Committed = 1, OutOfStock, CreditChanged } public sealed class ShopCommit { public ShopTradeRecord Trade { get; init; } = new ShopTradeRecord(); public int StockTake { get; init; } public string StockEntryId { get; init; } = string.Empty; public long CreditExpected { get; init; } public IReadOnlyList<ActivityEntry> Activity { get; init; } = Array.Empty<ActivityEntry>(); } public sealed class SellWindow { public long SinceMs { get; init; } public long FromGameDay { get; init; } = -1L; } public sealed class ServerSwitchRecord { public string SwitchId { get; init; } = string.Empty; public bool On { get; init; } public long ChangedMs { get; init; } public string ChangedBy { get; init; } = string.Empty; } public sealed class HeldName { public string Name { get; init; } = string.Empty; public int Holders { get; init; } } public sealed class HeldFlag { public string FlagId { get; init; } = string.Empty; public long SetMs { get; init; } } public sealed class QuestWipe { public IReadOnlyList<long> Instances { get; init; } = Array.Empty<long>(); public int Events { get; init; } public int GrantsClosed { get; init; } } public sealed class WorldRow { public long Id { get; init; } public string Key { get; init; } = string.Empty; public string Body { get; init; } = string.Empty; public string UpdatedBy { get; init; } = string.Empty; public long UpdatedMs { get; init; } } } namespace ALIVE.Core.Protocol { public static class AliveProtocol { public const ushort ProtoVersion = 1; public const byte EnvelopeVersion = 1; public const ushort Magic = 42782; public const int MaxFrameBytes = 8192; public const int MaxPayloadBytes = 4194304; public const int MaxPayloadBytesC2S = 262144; public const int MaxChunks = 64; public const int MaxChunksC2S = 8; public const int CompressMinBytes = 512; public const int MaxStringBytes = 4096; public const int MaxCollectionSize = 1024; public const string RpcChannelServer = "ALIVE.s2c"; public const string RpcChannelPlayer = "ALIVE.c2s.player"; public const string RpcChannelAdmin = "ALIVE.c2s.admin"; } public static class AttestationDigest { public const byte SpecNonceThenFile = 1; public static ByteString Response(ByteString serverNonce, byte[] fileBytes) { if (serverNonce == null) { throw new ArgumentNullException("serverNonce"); } if (fileBytes == null) { throw new ArgumentNullException("fileBytes"); } using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(serverNonce.Raw, 0, serverNonce.Length, null, 0); sHA.TransformFinalBlock(fileBytes, 0, fileBytes.Length); return ByteString.Own(sHA.Hash); } public static ByteString Combined(IReadOnlyList<ByteString> responses) { if (responses == null) { throw new ArgumentNullException("responses"); } WireWriter wireWriter = new WireWriter(); foreach (ByteString response in responses) { wireWriter.WriteRaw(response); } return Sha256(wireWriter.ToArray()); } public static ByteString PluginSet(IReadOnlyList<PluginReport> plugins) { if (plugins == null) { throw new ArgumentNullException("plugins"); } WireWriter wireWriter = new WireWriter(); foreach (PluginReport plugin in plugins) { wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.PluginId))); wireWriter.WriteU8(0); wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.Version))); wireWriter.WriteU8(0); wireWriter.WriteRaw(plugin.FileHash); } return Sha256(wireWriter.ToArray()); } private static ByteString Sha256(byte[] data) { using SHA256 sHA = SHA256.Create(); return ByteString.Own(sHA.ComputeHash(data)); } } public sealed class ByteString : IEquatable<ByteString> { private readonly byte[] _bytes; public static ByteString Empty { get; } = new ByteString(Array.Empty<byte>()); public int Length => _bytes.Length; public byte this[int index] => _bytes[index]; public bool IsAllZero { get { byte[] bytes = _bytes; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] != 0) { return false; } } return true; } } internal byte[] Raw => _bytes; private ByteString(byte[] owned) { _bytes = owned; } public static ByteString CopyFrom(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (bytes.Length != 0) { return new ByteString((byte[])bytes.Clone()); } return Empty; } public static ByteString CopyFrom(byte[] bytes, int offset, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || count < 0 || offset > checked(bytes.Length - count)) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return Empty; } byte[] array = new byte[count]; Buffer.BlockCopy(bytes, offset, array, 0, count); return new ByteString(array); } public static ByteString Zeros(int length) { if (length != 0) { return new ByteString(new byte[length]); } return Empty; } internal static ByteString Own(byte[] bytes) { if (bytes.Length != 0) { return new ByteString(bytes); } return Empty; } public byte[] ToArray() { return (byte[])_bytes.Clone(); } public bool FixedTimeEquals(ByteString? other) { if (other == null || other._bytes.Length != _bytes.Length) { return false; } int num = 0; for (int i = 0; i < _bytes.Length; i = checked(i + 1)) { num |= _bytes[i] ^ other._bytes[i]; } return num == 0; } internal void CopyTo(byte[] destination, int offset) { Buffer.BlockCopy(_bytes, 0, destination, offset, _bytes.Length); } public bool Equals(ByteString? other) { return FixedTimeEquals(other); } public override bool Equals(object? obj) { if (obj is ByteString other) { return FixedTimeEquals(other); } return false; } public override int GetHashCode() { int num = -2128831035; byte[] bytes = _bytes; foreach (byte b in bytes) { num = (num ^ b) * 16777619; } return num; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(checked(_bytes.Length * 2)); byte[] bytes = _bytes; foreach (byte b in bytes) { stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } public static class Crc32C { private const uint Polynomial = 2197175160u; private static readonly uint[] Table = BuildTable(); public static uint Compute(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } checked { if (offset < 0 || count < 0 || offset > data.Length - count) { throw new ArgumentOutOfRangeException("count"); } uint num = uint.MaxValue; int num2 = offset + count; for (int i = offset; i < num2; i++) { num = Table[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return ~num; } } private static uint[] BuildTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0x82F63B78u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } public enum DecodeOutcome { Complete, Pending, Dropped, Rejected } public sealed class DecodeResult { public DecodeOutcome Outcome { get; } public ErrorCode Error { get; } public bool HardSignal { get; } public string Detail { get; } public FrameHeader? Header { get; } public ByteString? Payload { get; } private DecodeResult(DecodeOutcome outcome, ErrorCode error, bool hardSignal, string detail, FrameHeader? header, ByteString? payload) { Outcome = outcome; Error = error; HardSignal = hardSignal; Detail = detail; Header = header; Payload = payload; } internal static DecodeResult Complete(FrameHeader header, ByteString payload) { return new DecodeResult(DecodeOutcome.Complete, ErrorCode.None, hardSignal: false, string.Empty, header, payload); } internal static DecodeResult Pending() { return new DecodeResult(DecodeOutcome.Pending, ErrorCode.None, hardSignal: false, string.Empty, null, null); } internal static DecodeResult Dropped(string detail) { return new DecodeResult(DecodeOutcome.Dropped, ErrorCode.None, hardSignal: false, detail, null, null); } internal static DecodeResult Reject(ErrorCode error, bool hard, string detail) { return new DecodeResult(DecodeOutcome.Rejected, error, hard, detail, null, null); } } public static class Envelope { public const int HeaderBytes = 44; public const int ChunkHeaderBytes = 12; public const int CrcBytes = 4; public const int IdemKeyBytes = 16; public const byte FlagCompressed = 1; public const byte FlagChunk = 2; public const byte FlagAdmin = 4; public const byte ReservedFlags = 248; public static int SingleBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 4); } public static int ChunkBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 12 - 4); } } public enum ErrorCode { None = 0, Malformed = 1000, UnsupportedEnvVersion = 1001, ReservedBitsSet = 1002, TrailingBytes = 1003, WrongDirection = 1004, UnknownMsgType = 1005, SizeLimit = 1006, SenderIdMismatch = 1007, BadCrc = 1008, UnsupportedMsgVersion = 1009, NoSession = 2001, NotReady = 2002, SessionExpired = 2003, SessionMismatch = 2004, ProtoVersionMismatch = 2101, AttestationFailed = 2102, DualClientDetected = 2103, PluginPolicyDenied = 2104, AttestTimeout = 2105, SyncTimeout = 2106, ClientRequired = 2107, Banned = 2108, ServerFullAlive = 2109, ClientVersionMismatch = 2110, FieldInvalid = 3001, NotFound = 3002, QtyOutOfRange = 3003, ItemNotAllowed = 3004, StringTooLong = 3011, ContentSchemaInvalid = 3006, ContentBoundsExceeded = 3007, CollectionTooLarge = 3012, CharsetViolation = 3013, IdempotencyConflict = 3009, IdempotencyMissing = 3010, NotAuthorized = 4001, NotOwner = 4002, NotOffered = 4003, OutOfRange = 4005, OptionNotOffered = 4009, DualControlRequired = 4011, SuperAdminRequired = 4012, SelfApprovalForbidden = 4013, ShopClosed = 5001, StaleVersion = 5002, PriceChanged = 5003, OutOfStock = 5004, InsufficientFunds = 5005, ObjectivesIncomplete = 5006, NotActive = 5010, AlreadyCompleted = 5011, InstanceNotFound = 5016, NothingToRevoke = 5017, ApprovalExpired = 5020, LimitReached = 5021, RateLimited = 6001, BurstLimited = 6002, MemoryBudget = 6004, Internal = 7001 } public static class FieldRules { public static bool IsVersion(string? value) { if (value == null || value.Length == 0 || value.Length > 32) { return false; } int i = 0; int num = 0; checked { while (true) { int num2 = i; for (; i < value.Length && value[i] >= '0' && value[i] <= '9'; i++) { } int num3 = i - num2; if (num3 < 1 || num3 > 5) { return false; } num++; if (i == value.Length) { return num <= 4; } if (value[i] != '.' || num >= 4) { break; } i++; } if (value[i] != '-') { return false; } int num4 = value.Length - i - 1; if (num4 < 1 || num4 > 16) { return false; } for (int j = i + 1; j < value.Length; j++) { char c = value[j]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.') { return false; } } return true; } } public static bool IsPluginId(string? value) { return IsToken(value, 128, allowUpper: true, leadingUnderscore: true); } public static bool IsIdentifier(string? value) { return IsToken(value, 64, allowUpper: false); } public static bool IsBuildId(string? value) { if (value != null) { if (value.Length != 0) { return IsToken(value, 40, allowUpper: true); } return true; } return false; } private static bool IsToken(string? value, int max, bool allowUpper, bool leadingUnderscore = false) { if (value == null || value.Length == 0 || value.Length > max) { return false; } for (int i = 0; i < value.Length; i = checked(i + 1)) { char c = value[i]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && (!allowUpper || c < 'A' || c > 'Z') && (i <= 0 || (c != '.' && c != '_' && c != '-')) && (!(i == 0 && leadingUnderscore) || c != '_')) { return false; } } return true; } } public sealed class Frame { public FrameHeader Header { get; } public bool Compressed { get; } public int PayloadLength { get; } public ChunkInfo? Chunk { get; } public ByteString Body { get; } internal Frame(FrameHeader header, bool compressed, int payloadLength, ChunkInfo? chunk, ByteString body) { Header = header; Compressed = compressed; PayloadLength = payloadLength; Chunk = chunk; Body = body; } } public sealed class ChunkInfo { public uint ChunkId { get; } public int Index { get; } public int Count { get; } public int TotalLength { get; } internal ChunkInfo(uint chunkId, int index, int count, int totalLength) { ChunkId = chunkId; Index = index; Count = count; TotalLength = totalLength; } } public static class FrameCodec { public static IReadOnlyList<byte[]> Encode(FrameHeader header, ByteString payload, FrameLimits limits, uint chunkId) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (limits == null) { throw new ArgumentNullException("limits"); } if (header.IdemKey == null || header.IdemKey.Length != 16) { throw new ArgumentException("The idempotency key must be 16 bytes.", "header"); } if (payload.Length > limits.MaxPayloadBytes) { throw new ArgumentOutOfRangeException("payload", "Payload of " + payload.Length + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } bool flag = false; byte[] array = payload.Raw; if (payload.Length >= 512) { byte[] array2 = Deflate(array); if (array2.Length < array.Length) { array = array2; flag = true; } } byte b = checked((byte)((flag ? 1 : 0) | (header.Admin ? 4 : 0))); if (array.Length <= Envelope.SingleBodyLimit(limits.MaxFrameBytes)) { return new byte[1][] { Build(header, b, payload.Length, null, array, 0, array.Length) }; } int num = Envelope.ChunkBodyLimit(limits.MaxFrameBytes); int num2 = checked(array.Length + num - 1) / num; if (num2 > limits.MaxChunks) { throw new ArgumentOutOfRangeException("payload", "Payload needs " + num2 + " chunks; the limit is " + limits.MaxChunks + "."); } byte[][] array3 = new byte[num2][]; checked { for (int i = 0; i < num2; i++) { int num3 = i * num; int length = Math.Min(num, array.Length - num3); array3[i] = Build(header, (byte)(b | 2), payload.Length, new ChunkInfo(chunkId, i, num2, array.Length), array, num3, length); } return array3; } } public static bool TryDecode(byte[]? frame, FrameLimits limits, [NotNullWhen(true)] out Frame? decoded, [NotNullWhen(false)] out DecodeResult? failure) { decoded = null; failure = Check(frame, limits); if (failure != null) { return false; } Frame decoded2; DecodeResult decodeResult = Parse(frame, limits, out decoded2); if (decodeResult != null || decoded2 == null) { failure = decodeResult ?? DecodeResult.Reject(ErrorCode.Malformed, hard: true, "The envelope could not be read."); return false; } decoded = decoded2; failure = null; return true; } private static DecodeResult? Check(byte[]? frame, FrameLimits limits) { if (limits == null) { throw new ArgumentNullException("limits"); } if (frame == null || frame.Length < 2) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame is too short to hold an envelope."); } if ((frame[0] | (frame[1] << 8)) != 42782) { return DecodeResult.Dropped("Not an ALIVE frame (magic mismatch)."); } if (frame.Length < 48) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame of " + frame.Length + " bytes is shorter than an envelope."); } if (frame.Length > limits.MaxFrameBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Frame of " + frame.Length + " bytes exceeds the limit of " + limits.MaxFrameBytes + "."); } int num = checked(frame.Length - 4); WireReader wireReader = new WireReader(frame, num, 4); if (wireReader.ReadU32() != Crc32C.Compute(frame, 0, num)) { return DecodeResult.Reject(ErrorCode.BadCrc, hard: false, "CRC mismatch: the frame was corrupted or truncated."); } return null; } private static DecodeResult? Parse(byte[] frame, FrameLimits limits, out Frame? decoded) { decoded = null; checked { int num = frame.Length - 4; try { WireReader wireReader = new WireReader(frame, 2, num - 2); byte b = wireReader.ReadU8(); if (b != 1) { return DecodeResult.Reject(ErrorCode.UnsupportedEnvVersion, hard: false, "Envelope version " + b + " is not supported."); } byte b2 = wireReader.ReadU8(); if ((b2 & 0xF8) != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "Reserved flag bits were set."); } ushort msgType = wireReader.ReadU16(); byte msgVersion = wireReader.ReadU8(); if (wireReader.ReadU8() != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "The reserved header byte was not zero."); } uint seq = wireReader.ReadU32(); uint ackSeq = wireReader.ReadU32(); ulong sessionId = wireReader.ReadU64(); ByteString idemKey = wireReader.ReadFixed(16); uint num2 = wireReader.ReadU32(); if (num2 > (uint)limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Declared payload of " + num2 + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } ChunkInfo chunk = null; if ((b2 & 2) != 0) { uint chunkId = wireReader.ReadU32(); ushort num3 = wireReader.ReadU16(); ushort num4 = wireReader.ReadU16(); uint num5 = wireReader.ReadU32(); if (num4 == 0 || num4 > limits.MaxChunks) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunk count " + num4 + " is outside 1-" + limits.MaxChunks + "."); } if (num3 >= num4) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk index " + num3 + " is not below the count " + num4 + "."); } if (num5 == 0 || num5 > limits.MaxChunkedBodyBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked body of " + num5 + " bytes is outside the limit."); } if (wireReader.Remaining == 0) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk frame carried no bytes."); } chunk = new ChunkInfo(chunkId, num3, num4, (int)num5); } FrameHeader header = new FrameHeader { Admin = ((b2 & 4) != 0), MsgType = msgType, MsgVersion = msgVersion, Seq = seq, AckSeq = ackSeq, SessionId = sessionId, IdemKey = idemKey }; decoded = new Frame(header, (b2 & 1) != 0, (int)num2, chunk, wireReader.ReadRest()); return null; } catch (WireException ex) { return DecodeResult.Reject(ex.Code, hard: true, ex.Message); } } } public static DecodeResult DecodeSingle(byte[]? frame, FrameLimits limits) { if (!TryDecode(frame, limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk arrived where a single frame was required."); } return Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } internal static DecodeResult Open(FrameHeader header, byte[] body, bool compressed, int payloadLength) { if (!compressed) { if (body.Length != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Payload is " + body.Length + " bytes but declared " + payloadLength + "."); } return DecodeResult.Complete(header, ByteString.Own(body)); } checked { try { byte[] array = new byte[payloadLength]; using (MemoryStream stream = new MemoryStream(body, writable: false)) { using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); int i; int num; for (i = 0; i < payloadLength; i += num) { num = deflateStream.Read(array, i, payloadLength - i); if (num == 0) { break; } } if (i != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflated to " + i + " bytes but declared " + payloadLength + "."); } byte[] buffer = new byte[1]; if (deflateStream.Read(buffer, 0, 1) != 0) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflates beyond its declared " + payloadLength + " bytes."); } } return DecodeResult.Complete(header, ByteString.Own(array)); } catch (Exception ex) when (ex is InvalidDataException || ex is IOException || ex is NotSupportedException) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Compressed payload is not valid deflate: " + ex.Message); } } } private static byte[] Deflate(byte[] data) { using MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) { deflateStream.Write(data, 0, data.Length); } return memoryStream.ToArray(); } private static byte[] Build(FrameHeader h, byte flags, int payloadLength, ChunkInfo? chunk, byte[] body, int offset, int length) { checked { WireWriter wireWriter = new WireWriter(56 + length + 4); wireWriter.WriteU16(42782); wireWriter.WriteU8(1); wireWriter.WriteU8(flags); wireWriter.WriteU16(h.MsgType); wireWriter.WriteU8(h.MsgVersion); wireWriter.WriteU8(0); wireWriter.WriteU32(h.Seq); wireWriter.WriteU32(h.AckSeq); wireWriter.WriteU64(h.SessionId); wireWriter.WriteFixed(h.IdemKey, 16); wireWriter.WriteU32((uint)payloadLength); if (chunk != null) { wireWriter.WriteU32(chunk.ChunkId); wireWriter.WriteU16((ushort)chunk.Index); wireWriter.WriteU16((ushort)chunk.Count); wireWriter.WriteU32((uint)chunk.TotalLength); } wireWriter.WriteRaw(ByteString.CopyFrom(body, offset, length)); byte[] array = wireWriter.ToArray(); wireWriter.WriteU32(Crc32C.Compute(array, 0, array.Length)); return wireWriter.ToArray(); } } } public sealed class FrameHeader { public bool Admin { get; init; } public ushort MsgType { get; init; } public byte MsgVersion { get; init; } = 1; public uint Seq { get; init; } public uint AckSeq { get; init; } public ulong SessionId { get; init; } public ByteString IdemKey { get; init; } = ByteString.Zeros(16); public bool SameAs(FrameHeader other) { if (other != null && Admin == other.Admin && MsgType == other.MsgType && MsgVersion == other.MsgVersion && Seq == other.Seq && AckSeq == other.AckSeq && SessionId == other.SessionId) { return IdemKey.FixedTimeEquals(other.IdemKey); } return false; } } public sealed class FrameLimits { public static FrameLimits ServerToClient { get; } = new FrameLimits(8192, 4194304, 64); public static FrameLimits ClientToServer { get; } = new FrameLimits(8192, 262144, 8); public int MaxFrameBytes { get; } public int MaxPayloadBytes { get; } public int MaxChunks { get; } public long MaxChunkedBodyBytes { get { checked { return unchecked((long)MaxChunks) * unchecked((long)Envelope.ChunkBodyLimit(MaxFrameBytes)); } } } public FrameLimits(int maxFrameBytes, int maxPayloadBytes, int maxChunks) { if (maxFrameBytes < 1024) { throw new ArgumentOutOfRangeException("maxFrameBytes", "The protocol needs frames of at least 1 KiB."); } if (maxPayloadBytes < 1) { throw new ArgumentOutOfRangeException("maxPayloadBytes"); } if (maxChunks < 1 || maxChunks > 65535) { throw new ArgumentOutOfRangeException("maxChunks"); } MaxFrameBytes = maxFrameBytes; MaxPayloadBytes = maxPayloadBytes; MaxChunks = maxChunks; } } public sealed class FrameReceiver { private readonly FrameLimits _limits; public Reassembler Chunks { get; } public FrameReceiver(FrameLimits limits) { _limits = limits ?? throw new ArgumentNullException("limits"); Chunks = new Reassembler(limits, 4, 30000L, 8388608L); } public DecodeResult Receive(byte[]? frame, long nowMs) { if (!FrameCodec.TryDecode(frame, _limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return Chunks.Accept(decoded, nowMs); } return FrameCodec.Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } } public sealed class Reassembler { private sealed class Pending { internal Frame First { get; } internal long StartedMs { get; } internal long Order { get; } internal ByteString?[] Parts { get; } internal int Received { get; set; } internal int Bytes { get; set; } internal Pending(Frame first, long startedMs, long order) { First = first; StartedMs = startedMs; Order = order; Parts = new ByteString[first.Chunk.Count]; } internal bool Matches(Frame f) { ChunkInfo chunk = First.Chunk; ChunkInfo chunk2 = f.Chunk; if (chunk.Count == chunk2.Count && chunk.TotalLength == chunk2.TotalLength && First.Compressed == f.Compressed && First.PayloadLength == f.PayloadLength) { return First.Header.SameAs(f.Header); } return false; } } public const int DefaultMaxConcurrent = 4; public const long DefaultTtlMs = 30000L; public const long DefaultMemoryBudget = 8388608L; private readonly FrameLimits _limits; private readonly int _maxConcurrent; private readonly long _ttlMs; private readonly long _memoryBudget; private readonly Dictionary<uint, Pending> _pending = new Dictionary<uint, Pending>(); private long _order; public int PendingCount => _pending.Count; public long BufferedBytes { get; private set; } public int Evictions { get; private set; } public int Expirations { get; private set; } public Reassembler(FrameLimits limits, int maxConcurrent = 4, long ttlMs = 30000L, long memoryBudget = 8388608L) { _limits = limits ?? throw new ArgumentNullException("limits"); if (maxConcurrent < 1) { throw new ArgumentOutOfRangeException("maxConcurrent"); } if (ttlMs < 1) { throw new ArgumentOutOfRangeException("ttlMs"); } if (memoryBudget < 1) { throw new ArgumentOutOfRangeException("memoryBudget"); } _maxConcurrent = maxConcurrent; _ttlMs = ttlMs; _memoryBudget = memoryBudget; } public DecodeResult Accept(Frame frame, long nowMs) { if (frame == null) { throw new ArgumentNullException("frame"); } ChunkInfo chunkInfo = frame.Chunk ?? throw new ArgumentException("Not a chunk frame.", "frame"); if (chunkInfo.Count > _limits.MaxChunks || frame.PayloadLength > _limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked message " + chunkInfo.ChunkId + " exceeds this direction's limits."); } Expire(nowMs); checked { if (!_pending.TryGetValue(chunkInfo.ChunkId, out Pending value)) { while (_pending.Count >= _maxConcurrent) { Pending p = (from x in _pending.Values orderby x.StartedMs, x.Order select x).First(); Remove(p); Evictions++; } value = new Pending(frame, nowMs, _order++); _pending.Add(chunkInfo.ChunkId, value); } else if (!value.Matches(frame)) { Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " changed the message's header or chunk count mid-stream."); } ByteString byteString = value.Parts[chunkInfo.Index]; if (byteString != null) { if (byteString.FixedTimeEquals(frame.Body)) { return DecodeResult.Pending(); } Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " arrived twice with different bytes."); } if (BufferedBytes + frame.Body.Length > _memoryBudget) { Clear(); long memoryBudget = _memoryBudget; return DecodeResult.Reject(ErrorCode.MemoryBudget, hard: false, "Reassembly memory budget of " + memoryBudget + " bytes exhausted; all partial messages dropped."); } if (value.Bytes + frame.Body.Length > chunkInfo.TotalLength) { Remove(value); return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunks of message " + chunkInfo.ChunkId + " exceed its declared " + chunkInfo.TotalLength + " bytes."); } value.Parts[chunkInfo.Index] = frame.Body; value.Received++; value.Bytes += frame.Body.Length; BufferedBytes += frame.Body.Length; if (value.Received < chunkInfo.Count) { return DecodeResult.Pending(); } Remove(value); if (value.Bytes != chunkInfo.TotalLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Message " + chunkInfo.ChunkId + " reassembled to " + value.Bytes + " bytes but declared " + chunkInfo.TotalLength + "."); } byte[] array = new byte[value.Bytes]; int num = 0; ByteString[] parts = value.Parts; foreach (ByteString byteString2 in parts) { byteString2.CopyTo(array, num); num += byteString2.Length; } return FrameCodec.Open(value.First.Header, array, value.First.Compressed, value.First.PayloadLength); } } public void Expire(long nowMs) { checked { foreach (Pending item in _pending.Values.Where((Pending x) => nowMs - x.StartedMs > _ttlMs).ToList()) { Remove(item); Expirations++; } } } public void Clear() { _pending.Clear(); BufferedBytes = 0L; } private void Remove(Pending p) { checked { if (_pending.Remove(p.First.Chunk.ChunkId)) { BufferedBytes -= p.Bytes; } } } } public sealed class ReplayWindow { public const int Width = 64; private ulong _seen; public uint Highest { get; private set; } public long Rejected { get; private set; } public bool Accept(uint seq) { uint num2; checked { if (seq == 0) { Rejected++; return false; } if (seq > Highest) { uint num = seq - Highest; _seen = ((num >= 64) ? 0 : (_seen << (int)num)); _seen |= 1uL; Highest = seq; return true; } num2 = Highest - seq; if (num2 >= 64) { Rejected++; return false; } } ulong num3 = (ulong)(1L << checked((int)num2)); checked { if ((_seen & num3) != 0L) { Rejected++; return false; } _seen |= num3; return true; } } } public sealed class WireException : Exception { public ErrorCode Code { get; } = ErrorCode.Malformed; public WireException() { } public WireException(string message) : base(message) { } public WireException(string message, Exception innerException) : base(message, innerException) { } public WireException(ErrorCode code, string message) : base(message) { Code = code; } } public sealed class WireReader { private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly byte[] _buffer; private readonly int _end; private int _position; public int Remaining => checked(_end - _position); public WireReader(byte[] buffer) : this(buffer, 0, (buffer != null) ? buffer.Length : 0) { } public WireReader(byte[] buffer, int offset, int count) { _buffer = buffer ?? throw new ArgumentNullException("buffer"); checked { if (offset < 0 || count < 0 || offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } _position = offset; _end = offset + count; } } public byte ReadU8() { Need(1, "u8"); return _buffer[checked(_position++)]; } public bool ReadBool() { byte b = ReadU8(); return b switch { 0 => false, 1 => true, _ => throw new WireException(ErrorCode.Malformed, "A bool field held " + b + "; only 0 and 1 are valid."), }; } public ushort ReadU16() { Need(2, "u16"); checked { int num = _buffer[_position] | (_buffer[_position + 1] << 8); _position += 2; return (ushort)num; } } public uint ReadU32() { Need(4, "u32"); uint num = 0u; for (int i = 0; i < 4; i = checked(i + 1)) { num |= (uint)checked(_buffer[_position + i] << 8 * i); } checked { _position += 4; return num; } } public ulong ReadU64() { Need(8, "u64"); ulong num = 0uL; for (int i = 0; i < 8; i = checked(i + 1)) { num |= (ulong)_buffer[checked(_position + i)] << checked(8 * i); } checked { _position += 8; return num; } } public long ReadI64() { return (long)ReadU64(); } public ByteString ReadFixed(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } Need(length, "byte[" + length + "]"); ByteString result = ByteString.CopyFrom(_buffer, _position, length); checked { _position += length; return result; } } public ByteString ReadRest() { ByteString result = ByteString.CopyFrom(_buffer, _position, Remaining); _position = _end; return result; } public ByteString ReadBlob(int maxBytes) { uint num = ReadU32(); checked { if (num > (uint)maxBytes) { throw new WireException(ErrorCode.SizeLimit, "A blob declared " + num + " bytes; the limit is " + maxBytes + "."); } return ReadFixed((int)num); } } public string ReadString(int maxBytes) { ushort num = ReadU16(); if (n
plugins/ALIVE.Server.Adapter.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using ALIVE.Client; using ALIVE.Core; using ALIVE.Core.Abstractions; using ALIVE.Core.Content; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Diagnostics; using ALIVE.Core.Life; using ALIVE.Core.Places; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using ALIVE.Server.Jobs; using ALIVE.Server.Persistence; using ALIVE.Server.Platform; using ALIVE.Server.Quests; using ALIVE.Server.Rewards; using ALIVE.Server.Sessions; using ALIVE.Server.Tills; using ALIVE.Server.Web; using ALIVE.Server.World; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Entities; using Jotunn.Managers; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Server.Adapter")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ALIVE.Client { [HarmonyPatch] internal static class PlaceCreaturePatches { private const float Ahead = 1.5f; private const float KindFor = 5f; private const float NoteEvery = 60f; internal const ushort SpawnRules = 1792; private static readonly FieldRef<BaseAI, Character> AiCharacter = AccessTools.FieldRefAccess<BaseAI, Character>("m_character"); private static readonly FieldRef<MonsterAI, Character> TargetCreature = AccessTools.FieldRefAccess<MonsterAI, Character>("m_targetCreature"); private static readonly FieldRef<MonsterAI, StaticTarget> TargetStatic = AccessTools.FieldRefAccess<MonsterAI, StaticTarget>("m_targetStatic"); private static readonly FieldRef<Procreation, Tameable> Tamer = AccessTools.FieldRefAccess<Procreation, Tameable>("m_tameable"); private static readonly FieldRef<Procreation, GameObject> Offspring = AccessTools.FieldRefAccess<Procreation, GameObject>("m_offspring"); private static readonly FieldRef<EggGrow, GameObject> Grown = AccessTools.FieldRefAccess<EggGrow, GameObject>("m_grownPrefab"); private static readonly FieldRef<EggGrow, bool> EggTamed = AccessTools.FieldRefAccess<EggGrow, bool>("m_tamed"); private static readonly FieldRef<SpawnAbility, Character> Summoner = AccessTools.FieldRefAccess<SpawnAbility, Character>("m_owner"); private static readonly FieldRef<SpawnAbility, GameObject[]> Summoned = AccessTools.FieldRefAccess<SpawnAbility, GameObject[]>("m_spawnPrefab"); private static readonly FieldInfo? NestPrefabs = AccessTools.Field(typeof(SpawnArea), "m_prefabs"); private static readonly Dictionary<int, (CreatureKind Kind, float Until)> Kinds = new Dictionary<int, (CreatureKind, float)>(); private static readonly Dictionary<string, CreatureKind> PrefabKinds = new Dictionary<string, CreatureKind>(StringComparer.Ordinal); private static readonly Dictionary<string, float> Noted = new Dictionary<string, float>(StringComparer.Ordinal); private static FieldInfo? _nestPrefab; private static bool _saidFailed; private static Func<ProtectionView?>? _views; private static Func<Character, bool>? _ours; private static Action<string>? _tell; private static IAliveLog? _log; private static DebugLog? _debug; private static string _game = "this game"; private const ushort EnterRules = 14336; internal static ProtectionView? View => _views?.Invoke(); internal static IAliveLog? Log => _log; internal static DebugLog? GameDebug => _debug; internal static string Game => _game; internal static void Use(Func<ProtectionView?> views, IAliveLog? log, DebugLog debug, string game, Func<Character, bool>? ours, Action<string>? tell) { _views = views; _log = log; _debug = debug; _game = (string.IsNullOrEmpty(game) ? "this game" : game); _ours = ours; _tell = tell; } [HarmonyPrefix] [HarmonyPatch(typeof(SpawnSystem), "Spawn")] private static bool WorldSpawn(SpawnData __0, Vector3 __1) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) try { if (__0 == null) { return true; } PlaceItem val = NoSpawning(KindOfPrefab(__0.m_prefab), __1); if (val == null) { return true; } Note("the world's spawn", __0.m_prefab, KindOfPrefab(__0.m_prefab), val); return false; } catch (Exception e) { Failed(e); return true; } } [HarmonyPrefix] [HarmonyPatch(typeof(CreatureSpawner), "Spawn")] private static bool SpawnPoint(CreatureSpawner __instance, ref ZNetView? __result) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null) { return true; } PlaceItem val = NoSpawning(KindOfPrefab(__instance.m_creaturePrefab), ((Component)__instance).transform.position); if (val == null) { return true; } Note("a spawn point", __instance.m_creaturePrefab, KindOfPrefab(__instance.m_creaturePrefab), val); __result = null; return false; } catch (Exception e) { Failed(e); return true; } } [HarmonyPrefix] [HarmonyPatch(typeof(SpawnArea), "SpawnOne")] private static bool Nest(SpawnArea __instance, ref bool __result) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null || (object)NestPrefabs == null || View == null || (View.CreatureRules & 0x3F00) == 0) { return true; } if (!(NestPrefabs.GetValue(__instance) is IList list)) { return true; } Vector3 position = ((Component)__instance).transform.position; foreach (object item in list) { if (item == null) { continue; } if ((object)_nestPrefab == null) { _nestPrefab = AccessTools.Field(item.GetType(), "m_prefab"); } object? obj = _nestPrefab?.GetValue(item); GameObject val = (GameObject)((obj is GameObject) ? obj : null); if (val != null) { PlaceItem val2 = NoSpawning(KindOfPrefab(val), position); if (val2 != null) { Note("a nest", val, KindOfPrefab(val), val2); __result = false; return false; } } } return true; } catch (Exception e) { Failed(e); return true; } } [HarmonyPrefix] [HarmonyPatch(typeof(Procreation), "Procreate")] private static bool Born(Procreation __instance) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0047: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null) { return true; } Tameable val = Tamer.Invoke(__instance); CreatureKind kind = (CreatureKind)(((Object)(object)val != (Object)null && val.IsTamed()) ? 3 : ((int)KindOfPrefab(Offspring.Invoke(__instance)))); return !Held(kind, ((Component)__instance).transform.position); } catch (Exception e) { Failed(e); return true; } } [HarmonyPostfix] [HarmonyPatch(typeof(EggGrow), "CanGrow")] private static void Hatch(EggGrow __instance, ref bool __result) { //IL_0029: 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_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) try { if (__result && !((Object)(object)__instance == (Object)null)) { CreatureKind kind = (CreatureKind)(EggTamed.Invoke(__instance) ? 3 : ((int)KindOfPrefab(Grown.Invoke(__instance)))); if (Held(kind, ((Component)__instance).transform.position)) { __result = false; } } } catch (Exception e) { Failed(e); } } [HarmonyPrefix] [HarmonyPatch(typeof(SpawnAbility), "Spawn")] private static bool Summon(SpawnAbility __instance, ref IEnumerator __result) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_00c4: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null) { return true; } Character val = Summoner.Invoke(__instance); GameObject[] array = Summoned.Invoke(__instance); CreatureKind kind = (CreatureKind)(((Object)(object)val != (Object)null && (val.IsPlayer() || val.IsTamed())) ? 3 : ((int)KindOfPrefab((array != null && array.Length != 0) ? array[0] : null))); PlaceItem val2 = NoSpawning(kind, ((Component)__instance).transform.position); if (val2 == null) { return true; } if ((Object)(object)val != (Object)null && (Object)(object)val == (Object)(object)Player.m_localPlayer) { _tell?.Invoke("Nothing can be summoned in " + val2.Name + "."); } Note("a summons", (array != null && array.Length != 0) ? array[0] : null, kind, val2); __result = Nothing(); ZNetView component = ((Component)__instance).GetComponent<ZNetView>(); if ((Object)(object)component == (Object)null) { Object.Destroy((Object)(object)((Component)__instance).gameObject); } else if (component.IsValid() && component.IsOwner() && (Object)(object)ZNetScene.instance != (Object)null) { ZNetScene.instance.Destroy(((Component)__instance).gameObject); } return false; } catch (Exception e) { Failed(e); return true; } } [HarmonyPrefix] [HarmonyPatch(typeof(BaseAI), "MoveTowards")] private static void Step(BaseAI __instance, ref Vector3 __0) { TurnBack(__instance, ref __0); } [HarmonyPrefix] [HarmonyPatch(typeof(BaseAI), "MoveTowardsSwoop")] private static void Swoop(BaseAI __instance, ref Vector3 __0) { TurnBack(__instance, ref __0); } [HarmonyPostfix] [HarmonyPatch(typeof(BaseAI), "IsValidRandomMovePoint")] private static void Wander(BaseAI __instance, Vector3 __0, ref bool __result) { //IL_0049: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_0079: Unknown result type (might be due to invalid IL or missing references) try { if (!__result || (Object)(object)__instance == (Object)null) { return; } ProtectionView view = View; if (view == null || (view.CreatureRules & 0x3800) == 0) { return; } Character val = AiCharacter.Invoke(__instance); if (!((Object)(object)val == (Object)null)) { Vector3 position = ((Component)val).transform.position; (double, double) tuple = default((double, double)); if (view.KeepsOut(KindOf(val), (double)position.x, (double)position.y, (double)position.z, (double)__0.x, (double)__0.y, (double)__0.z, ref tuple)) { __result = false; } } } catch (Exception e) { Failed(e); } } [HarmonyPostfix] [HarmonyPatch(typeof(MonsterAI), "UpdateTarget")] private static void Target(MonsterAI __instance) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_007f: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: 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_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010e: 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) try { if ((Object)(object)__instance == (Object)null) { return; } ProtectionView view = View; if (view == null || (view.CreatureRules & 0x3800) == 0) { return; } Character val = AiCharacter.Invoke((BaseAI)(object)__instance); if ((Object)(object)val == (Object)null) { return; } CreatureKind val2 = KindOf(val); if ((int)val2 == 0) { return; } Vector3 position = ((Component)val).transform.position; Character val3 = TargetCreature.Invoke(__instance); if ((Object)(object)val3 != (Object)null) { Vector3 position2 = ((Component)val3).transform.position; if (view.TargetKeptAway(val2, (double)position.x, (double)position.y, (double)position.z, (double)position2.x, (double)position2.y, (double)position2.z)) { TargetCreature.Invoke(__instance) = null; } } StaticTarget val4 = TargetStatic.Invoke(__instance); if ((Object)(object)val4 != (Object)null) { Vector3 position3 = ((Component)val4).transform.position; if (view.TargetKeptAway(val2, (double)position.x, (double)position.y, (double)position.z, (double)position3.x, (double)position3.y, (double)position3.z)) { TargetStatic.Invoke(__instance) = null; } } } catch (Exception e) { Failed(e); } } private static void TurnBack(BaseAI ai, ref Vector3 dir) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_0090: 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_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_00a7: 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_00b0: 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_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: 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_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_010e: 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) try { if ((Object)(object)ai == (Object)null) { return; } ProtectionView view = View; if (view == null || (view.CreatureRules & 0x3800) == 0) { return; } Character val = AiCharacter.Invoke(ai); if ((Object)(object)val == (Object)null) { return; } CreatureKind val2 = KindOf(val); if ((int)val2 == 0) { return; } Vector3 val3 = default(Vector3); ((Vector3)(ref val3))..ctor(dir.x, 0f, dir.z); if (!(((Vector3)(ref val3)).sqrMagnitude < 1E-06f)) { Vector3 position = ((Component)val).transform.position; Vector3 val4 = position + ((Vector3)(ref val3)).normalized * 1.5f; (double, double) tuple = default((double, double)); if (view.KeepsOut(val2, (double)position.x, (double)position.y, (double)position.z, (double)val4.x, (double)position.y, (double)val4.z, ref tuple)) { dir = new Vector3((float)tuple.Item1, 0f, (float)tuple.Item2) * Mathf.Max(((Vector3)(ref dir)).magnitude, 0.1f); } } } catch (Exception e) { Failed(e); } } private static bool Held(CreatureKind kind, 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) return NoSpawning(kind, at) != null; } internal static PlaceItem? NoSpawning(CreatureKind kind, Vector3 at) { //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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) ProtectionView view = View; if (view == null || !view.Known || (int)kind == 0) { return null; } return view.NoSpawning(kind, (double)at.x, (double)at.y, (double)at.z); } internal static CreatureKind KindOf(Character c) { //IL_0053: 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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)c == (Object)null) { return (CreatureKind)0; } int instanceID = ((Object)c).GetInstanceID(); float time = Time.time; if (Kinds.TryGetValue(instanceID, out (CreatureKind, float) value) && value.Item2 > time) { return value.Item1; } if (Kinds.Count > 4000) { Kinds.Clear(); } CreatureKind val = Work(c); Kinds[instanceID] = (val, time + 5f); return val; } private static CreatureKind Work(Character c) { if (!c.IsPlayer() && !c.IsBoss()) { if (_ours != null && _ours(c)) { return (CreatureKind)0; } ZNetView component = ((Component)c).GetComponent<ZNetView>(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (val != null && (val.GetString("alive_creature", string.Empty).Length > 0 || val.GetString("alive_npc", string.Empty).Length > 0 || val.GetString("alive_sentry_of", string.Empty).Length > 0)) { return (CreatureKind)0; } if (!c.IsTamed()) { if (Animal(((Component)c).gameObject, c)) { return (CreatureKind)2; } return (CreatureKind)1; } return (CreatureKind)3; } return (CreatureKind)0; } private static CreatureKind KindOfPrefab(GameObject? prefab) { //IL_001f: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)prefab == (Object)null) { return (CreatureKind)0; } if (PrefabKinds.TryGetValue(((Object)prefab).name, out var value)) { return value; } Character component = prefab.GetComponent<Character>(); CreatureKind val = (CreatureKind)((!((Object)(object)component == (Object)null) && !component.IsPlayer() && !component.IsBoss()) ? ((!Animal(prefab, component)) ? 1 : 2) : 0); PrefabKinds[((Object)prefab).name] = val; return val; } private static bool Animal(GameObject go, Character c) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 if (!((Object)(object)go.GetComponent<AnimalAI>() != (Object)null) && !((Object)(object)go.GetComponent<Tameable>() != (Object)null) && (int)c.m_faction != 1) { return ((Object)go).name.StartsWith("Neck", StringComparison.Ordinal); } return true; } private static IEnumerator Nothing() { yield break; } private static void Note(string what, GameObject? prefab, CreatureKind kind, PlaceItem place) { //IL_00f1: Unknown result type (might be due to invalid IL or missing references) DebugLog debug = _debug; if (debug == null || !debug.On((DebugArea)8)) { return; } string text = (((Object)(object)prefab == (Object)null) ? "a creature" : ((Object)prefab).name); string key = what + "|" + text + "|" + place.Id.ToString(CultureInfo.InvariantCulture); float time = Time.time; if (!Noted.TryGetValue(key, out var value) || !(time - value < 60f)) { if (Noted.Count > 500) { Noted.Clear(); } Noted[key] = time; debug.Write((DebugArea)8, what + " in " + _game + " did not make " + text + " in '" + place.Name + "', where " + Words(kind) + " do not spawn"); } } internal static string Words(CreatureKind kind) { //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_0014: Expected I4, but got Unknown return (kind - 1) switch { 0 => "hostile monsters", 1 => "wild animals", 2 => "tamed and summoned creatures", _ => "creatures", }; } internal static void Failed(Exception e) { if (!_saidFailed) { _saidFailed = true; IAliveLog? log = _log; if (log != null) { log.Warning("ALIVE: a check of creatures in protected places failed in " + _game + " and let the game go ahead: " + e.Message); } } } } [HarmonyPatch] internal static class PlaceCreatureBirths { private const long NewFor = 30000000L; private const int LogMost = 30; private const int WaysMost = 128; private const int WayFrames = 8; private static readonly Dictionary<int, string> Ways = new Dictionary<int, string>(); private static int _logged; [HarmonyPrefix] [HarmonyPatch(typeof(BaseAI), "Awake")] private static void Woken(BaseAI __instance) { //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) try { ProtectionView view = PlaceCreaturePatches.View; if ((Object)(object)__instance == (Object)null || view == null || !view.Known || (view.CreatureRules & 0x700) == 0) { return; } ZNetView component = ((Component)__instance).GetComponent<ZNetView>(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || component.GetZDO().GetLong(ZDOVars.s_spawnTime, 0L) != 0L) { return; } Vector3 position = ((Component)__instance).transform.position; if (view.Protects((ushort)1792, (double)position.x, (double)position.y, (double)position.z) != null) { if (Ways.Count >= 128) { Ways.Clear(); } Ways[((Object)((Component)__instance).gameObject).GetInstanceID()] = Way(); } } catch (Exception e) { PlaceCreaturePatches.Failed(e); } } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "Start")] private static void Started(Character __instance) { Check(__instance); } [HarmonyPostfix] [HarmonyPatch(typeof(Humanoid), "Start")] private static void HumanoidStarted(Humanoid __instance) { Check((Character)(object)__instance); } private static void Check(Character c) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0122: 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) try { if ((Object)(object)c == (Object)null) { return; } int instanceID = ((Object)((Component)c).gameObject).GetInstanceID(); Ways.TryGetValue(instanceID, out string value); if (value != null) { Ways.Remove(instanceID); } ProtectionView view = PlaceCreaturePatches.View; if (view == null || !view.Known || (view.CreatureRules & 0x700) == 0) { return; } ZNetView component = ((Component)c).GetComponent<ZNetView>(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || (Object)(object)ZNet.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null) { return; } long num = component.GetZDO().GetLong(ZDOVars.s_spawnTime, 0L); if (num != 0L && Math.Abs(checked(ZNet.instance.GetTime().Ticks - num)) <= 30000000) { Vector3 position = ((Component)c).transform.position; CreatureKind kind = PlaceCreaturePatches.KindOf(c); PlaceItem val = PlaceCreaturePatches.NoSpawning(kind, position); if (val != null) { Say(Utils.GetPrefabName(((Component)c).gameObject) + " made at " + Spot(position) + " in '" + val.Name + "', where " + PlaceCreaturePatches.Words(kind) + " do not spawn, was removed in " + PlaceCreaturePatches.Game + "; it was made by " + (value ?? "a way not seen as it woke")); ZNetScene.instance.Destroy(((Component)c).gameObject); } } } catch (Exception e) { PlaceCreaturePatches.Failed(e); } } private static void Say(string line) { checked { if (_logged < 30) { _logged++; IAliveLog? log = PlaceCreaturePatches.Log; if (log != null) { log.Info("ALIVE: " + line + ((_logged == 30) ? " (no more of these in this log this session; the debug log's Places has every one)" : string.Empty)); } } else { DebugLog gameDebug = PlaceCreaturePatches.GameDebug; if (gameDebug != null && gameDebug.On((DebugArea)8)) { gameDebug.Write((DebugArea)8, line); } } } } private static string Way() { StackFrame[] frames = new StackTrace(2, fNeedFileInfo: false).GetFrames(); if (frames == null) { return "a way not known"; } List<string> list = new List<string>(); StackFrame[] array = frames; foreach (StackFrame stackFrame in array) { MethodBase method = stackFrame.GetMethod(); if ((object)method == null) { continue; } string text = method.DeclaringType?.Name ?? string.Empty; if (!(text == "Object") && !(text == "PlaceCreatureBirths")) { list.Add((text.Length > 0) ? (text + "." + method.Name) : method.Name); if (list.Count >= 8) { break; } } } if (list.Count != 0) { return string.Join(" < ", list); } return "a way not known"; } private static string Spot(Vector3 at) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) return "(" + Mathf.RoundToInt(at.x).ToString(CultureInfo.InvariantCulture) + ", " + Mathf.RoundToInt(at.z).ToString(CultureInfo.InvariantCulture) + ")"; } } [HarmonyPatch] internal static class PieceShieldPatches { private static bool _saidFailed; [HarmonyPrefix] [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] private static bool Hit(WearNTear __instance) { return !Shielded(__instance); } [HarmonyPrefix] [HarmonyPatch(typeof(WearNTear), "ApplyDamage")] private static bool Wear(WearNTear __instance, ref bool __result) { if (!Shielded(__instance)) { return true; } __result = false; return false; } private static bool Shielded(WearNTear piece) { //IL_0049: 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_0051: 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_005f: Unknown result type (might be due to invalid IL or missing references) try { ProtectionView view = PlaceCreaturePatches.View; if ((Object)(object)piece == (Object)null || view == null || !view.Known) { return false; } string text = Uid(((Component)piece).gameObject); if (text.Length > 0 && view.IsLocked(text)) { return true; } Vector3 position = ((Component)piece).transform.position; return view.Protects((ushort)4, (double)position.x, (double)position.y, (double)position.z) != null; } catch (Exception ex) { if (!_saidFailed) { _saidFailed = true; IAliveLog? log = PlaceCreaturePatches.Log; if (log != null) { log.Warning("ALIVE: keeping a piece from damage failed in " + PlaceCreaturePatches.Game + " and let the game go ahead: " + ex.Message); } } return false; } } private static string Uid(GameObject go) { if ((Object)(object)go == (Object)null) { return string.Empty; } ZNetView componentInParent = go.GetComponentInParent<ZNetView>(); if ((Object)(object)componentInParent == (Object)null || !componentInParent.IsValid()) { return string.Empty; } ZDO zDO = componentInParent.GetZDO(); if (zDO != null) { return ((ZDOID)(ref zDO.m_uid)).UserID.ToString(CultureInfo.InvariantCulture) + ":" + ((ZDOID)(ref zDO.m_uid)).ID.ToString(CultureInfo.InvariantCulture); } return string.Empty; } } [HarmonyPatch] internal static class CreaturePatches { private static bool _saidFailed; [HarmonyPostfix] [HarmonyPatch(typeof(Character), "Awake")] private static void Awake(Character __instance) { //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0144: 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_010b: 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) try { if ((Object)(object)__instance == (Object)null || __instance.IsPlayer()) { return; } ZNetView component = ((Component)__instance).GetComponent<ZNetView>(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } ZDO zDO = component.GetZDO(); if (zDO != null && zDO.GetString("alive_creature", string.Empty).Length != 0) { AliveCreatureMark aliveCreatureMark = ((Component)__instance).gameObject.GetComponent<AliveCreatureMark>(); if ((Object)(object)aliveCreatureMark == (Object)null) { aliveCreatureMark = ((Component)__instance).gameObject.AddComponent<AliveCreatureMark>(); } aliveCreatureMark.View = component; aliveCreatureMark.Damage = Mathf.Clamp(zDO.GetFloat("alive_cr_damage", 1f), 0.1f, 20f); aliveCreatureMark.Passive = zDO.GetInt("alive_cr_passive", 0) == 1; aliveCreatureMark.NoDrops = zDO.GetInt("alive_cr_nodrops", 0) == 1; float num = zDO.GetFloat("alive_cr_scale", 1f); if (num >= 0.25f && num <= 4f && Mathf.Abs(num - 1f) > 0.001f) { Transform transform = ((Component)__instance).transform; transform.localScale *= num; } string text = zDO.GetString("alive_cr_faction", string.Empty); if (text.Length > 0 && Enum.TryParse<Faction>(text, ignoreCase: false, out Faction result)) { __instance.m_faction = result; } string text2 = zDO.GetString("alive_cr_resist", string.Empty); if (text2.Length > 0) { __instance.m_damageModifiers = Resist(__instance.m_damageModifiers, text2); } } } catch (Exception ex) { if (!_saidFailed) { _saidFailed = true; IAliveLog? log = PlaceCreaturePatches.Log; if (log != null) { log.Warning("ALIVE: a creature's changes could not be applied in " + PlaceCreaturePatches.Game + ": " + ex.Message); } } } } [HarmonyPostfix] [HarmonyPatch(typeof(Attack), "GetLevelDamageFactor")] private static void Damage(Humanoid ___m_character, ref float __result) { if (!((Object)(object)___m_character == (Object)null)) { AliveCreatureMark component = ((Component)___m_character).GetComponent<AliveCreatureMark>(); if ((Object)(object)component != (Object)null) { __result *= component.Damage; } } } [HarmonyPrefix] [HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")] private static bool Drops(CharacterDrop __instance, ref List<KeyValuePair<GameObject, int>> __result) { AliveCreatureMark aliveCreatureMark = (((Object)(object)__instance == (Object)null) ? null : ((Component)__instance).GetComponent<AliveCreatureMark>()); if ((Object)(object)aliveCreatureMark == (Object)null || !aliveCreatureMark.NoDrops) { return true; } __result = new List<KeyValuePair<GameObject, int>>(); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[] { typeof(Character), typeof(Character) })] private static void Enemy(Character a, Character b, ref bool __result) { if (__result && (Calm(a, b) || Calm(b, a))) { __result = false; } } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "ApplyDamage")] private static void Hurt(Character __instance, HitData hit) { try { AliveCreatureMark aliveCreatureMark = (((Object)(object)__instance == (Object)null) ? null : ((Component)__instance).GetComponent<AliveCreatureMark>()); if ((Object)(object)aliveCreatureMark == (Object)null || !aliveCreatureMark.Passive || hit == null) { return; } Character attacker = hit.GetAttacker(); if ((Object)(object)attacker == (Object)null || !attacker.IsPlayer()) { return; } ZNetView view = aliveCreatureMark.View; if (!((Object)(object)view == (Object)null) && view.IsValid() && view.IsOwner()) { ZDO zDO = view.GetZDO(); if (!zDO.GetBool("alive_cr_angry", false)) { zDO.Set("alive_cr_angry", true); } } } catch (Exception) { } } private static bool Calm(Character creature, Character other) { if ((Object)(object)creature == (Object)null || (Object)(object)other == (Object)null || !other.IsPlayer()) { return false; } AliveCreatureMark component = ((Component)creature).GetComponent<AliveCreatureMark>(); if ((Object)(object)component != (Object)null && component.Passive) { return !component.Angry; } return false; } private static DamageModifiers Resist(DamageModifiers mods, string text) { //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: 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_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: 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_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0213: 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_021c: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) string[] array = text.Split(','); foreach (string text2 in array) { int num = text2.IndexOf('='); if (num <= 0) { continue; } string text3 = text2.Substring(0, num).Trim(); if (Modifier(text2.Substring(checked(num + 1)).Trim(), out var modifier)) { switch (text3) { case "blunt": mods.m_blunt = modifier; break; case "slash": mods.m_slash = modifier; break; case "pierce": mods.m_pierce = modifier; break; case "chop": mods.m_chop = modifier; break; case "pickaxe": mods.m_pickaxe = modifier; break; case "fire": mods.m_fire = modifier; break; case "frost": mods.m_frost = modifier; break; case "lightning": mods.m_lightning = modifier; break; case "poison": mods.m_poison = modifier; break; case "spirit": mods.m_spirit = modifier; break; } } } return mods; } private static bool Modifier(string word, out DamageModifier modifier) { switch (word) { case "normal": modifier = (DamageModifier)0; return true; case "resistant": modifier = (DamageModifier)1; return true; case "very_resistant": modifier = (DamageModifier)5; return true; case "slightly_resistant": modifier = (DamageModifier)7; return true; case "weak": modifier = (DamageModifier)2; return true; case "very_weak": modifier = (DamageModifier)6; return true; case "slightly_weak": modifier = (DamageModifier)8; return true; case "immune": modifier = (DamageModifier)3; return true; case "ignore": modifier = (DamageModifier)4; return true; default: modifier = (DamageModifier)0; return false; } } } internal sealed class AliveCreatureMark : MonoBehaviour { internal ZNetView? View { get; set; } internal float Damage { get; set; } = 1f; internal bool Passive { get; set; } internal bool NoDrops { get; set; } internal bool Angry { get { ZNetView view = View; if ((Object)(object)view != (Object)null && view.IsValid()) { return view.GetZDO().GetBool("alive_cr_angry", false); } return false; } } } internal static class OtherMods { private static readonly object[] Off = new object[1] { false }; private static bool _lookedForEpicLoot; private static MethodInfo? _epicLootDrops; private static bool _saidEpicLoot; internal static void NoEpicLootDrops(IAliveLog? log) { try { if (!_lookedForEpicLoot) { _lookedForEpicLoot = true; Type type = AccessTools.TypeByName("EpicLoot.EpicLootDropsHelper"); _epicLootDrops = (((object)type == null) ? null : AccessTools.PropertySetter(type, "InstantDropsEnabled")); if (type != null && (object)_epicLootDrops == null) { _saidEpicLoot = true; if (log != null) { log.Warning("ALIVE: this Epic Loot has no 'InstantDropsEnabled' to turn off, so a sentry's kill may still drop its magic items."); } } } _epicLootDrops?.Invoke(null, Off); } catch (Exception ex) { if (!_saidEpicLoot) { _saidEpicLoot = true; if (log != null) { log.Warning("ALIVE: Epic Loot's drops could not be turned off for a sentry's kill: " + ex.Message); } } } } } internal static class SentryBodyPrefab { private static readonly string[] SentryMinds = new string[4] { "Skeleton", "Draugr", "Goblin", "Dverger" }; private static readonly string[] PlayerParts = new string[3] { "PlayerController", "Talker", "Skills" }; private const BindingFlags Fields = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; internal static bool Build(Action<GameObject> finish, out string said) { //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Expected O, but got Unknown //IL_0324: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Expected O, but got Unknown //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Expected O, but got Unknown //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Expected O, but got Unknown //IL_03e9: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_0441: Expected O, but got Unknown GameObject val = PrefabManager.Instance.CreateClonedPrefab("ALIVE_Sentry", "Player"); Player val2 = (((Object)(object)val == (Object)null) ? null : val.GetComponent<Player>()); if (val == null || (Object)(object)val2 == (Object)null) { said = "this game has no player body to make a sentry's fighting body from"; return false; } List<string> list = new List<string>(); MonoBehaviour[] components = val.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour val3 in components) { if (!((Object)(object)val3 == (Object)null) && Array.IndexOf(PlayerParts, ((object)val3).GetType().Name) >= 0) { list.Add(((object)val3).GetType().Name); Object.DestroyImmediate((Object)(object)val3); } } List<(Type, List<(FieldInfo, object)>)> list2 = new List<(Type, List<(FieldInfo, object)>)>(); MonoBehaviour[] components2 = val.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour val4 in components2) { if (!((Object)(object)val4 == (Object)null) && !(val4 is Player) && NeedsCharacter(((object)val4).GetType())) { list2.Add((((object)val4).GetType(), Values(val4, ((object)val4).GetType(), typeof(MonoBehaviour)))); } } foreach (var item2 in list2) { Type item = item2.Item1; Object.DestroyImmediate((Object)(object)val.GetComponent(item)); } List<(FieldInfo, object)> values = Values(val2, typeof(Humanoid), typeof(MonoBehaviour)); Object.DestroyImmediate((Object)(object)val2); if ((Object)(object)val.GetComponent<Player>() != (Object)null) { said = "the player could not be taken off a sentry's fighting body"; return false; } list.Add("Player"); Humanoid val5 = val.AddComponent<Humanoid>(); Apply(val5, values); foreach (var (type, values2) in list2) { Apply(val.AddComponent(type), values2); } ((Character)val5).m_name = "Sentry"; ((Character)val5).m_group = "alive_sentry"; ((Character)val5).m_faction = (Faction)0; ((Character)val5).m_boss = false; ((Character)val5).m_health = 300f; ((Character)val5).m_runSpeed = Mathf.Min(((Character)val5).m_runSpeed, 6f); val5.m_defaultItems = Array.Empty<GameObject>(); val5.m_randomWeapon = Array.Empty<GameObject>(); val5.m_randomArmor = Array.Empty<GameObject>(); val5.m_randomShield = Array.Empty<GameObject>(); val5.m_randomSets = Array.Empty<ItemSet>(); val5.m_randomItems = Array.Empty<RandomItem>(); string text = string.Empty; MonsterAI val6 = null; string[] sentryMinds = SentryMinds; foreach (string text2 in sentryMinds) { GameObject prefab = PrefabManager.Instance.GetPrefab(text2); val6 = (((Object)(object)prefab == (Object)null) ? null : prefab.GetComponent<MonsterAI>()); if (!((Object)(object)val6 == (Object)null)) { text = text2; break; } } MonsterAI val7 = val.AddComponent<MonsterAI>(); if ((Object)(object)val6 != (Object)null) { Apply(val7, Values(val6, typeof(MonsterAI), typeof(MonoBehaviour))); } ((BaseAI)val7).m_alertedEffects = new EffectList(); ((BaseAI)val7).m_idleSound = new EffectList(); val7.m_wakeupEffects = new EffectList(); val7.m_sleepEffects = new EffectList(); ((BaseAI)val7).m_spawnMessage = string.Empty; ((BaseAI)val7).m_deathMessage = string.Empty; ((BaseAI)val7).m_alertedMessage = string.Empty; val7.m_sleeping = false; val7.m_noiseWakeup = false; val7.m_enableHuntPlayer = false; val7.m_attackPlayerObjects = false; ((BaseAI)val7).m_aggravatable = false; ((BaseAI)val7).m_passiveAggresive = false; val7.m_fleeIfHurtWhenTargetCantBeReached = false; val7.m_fleeIfNotAlerted = false; val7.m_fleeIfLowHealth = 0f; ((BaseAI)val7).m_afraidOfFire = false; ((BaseAI)val7).m_avoidFire = true; ((BaseAI)val7).m_avoidWater = true; val7.m_consumeItems = new List<ItemDrop>(); ((BaseAI)val7).m_randomMoveRange = 2f; ((BaseAI)val7).m_pathAgentType = (AgentType)1; val7.m_circulateWhileCharging = false; finish(val); ZNetView component = val.GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null) { component.m_persistent = false; } int num = LayerMask.NameToLayer("character"); if (num >= 0) { val.layer = num; } PrefabManager.Instance.AddPrefab(new CustomPrefab(val, false)); List<string> list3 = new List<string>(); MonoBehaviour[] components3 = val.GetComponents<MonoBehaviour>(); foreach (MonoBehaviour val8 in components3) { list3.Add(((object)val8).GetType().Name); } said = "a humanoid with " + ((text.Length > 0) ? ("a " + text + "'s") : "a creature's") + " mind; has " + string.Join(", ", list3) + "; took off " + string.Join(", ", list) + ((list2.Count > 0) ? ("; put back " + list2.Count + " part(s) that need a character") : string.Empty) + "; " + val.GetComponentsInChildren<Collider>(true).Length + " collider(s)"; return true; } private static bool NeedsCharacter(Type type) { object[] customAttributes = type.GetCustomAttributes(typeof(RequireComponent), inherit: true); foreach (object obj in customAttributes) { RequireComponent val = (RequireComponent)((obj is RequireComponent) ? obj : null); if (val != null && (Needs(val.m_Type0) || Needs(val.m_Type1) || Needs(val.m_Type2))) { return true; } } return false; } private static bool Needs(Type? t) { if (t != null) { return t.IsAssignableFrom(typeof(Player)); } return false; } private static List<(FieldInfo Field, object? Value)> Values(object from, Type type, Type stopAt) { List<(FieldInfo, object)> list = new List<(FieldInfo, object)>(); Type type2 = type; while (type2 != null && type2 != stopAt) { FieldInfo[] fields = type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { list.Add((fieldInfo, fieldInfo.GetValue(from))); } type2 = type2.BaseType; } return list; } private static void Apply(object to, List<(FieldInfo Field, object? Value)> values) { foreach (var (fieldInfo, value) in values) { if (fieldInfo.DeclaringType != null && fieldInfo.DeclaringType.IsInstanceOfType(to)) { fieldInfo.SetValue(to, value); } } } } internal static class SentrySides { internal static bool Hostile(Character c, Func<Character, bool> isSentry) { //IL_002d: 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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 if ((Object)(object)c == (Object)null || c.IsDead() || c.IsPlayer() || c.IsTamed() || isSentry(c)) { return false; } Faction faction = c.GetFaction(); if ((int)faction > 1) { if ((int)faction == 10) { BaseAI baseAI = c.GetBaseAI(); if ((Object)(object)baseAI != (Object)null) { return baseAI.IsAggravated(); } return false; } if (faction - 11 > 1) { return true; } } return false; } } [HarmonyPatch] internal static class SentryLoot { private const string EpicLootName = "characterName"; private const string EpicLootLuckyRolls = "el-lky-rolls"; private static readonly HashSet<CharacterDrop> Spoiled = new HashSet<CharacterDrop>(); internal static void Spoil(CharacterDrop? drops) { if ((Object)(object)drops == (Object)null) { return; } if (Spoiled.Count > 64) { Spoiled.RemoveWhere((CharacterDrop d) => (Object)(object)d == (Object)null); } Spoiled.Add(drops); } internal static bool IsSpoiled(CharacterDrop? drops) { if ((Object)(object)drops != (Object)null && Spoiled.Count > 0) { return Spoiled.Contains(drops); } return false; } [HarmonyPostfix] [HarmonyPriority(0)] [HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")] private static void Empty(CharacterDrop __instance, List<KeyValuePair<GameObject, int>> __result) { if (__result != null && IsSpoiled(__instance)) { __result.Clear(); } } [HarmonyPostfix] [HarmonyPriority(0)] [HarmonyAfter(new string[] { "randyknapp.mods.epicloot" })] [HarmonyPatch(typeof(Ragdoll), "Setup")] private static void Bare(CharacterDrop characterDrop, ZNetView ___m_nview) { if (!IsSpoiled(characterDrop) || (Object)(object)___m_nview == (Object)null || !___m_nview.IsValid()) { return; } ZDO zDO = ___m_nview.GetZDO(); if (zDO != null) { if (zDO.GetString("characterName", string.Empty).Length > 0) { zDO.Set("characterName", string.Empty); } if (zDO.GetInt("el-lky-rolls", 0) != 0) { zDO.Set("el-lky-rolls", 0); } } } } internal static class PovLink { private static bool _looked; private static PovFacts? _facts; private static MethodInfo? _rarityOf; private static MethodInfo? _modifiersOf; private static MethodInfo? _isPovBoss; private static MethodInfo? _leaveAlone; private static bool _saidRead; internal static PovFacts? Facts => _facts; internal static bool ReadsCreatures { get { if (_facts != null && _facts.Has("creatures") && _rarityOf != null && _modifiersOf != null) { return _isPovBoss != null; } return false; } } internal static PovFacts? Find(IAliveLog log, string where) { //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Expected O, but got Unknown if (_looked) { return _facts; } _looked = true; try { Assembly assembly = ApiAssembly(); Type type = assembly?.GetType("Valheiman.Api.Pov", throwOnError: false); if ((object)type == null) { log.Info("ALIVE: Path of Valheiman is not on " + where + ": PoV settings in quests and dialogue are kept and not used."); return null; } PluginInfo value; string modVersion = (Chainloader.PluginInfos.TryGetValue("treextr.pathofvalheiman", out value) ? value.Metadata.Version.ToString() : string.Empty); string apiVersion = Field(type, "ApiVersion")?.ToString() ?? Field(type, "Version")?.ToString() ?? string.Empty; string[] array = ((Field(type, "Features") is string[] source) ? source.Where((string f) => !string.IsNullOrEmpty(f)).ToArray() : Array.Empty<string>()); Type type2 = assembly.GetType("Valheiman.Api.Creatures", throwOnError: false); Type typeFromHandle = typeof(Character); _rarityOf = type2?.GetMethod("RarityOf", new Type[1] { typeFromHandle }); _modifiersOf = type2?.GetMethod("ModifiersOf", new Type[1] { typeFromHandle }); _isPovBoss = type2?.GetMethod("IsPovBoss", new Type[1] { typeFromHandle }); _leaveAlone = type2?.GetMethod("LeaveAlone", new Type[2] { typeof(string), typeof(string) }); PovFacts val = new PovFacts(); val.set_ModVersion(modVersion); val.set_ApiVersion(apiVersion); val.set_Features((IReadOnlyCollection<string>)(object)array); val.set_Modifiers(Modifiers(type2)); val.set_Professions(Professions(assembly.GetType("Valheiman.Api.Crafting", throwOnError: false))); _facts = val; log.Info("ALIVE: " + ((object)_facts)?.ToString() + " is on " + where + " (" + string.Join(", ", array) + ")."); return _facts; } catch (Exception ex) { log.Warning("ALIVE: Path of Valheiman could not be read on " + where + ", so ALIVE's PoV parts are off here: " + ex.Message); _facts = null; return null; } } internal static bool LeaveAlone(string prefab, string owner, IAliveLog log) { if (_facts == null || (object)_leaveAlone == null || !_facts.Has("creatures.leave-alone")) { return false; } try { _leaveAlone.Invoke(null, new object[2] { prefab, owner }); log.Info("ALIVE: Path of Valheiman leaves " + prefab + " alone (no rarity, stars, modifiers or scaling)."); return true; } catch (Exception ex) { log.Warning("ALIVE: Path of Valheiman would not leave " + prefab + " alone: " + (ex.InnerException ?? ex).Message); return false; } } internal static bool Read(Character creature, out int rarity, out IReadOnlyList<string> modifiers, out bool boss, IAliveLog? log) { rarity = 0; modifiers = Array.Empty<string>(); boss = false; if ((Object)(object)creature == (Object)null || !ReadsCreatures) { return false; } try { object[] parameters = new object[1] { creature }; rarity = Math.Max(0, Math.Min(4, Convert.ToInt32(_rarityOf.Invoke(null, parameters), CultureInfo.InvariantCulture))); IReadOnlyList<string> readOnlyList2; if (!(_modifiersOf.Invoke(null, parameters) is IEnumerable source)) { IReadOnlyList<string> readOnlyList = Array.Empty<string>(); readOnlyList2 = readOnlyList; } else { IReadOnlyList<string> readOnlyList = (from object m in source select m?.ToString() ?? string.Empty into m where m.Length > 0 select m).ToList(); readOnlyList2 = readOnlyList; } modifiers = readOnlyList2; object obj = _isPovBoss.Invoke(null, parameters); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } boss = (byte)((uint)num & (flag ? 1u : 0u)) != 0; return true; } catch (Exception ex) { if (!_saidRead) { _saidRead = true; if (log != null) { log.Warning("ALIVE: Path of Valheiman could not be asked about a creature, so kill steps with a PoV filter will not count it: " + (ex.InnerException ?? ex).Message); } } return false; } } private static Assembly? ApiAssembly() { if (!Chainloader.PluginInfos.TryGetValue("treextr.pathofvalheiman", out var value)) { return null; } if ((Object)(object)value.Instance != (Object)null) { return ((object)value.Instance).GetType().Assembly; } return AccessTools.TypeByName("Valheiman.Api.Pov")?.Assembly; } private static object? Field(Type type, string name) { object obj = type.GetField(name, BindingFlags.Static | BindingFlags.Public)?.GetValue(null); if (obj == null) { PropertyInfo? property = type.GetProperty(name, BindingFlags.Static | BindingFlags.Public); if ((object)property == null) { return null; } obj = property.GetValue(null); } return obj; } private static IReadOnlyList<PovModifier> Modifiers(Type? creatures) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected O, but got Unknown if ((object)creatures == null || !(Field(creatures, "Modifiers") is IEnumerable enumerable)) { return Array.Empty<PovModifier>(); } List<PovModifier> list = new List<PovModifier>(); foreach (object item in enumerable) { if (item != null) { Type type = item.GetType(); string text = type.GetProperty("Id")?.GetValue(item)?.ToString() ?? string.Empty; if (text.Length != 0) { PovModifier val = new PovModifier(); val.set_Id(text); val.set_Title(type.GetProperty("Title")?.GetValue(item)?.ToString() ?? text); val.set_About(type.GetProperty("About")?.GetValue(item)?.ToString() ?? string.Empty); list.Add(val); } } } return list; } private static IReadOnlyList<string> Professions(Type? crafting) { try { if ((object)crafting == null || !(Field(crafting, "Professions") is IEnumerable enumerable)) { return Array.Empty<string>(); } List<string> list = new List<string>(); foreach (object item in enumerable) { if (item != null) { string text = (item as string) ?? item.GetType().GetProperty("Id")?.GetValue(item)?.ToString() ?? item.ToString(); if (PovTerms.IsId(text)) { list.Add(text); } } } return list; } catch (Exception) { return Array.Empty<string>(); } } } internal static class EliteLink { internal const string PluginId = "gglasgow.elitecreaturesreborn"; internal static bool Here => Chainloader.PluginInfos.ContainsKey("gglasgow.elitecreaturesreborn"); internal static void Patch(Harmony harmony, IAliveLog log, string where) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown if (!Here) { return; } try { Type type = AccessTools.TypeByName("EliteCreaturesReborn.Patches.CharacterLifecyclePatch"); MethodInfo methodInfo = (((object)type == null) ? null : AccessTools.Method(type, "Attach", new Type[1] { typeof(Character) }, (Type[])null)); if ((object)methodInfo == null) { log.Warning("ALIVE: this Elite Creatures Reborn has no CharacterLifecyclePatch.Attach(Character), so it may make sentries elites on " + where + "."); return; } harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(EliteLink), "Prefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); log.Info("ALIVE: Elite Creatures Reborn leaves sentries, and ALIVE's creatures that say so, alone on " + where + "."); } catch (Exception ex) { log.Warning("ALIVE: Elite Creatures Reborn may make sentries elites on " + where + " (" + ex.Message + ")."); } } private static bool Prefix(Character character) { try { return !LeftAlone(character); } catch (Exception) { return true; } } internal static bool LeftAlone(Character character) { if ((Object)(object)character == (Object)null) { return false; } if (string.Equals(Utils.GetPrefabName(((Component)character).gameObject), "ALIVE_Sentry", StringComparison.Ordinal)) { return true; } ZNetView component = ((Component)character).GetComponent<ZNetView>(); ZDO val = (((Object)(object)component != (Object)null && component.IsValid()) ? component.GetZDO() : null); if (val != null) { return val.GetInt("alive_cr_noelite", 0) == 1; } return false; } } internal static class MapSampling { private static readonly Func<Vector3, float>? ForestFactor = ForestMethod(); internal static Func<double, double, MapSample> Sampler(WorldGenerator generator) { return delegate(double x, double z) { //IL_0016: 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_0034: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected I4, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor((float)x, 0f, (float)z); Biome biome = generator.GetBiome(val); float height = generator.GetHeight((float)x, (float)z); bool flag = ForestFactor != null && Trees(biome, ForestFactor(val)); return new MapSample((int)biome, height, flag); }; } private static bool Trees(Biome biome, float factor) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 if ((int)biome <= 8) { if ((int)biome == 1) { return factor < 1.15f; } if ((int)biome == 8) { return true; } } else { if ((int)biome == 16) { return factor < 0.8f; } if ((int)biome == 512) { return factor < 1.1f; } } return false; } private static Func<Vector3, float>? ForestMethod() { try { MethodInfo methodInfo = AccessTools.Method(typeof(WorldGenerator), "GetForestFactor", new Type[1] { typeof(Vector3) }, (Type[])null); return ((object)methodInfo == null) ? null : AccessTools.MethodDelegate<Func<Vector3, float>>(methodInfo, (object)null, true); } catch (Exception) { return null; } } } } namespace ALIVE.Server.Adapter { internal sealed class AliveAtlas : IWorldAtlas, IWorldObjects { internal const int MapSize = 4096; internal const int SmallMapSize = 1024; internal const double MapRadius = 10500.0; internal const int Cell = 16; private const int PaintVersion = 1; private const int SectorsPerFrame = 300; private const float RescanSeconds = 60f; private const float LocationsKeptSeconds = 30f; private static readonly FieldRef<ZDOMan, List<ZDO>[]>? Sectors = SectorsField(); private static readonly FieldRef<ZDOMan, Dictionary<ZDOID, ZDO>>? ById = ByIdField(); private readonly string _folder; private readonly SessionGateway _gateway; private readonly IAliveLog _log; private readonly Dictionary<int, bool> _pieces = new Dictionary<int, bool>(); private readonly Dictionary<(int, int), int> _counting = new Dictionary<(int, int), int>(); private List<AtlasCell> _cells = new List<AtlasCell>(); private List<AtlasLocation> _locations = new List<AtlasLocation>(); private int _locationCount = -1; private float _locationsReadAt = float.MinValue; private int _sector = -1; private float _nextScan; private bool _looked; private volatile WorldMapStatus _status = new WorldMapStatus(); private volatile string? _file; private volatile string? _small; private volatile bool _stop; private Thread? _painter; private string _seed = string.Empty; private readonly HashSet<ZDOID> _watched = new HashSet<ZDOID>(); private Action<ZDO>? _onDestroyed; private float _watchAt; private static readonly (string Prefix, string Label)[] Known = new(string, string)[22] { ("SunkenCrypt", "Sunken Crypt"), ("Crypt", "Burial Chambers"), ("TrollCave", "Troll Cave"), ("MountainCave", "Frost Cave"), ("Mistlands_DvergrTownEntrance", "Infested Mine"), ("Mistlands_DvergrBossEntrance", "The Queen's lair"), ("Eikthyrnir", "Eikthyr's altar"), ("GDKing", "The Elder's altar"), ("Bonemass", "Bonemass's altar"), ("Dragonqueen", "Moder's altar"), ("GoblinKing", "Yagluth's altar"), ("FaderLocation", "Fader's altar"), ("Vendor_BlackForest", "Haldor"), ("Hildir_camp", "Hildir"), ("BogWitch_Camp", "The Bog Witch"), ("StartTemple", "The sacrificial stones"), ("Runestone", "Runestone"), ("GoblinCamp", "Fuling camp"), ("WoodHouse", "Abandoned house"), ("StoneCircle", "Stone circle"), ("ShipWreck", "Shipwreck"), ("Mistlands_Giant", "Giant's remains") }; private static readonly string[] Dungeons = new string[6] { "Crypt", "SunkenCrypt", "TrollCave", "MountainCave", "Mistlands_DvergrTownEntrance", "Mistlands_DvergrBossEntrance" }; public string WorldName { get { string text; if (!((Object)(object)ZNet.instance == (Object)null)) { text = ZNet.instance.GetWorldName(); if (text == null) { return string.Empty; } } else { text = string.Empty; } return text; } } public string Seed => ZNet.World?.m_seedName ?? string.Empty; public double Radius => 10500.0; public int CellSize => 16; public WorldMapStatus Map => _status; public string? MapFile => _file; public bool Ready { get { if (ZDOMan.instance != null && (Object)(object)ZNetScene.instance != (Object)null && (Object)(object)ZNet.instance != (Object)null) { return Loaded(ZDOMan.instance); } return false; } } internal Func<IReadOnlyCollection<string>>? Watched { get; set; } internal Action<string>? Gone { get; set; } public string? SmallMapFile => _small; internal AliveAtlas(string webFolder, SessionGateway gateway, IAliveLog log) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown _folder = webFolder; _gateway = gateway; _log = log; } private static bool Loaded(ZDOMan man) { if (ById == null) { return true; } Dictionary<ZDOID, ZDO> dictionary = ById.Invoke(man); if (dictionary != null) { return dictionary.Count > 0; } return false; } internal void Update(float now) { try { if (!_looked && WorldGenerator.instance != null && ZNet.World != null) { _looked = true; LookForMap(); } Scan(now); Watch(now); } catch (Exception ex) { _log.Warning("ALIVE world map: " + ex.Message); _sector = -1; _nextScan = now + 60f; } } internal void Stop() { _stop = true; } public void Redraw() { if (_painter == null || !_painter.IsAlive) { Paint(); } } public IReadOnlyList<AtlasLocation> Locations() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: 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_00ce: 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_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00de: 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_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Expected O, but got Unknown ZoneSystem instance = ZoneSystem.instance; if ((Object)(object)instance == (Object)null) { return Array.Empty<AtlasLocation>(); } Dictionary<Vector2s, LocationInstance>.ValueCollection locationList = instance.GetLocationList(); float realtimeSinceStartup = Time.realtimeSinceStartup; if (locationList.Count == _locationCount && realtimeSinceStartup < _locationsReadAt + 30f) { return _locations; } _locationCount = locationList.Count; _locationsReadAt = realtimeSinceStartup; List<AtlasLocation> list = new List<AtlasLocation>(locationList.Count); foreach (LocationInstance item in locationList) { ZoneLocation location = item.m_location; if (location != null) { string text = (string.IsNullOrEmpty(location.m_prefabName) ? (location.m_name ?? string.Empty) : location.m_prefabName); if (text.Length != 0) { AtlasLocation val = new AtlasLocation(); val.set_Prefab(text); val.set_Label(Label(text)); val.set_X((double)item.m_position.x); val.set_Z((double)item.m_position.z); val.set_R((double)Math.Max(8f, location.m_exteriorRadius)); val.set_Dungeon(Dungeon(text)); val.set_Boss(BossAltars.BossOf(text)); val.set_Placed(item.m_placed); list.Add(val); } } } _locations = list; return _locations; } public IReadOnlyList<AtlasCell> Buildings() { return _cells; } public IReadOnlyList<AtlasPlayer> Players() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_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_009e: 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_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown ZNet instance = ZNet.instance; ZDOMan instance2 = ZDOMan.instance; List<AtlasPlayer> list = new List<AtlasPlayer>(); if ((Object)(object)instance == (Object)null || instance2 == null) { return list; } foreach (ZNetPeer peer in instance.GetPeers()) { if (peer != null && peer.IsReady() && !((ZDOID)(ref peer.m_characterID)).IsNone()) { ZDO zDO = instance2.GetZDO(peer.m_characterID); if (zDO != null) { Vector3 position = zDO.GetPosition(); AtlasPlayer val = new AtlasPlayer(); val.set_PlatformId(_gateway.PlatformIdOf(peer.m_uid) ?? string.Empty); val.set_Name(peer.m_playerName ?? string.Empty); val.set_X((double)position.x); val.set_Z((double)position.z); list.Add(val); } } } return list; } public LockableObject? Find(string uid) { //IL_0025: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Expected O, but got Unknown ZDOMan instance = ZDOMan.instance; ZNetScene instance2 = ZNetScene.instance; if (instance == null || (Object)(object)instance2 == (Object)null || !TryId(uid, out var id)) { return null; } ZDO zDO = instance.GetZDO(id); if (zDO == null) { return null; } GameObject prefab = instance2.GetPrefab(zDO.GetPrefab()); Vector3 position = zDO.GetPosition(); string kind = (((Object)(object)prefab == (Object)null) ? string.Empty : (((Object)(object)prefab.GetComponent<Door>() != (Object)null) ? "door" : (((Object)(object)prefab.GetComponent<Container>() != (Object)null) ? "chest" : (((Object)(object)prefab.GetComponent<ItemStand>() != (Object)null) ? "stand" : (((Object)(object)prefab.GetComponent<TeleportWorld>() != (Object)null) ? "portal" : string.Empty))))); bool usable = (Object)(object)prefab != (Object)null && (Object)(object)prefab.GetComponent<Character>() == (Object)null && (Object)(object)prefab.GetComponent<ItemDrop>() == (Object)null && zDO.GetString("alive_npc", string.Empty).Length == 0 && zDO.GetLong("alive_till", 0L) == 0L && zDO.GetLong("alive_altar", 0L) == 0L && zDO.GetString("alive_creature", string.Empty).Length == 0; string spot = (((Object)(object)prefab == (Object)null) ? string.Empty : (((Object)(object)prefab.GetComponentInChildren<Bed>(true) != (Object)null) ? "bed" : (((Object)(object)prefab.GetComponentInChildren<Chair>(true) != (Object)null) ? "seat" : (((Object)(object)prefab.GetComponentInChildren<CraftingStation>(true) != (Object)null || (Object)(object)prefab.GetComponentInChildren<CookingStation>(true) != (Object)null || (Object)(object)prefab.GetComponentInChildren<Smelter>(true) != (Object)null || (Object)(object)prefab.GetComponentInChildren<Fermenter>(true) != (Object)null) ? "work" : string.Empty)))); LockableObject val = new LockableObject(); val.set_Prefab(((Object)(object)prefab == (Object)null) ? string.Empty : ((Object)prefab).name); val.set_Kind(kind); val.set_X((double)position.x); val.set_Y((double)position.y); val.set_Z((double)position.z); val.set_Usable(usable); val.set_Spot(spot); return val; } public IReadOnlyList<string?> FindAt(IReadOnlyList<LockableObject> spots) { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0168: 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) string[] array = new string[spots?.Count ?? 0]; ZDOMan instance = ZDOMan.instance; if (spots == null || spots.Count == 0 || instance == null || ById == null) { return array; } Dictionary<int, List<int>> dictionary = new Dictionary<int, List<int>>(); checked { for (int i = 0; i < spots.Count; i++) { if (!string.IsNullOrEmpty(spots[i].Prefab)) { int stableHashCode = StringExtensionMethods.GetStableHashCode(spots[i].Prefab); if (!dictionary.TryGetValue(stableHashCode, out var value)) { value = (dictionary[stableHashCode] = new List<int>()); } value.Add(i); } } double[] array2 = new double[spots.Count]; for (int j = 0; j < array2.Length; j++) { array2[j] = double.MaxValue; } double num = 0.12249999999999998; Dictionary<ZDOID, ZDO> dictionary2 = ById.Invoke(instance); if (dictionary2 == null) { return array; } foreach (ZDO value3 in dictionary2.Values) { if (value3 == null || !dictionary.TryGetValue(value3.GetPrefab(), out var value2)) { continue; } Vector3 position = value3.GetPosition(); foreach (int item in value2) { double num2 = (double)position.x - spots[item].X; double num3 = (double)position.y - spots[item].Y; double num4 = (double)position.z - spots[item].Z; double num5 = num2 * num2 + num3 * num3 + num4 * num4; if (!(num5 > num) && !(num5 >= array2[item])) { array2[item] = num5; array[item] = Name(value3.m_uid); } } } return array; } } internal static string Name(ZDOID id) { return ((ZDOID)(ref id)).UserID.ToString(CultureInfo.InvariantCulture) + ":" + ((ZDOID)(ref id)).ID.ToString(CultureInfo.InvariantCulture); } internal static bool TryId(string uid, out ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) id = default(ZDOID); if (string.IsNullOrEmpty(uid)) { return false; } int num = uid.IndexOf(':'); checked { if (num <= 0 || num == uid.Length - 1) { return false; } if (!long.TryParse(uid.AsSpan(0, num), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result) || !uint.TryParse(uid.AsSpan(num + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var result2)) { return false; } id = new ZDOID(result, result2); return true; } } private void Watch(float now) { //IL_00d7: Unknown result type (might be due to invalid IL or missing references) if (now < _watchAt) { return; } _watchAt = now + 2f; ZDOMan instance = ZDOMan.instance; if (instance == null) { return; } FieldInfo fieldInfo = AccessTools.Field(typeof(ZDOMan), "m_onZDODestroyed"); if ((object)fieldInfo == null) { return; } if (_onDestroyed == null) { _onDestroyed = Destroyed; } Action<ZDO> action = fieldInfo.GetValue(instance) as Action<ZDO>; if (action == null || Array.IndexOf(action.GetInvocationList(), _onDestroyed) < 0) { fieldInfo.SetValue(instance, (Action<ZDO>)Delegate.Combine(action, _onDestroyed)); } _watched.Clear(); foreach (string item in (IEnumerable<string>)(((object)Watched?.Invoke()) ?? ((object)Array.Empty<string>()))) { if (TryId(item, out var id)) { _watched.Add(id); } } } private void Destroyed(ZDO zdo) { //IL_0017: 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) try { if (zdo != null && _watched.Count != 0 && _watched.Remove(zdo.m_uid)) { Gone?.Invoke(Name(zdo.m_uid)); } } catch (Exception ex) { _log.Warning("ALIVE places: a locked object went, and its lock could not be marked: " + ex.Message); } } private void PaintSmall(string bigFile, Func<double, double, MapSample> sample) { string text = FileFor("-small.png"); try { if (File.Exists(text) && File.GetLastWriteTimeUtc(text) >= File.GetLastWriteTimeUtc(bigFile)) { _small = text; return; } } catch (IOException) { } string text2 = text + ".tmp"; try { using (FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write, FileShare.None, 65536)) { if (!WorldMapPainter.Paint((Stream)fileStream, 1024, 10500.0, sample, (Action<double>)null, (Func<bool>)(() => _stop))) { return; } } if (File.Exists(text)) { File.Delete(text); } File.Move(text2, text); _small = text; _log.Info("ALIVE world map: painted the smaller copy for editors through their games (" + new FileInfo(text).Length / 1024 + " KB)."); } catch (Exception ex2) { _log.Warning("ALIVE world map: the smaller copy could not be painted: " + ex2.Message); try { if (File.Exists(text2)) { File.Delete(text2); } } catch (IOException) { } } } private string FileFor(string extension) { string text = new string(((WorldName.Length > 0) ? WorldName : "world").Select((char c) => (!char.IsLetterOrDigit(c)) ? '_' : c).ToArray()); return Path.Combine(_folder, "world-map-" + text + extension); } private void LookForMap() { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown _seed = Seed; try { string png = FileFor(".png"); string path = FileFor(".json"); if (File.Exists(png) && File.Exists(path)) { JObject val = JObject.Parse(File.ReadAllText(path)); if (string.Equals((string)val["seed"], _seed, StringComparison.Ordinal) && (int?)val["version"] == 1 && (int?)val["size"] == 4096) { _file = png; WorldMapStatus val2 = new WorldMapStatus(); val2.set_Ready(true); val2.set_DrawnMs(((long?)val["drawn_ms"]).GetValueOrDefault()); _status = val2; _log.Info("ALIVE world map: using the map painted " + (string)val["drawn_utc"] + " for seed " + _seed + "."); WorldGenerator instance = WorldGenerator.instance; if (instance != null) { Func<double, double, MapSample> sample = MapSampling.Sampler(instance); Thread thread = new Thread((ThreadStart)delegate { PaintSmall(png, sample); }); thread.IsBackground = true; thread.Priority = ThreadPriority.BelowNormal; thread.Name = "ALIVE small map"; thread.Start(); } return; } } } catch (Exception ex) when (ex is IOException || ex is JsonException || ex is UnauthorizedAccessException || ex is InvalidCastException || ex is FormatException) { _log.Warning("ALIVE world map: the saved map could not be read (" + ex.Message + "); painting it again."); } Paint(); } private void Paint() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_00b8: Expected O, but got Unknown //IL_0021: 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_0038: Expected O, but got Unknown WorldGenerator generator = WorldGenerator.instance; if (generator == null) { WorldMapStatus val = new WorldMapStatus(); val.set_Problem("The world is not loaded yet."); _status = val; return; } _seed = Seed; string png = FileFor(".png"); string meta = FileFor(".json"); string seed = _seed; WorldMapStatus val2 = new WorldMapStatus(); val2.set_Ready(_file != null); val2.set_DrawnMs(_status.DrawnMs); val2.set_Progress((double?)0.0); _status = val2; _painter = new Thread((ThreadStart)delegate { //IL_0286: 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_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Expected O, but got Unknown //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Expected O, but got Unknown Stopwatch stopwatch = Stopwatch.StartNew(); string text = png + ".tmp"; try { Directory.CreateDirectory(_folder); Func<double, double, MapSample> func = MapSampling.Sampler(generator); bool flag; using (FileStream fileStream = new FileStream(text, FileMode.Create, FileAccess.Write, FileShare.None, 65536)) { flag = WorldMapPainter.Paint((Stream)fileStream, 4096, 10500.0, func, (Action<double>)delegate(double p) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_004c: Expected O, but got Unknown AliveAtlas aliveAtlas3 = this; WorldMapStatus val5 = new WorldMapStatus(); val5.set_Ready(_file != null); val5.set_DrawnMs(_status.DrawnMs); val5.set_Progress((double?)p); aliveAtlas3._status = val5; }, (Func<bool>)(() => _stop)); } if (!flag) { File.Delete(text); } else { if (File.Exists(png)) { File.Delete(png); } File.Move(text, png); long num = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); File.WriteAllText(meta, ((JToken)new JObject { ["seed"] = JToken.op_Implicit(seed), ["version"] = JToken.op_Implicit(1), ["size"] = JToken.op_Implicit(4096), ["drawn_ms"] = JToken.op_Implicit(num), ["drawn_utc"] = JToken.op_Implicit(DateTime.UtcNow.ToString("u", CultureInfo.InvariantCulture)) }).ToString((Formatting)1, Array.Empty<JsonConverter>())); _file = png; AliveAtlas aliveAtlas = this; WorldMapStatus val3 = new WorldMapStatus(); val3.set_Ready(true); val3.set_DrawnMs(num); aliveAtlas._status = val3; PaintSmall(png, func); _log.Info("ALIVE world map: painted " + 4096 + "×" + 4096 + " for seed " + seed + " in " + stopwatch.ElapsedMilliseconds / 1000 + " s (" + new FileInfo(png).Length / 1048576 + " MB)."); } } catch (Exception ex) { AliveAtlas aliveAtlas2 = this; WorldMapStatus val4 = new WorldMapStatus(); val4.set_Ready(_file != null); val4.set_DrawnMs(_status.DrawnMs); val4.set_Problem("The map could not be painted: " + ex.Message); aliveAtlas2._status = val4; _log.Warning("ALIVE world map: painting failed: " + ex); try { if (File.Exists(text)) { File.Delete(text); } } catch (IOException) { } } }) { IsBackground = true, Priority = ThreadPriority.BelowNormal, Name = "ALIVE world map" }; _painter.Start(); _log.Info("ALIVE world map: painting the map for seed " + seed + " in the background (" + 4096 + " points across); it takes a few minutes."); } private void Scan(float now) { //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_00dc: 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_0100: Unknown result type (might be due to invalid IL or missing references) ZDOMan instance = ZDOMan.instance; ZNetScene instance2 = ZNetScene.instance; if (instance == null || (Object)(object)instance2 == (Object)null || Sectors == null) { return; } if (_sector < 0) { if (now < _nextScan) { return; } _sector = 0; _counting.Clear(); } List<ZDO>[] array = Sectors.Invoke(instance); if (array == null) { _sector = -1; _nextScan = now + 60f; return; } checked { int num = Math.Min(array.Length, _sector + 300); while (_sector < num) { List<ZDO> list = array[_sector]; if (list != null) { foreach (ZDO item in list) { if (item != null && IsPiece(instance2, item.GetPrefab()) && item.GetLong(ZDOVars.s_creator, 0L) != 0L) { Vector3 position = item.GetPosition(); if (!(position.y > 4000f)) { (int, int) key = ((int)Math.Floor(position.x / 16f), (int)Math.Floor(position.z / 16f)); _counting[key] = (_counting.TryGetValue(key, out var value) ? value : 0) + 1; } } } } _sector++; } if (_sector >= array.Length) { _cells = ((IEnumerable<KeyValuePair<(int, int), int>>)_counting).Select((Func<KeyValuePair<(int, int), int>, AtlasCell>)delegate(KeyValuePair<(int, int), int> c) { //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_001d: 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_0043: Expected O, but got Unknown AtlasCell val = new AtlasCell(); val.set_X((double)(c.Key.Item1 * 16 + 8)); val.set_Z((double)(c.Key.Item2 * 16 + 8)); val.set_Count(c.Value); return val; }).ToList(); _counting.Clear(); _sector = -1; _nextScan = now + 60f; } } } private bool IsPiece(ZNetScene scene, int hash) { if (_pieces.TryGetValue(hash, out var value)) { return value; } GameObject prefab = scene.GetPrefab(hash); value = (Object)(object)prefab != (Object)null && (Object)(object)prefab.GetComponent<Piece>() != (Object)null; _pieces[hash] = value; return value; } private static bool Dungeon(string prefab) { return Dungeons.Any((string d) => prefab.StartsWith(d, StringComparison.Ordinal)); } internal static string Label(string prefab) { string text = BossAltars.LabelOf(prefab); if (text.Length > 0) { return text; } (string, string)[] known = Known; for (int i = 0; i < known.Length; i++) { var (value, result) = known[i]; if (prefab.StartsWith(value, StringComparison.Ordinal)) { return result; } } StringBuilder stringBuilder = new StringBuilder(); string text2 = prefab.TrimEnd('0', '1', '2', '3', '4', '5', '6', '7', '8', '9').Replace('_', ' ').Trim(); checked { for (int j = 0; j < text2.Length; j++) { char c = text2[j]; if (j > 0 && char.IsUpper(c) && char.IsLower(text2[j - 1])) { stringBuilder.Append(' '); } stringBuilder.Append((stringBuilder.Length == 0) ? c : char.ToLowerInvariant(c)); } if (stringBuilder.Length <= 0) { return prefab; } return stringBuilder.ToString(); } } private static FieldRef<ZDOMan, List<ZDO>[]>? SectorsField() { try { return AccessTools.FieldRefAccess<ZDOMan, List<ZDO>[]>("m_objectsBySector"); } catch (Exception) { return null; } } private static FieldRef<ZDOMan, Dictionary<ZDOID, ZDO>>? ByIdField() { try { return AccessTools.FieldRefAccess<ZDOMan, Dictionary<ZDOID, ZDO>>("m_objectsByID"); } catch (Exception) { return null; } } } internal sealed class AliveCreatures : ICreatureWorld, IGamePrefabs { private sealed class PendingDeath { internal string Uid { get; } internal string Prefab { get; } internal Vector3 At { get; } internal float Since { get; } internal float Health { get; } internal bool Hurt { get; set; } internal CreatureTraits? Traits { get; set; } internal PendingDeath(string uid, string prefab, Vector3 at, float since, float health) { //IL_0015: 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) Uid = uid; Prefab = prefab; At = at; Since = since; Health = health; } } internal static readonly Version CreatureClient = new Version(0, 46); private const float TickEverySeconds = 1f; private const float AltarsEverySeconds = 5f; private const float SignSeconds = 2.5f; private readonly ServerHost _host; private readonly SessionGateway _gateway; private readonly IAliveLog _log; private readonly HashSet<string> _removing = new HashSet<string>(StringComparer.Ordinal); private readonly Dictionary<long, ZDOID> _altars = new Dictionary<long, ZDOID>(); private readonly Dictionary<long, ZDOID> _altarTills = new Dictionary<long, ZDOID>(); private readonly List<PendingDeath> _pending = new List<PendingDeath>(); private readonly Dictionary<string, (HashSet<int> Ragdolls, HashSet<int> Drops)> _signs = new Dictionary<string, (HashSet<int>, HashSet<int>)>(StringComparer.Ordinal); private readonly List<ZDO> _near = new List<ZDO>(); private readonly Dictionary<string, CreatureTraits> _traits = new Dictionary<string, CreatureTraits>(StringComparer.Ordinal); private ZDOMan? _hooked; private ZDOMan? _altarWorld; private float _nextTick; private float _nextAltars; private bool _altarsDirty = true; private bool _started; private bool? _cllc; private bool _saidFailed; private IReadOnlyList<string> _cllcOff = Array.Empty<string>(); private float _nextCllcLook; private static readonly (string Method, string Part)[] CllcSwitches = new(string, string)[3] { ("IsInfusionEnabled", "infusions"), ("IsExtraEffectEnabled", "extra effects"), ("IsAffixEnabled", "boss affixes") }; public bool Ready { get { if ((Object)(object)ZNet.instance != (Object)null && ZDOMan.instance != null && (Object)(object)ZNetScene.instance != (Object)null && (Object)(object)ZoneSystem.instance != (Object)null && (Object)(object)EnvMan.instance != (Object)null)
plugins/ALIVE.Server.dll
Decompiled 3 hours 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.ComponentModel; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core; using ALIVE.Core.Abstractions; using ALIVE.Core.Client; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content; using ALIVE.Core.Content.Conditions; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Currencies; using ALIVE.Core.Content.Dialogue; using ALIVE.Core.Content.Economy; using ALIVE.Core.Content.Effects; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Content.Packs; using ALIVE.Core.Content.Pricing; using ALIVE.Core.Content.Quests; using ALIVE.Core.Content.Shops; using ALIVE.Core.Content.Trades; using ALIVE.Core.Content.Validation; using ALIVE.Core.Diagnostics; using ALIVE.Core.Economy; using ALIVE.Core.Life; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using ALIVE.Core.Web; using ALIVE.Server.Admin; using ALIVE.Server.Authority; using ALIVE.Server.Content; using ALIVE.Server.Economy; using ALIVE.Server.Jobs; using ALIVE.Server.Persistence; using ALIVE.Server.Platform; using ALIVE.Server.Quests; using ALIVE.Server.Rewards; using ALIVE.Server.Runtime; using ALIVE.Server.Sessions; using ALIVE.Server.Shops; using ALIVE.Server.Tills; using ALIVE.Server.Util; using ALIVE.Server.Web; using ALIVE.Server.World; using Microsoft.CodeAnalysis; using Microsoft.Data.Sqlite; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SQLitePCL; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Server")] [assembly: InternalsVisibleTo("ALIVE.Server.Tests")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } internal static class IsExternalInit { } } namespace ALIVE.Server { public sealed class ServerHost : IDisposable { private QuestNotifier? _notifier; public static readonly Version PovXpSince = new Version(0, 59); private ContentDrafts? _drafts; private StoryNotes? _notes; public QuestLifecycle Lifecycle { get; } public QuestWatch Watch { get; } public QuestWork Work { get; } public ConditionEvaluator Conditions { get; } public QuestGates Gates { get; } public EffectRunner Effects { get; } public ShopService Shops { get; } public TillPayments Payments { get; } public BankService Bank { get; } public GrantService Grants { get; } public QuestRewardPayer Rewards { get; } public NpcPlacements Placements { get; } public QuestTurnIns TurnIns { get; } public IWorldView? World { get { return Placements.World; } set { Placements.World = value; } } public QuestObjectives Objectives { get; } public CreatureService Creatures { get; private set; } public PlaceService Places { get; private set; } public Reputation Reputation { get; private set; } public NpcLife Life { get; private set; } public NpcTalks Talks { get; private set; } public JobBoards Jobs { get; private set; } public LandCatalog Lands { get; private set; } public JobPool JobPool { get; private set; } public JobTravel Travel { get; private set; } public JobCounts JobCounts { get; private set; } public KillCredit Kills { get; } public PovFacts? Pov { get; set; } public bool EliteHere { get; set; } public PovBuilds PovBuilds { get; } = new PovBuilds(); public SentryKills SentryKills { get; private set; } public Func<long, SentryNow?>? SentryNow { get; set; } public Func<string, (string Type, string Skill)?>? ItemInfo { get; set; } public DialogueRuntime Dialogue { get; } public QuestEngine Quests { get; } public QuestViews QuestViews { get; } public LedgerService Ledger { get; } public AdminRoster Roster { get; } public Authorizer Authorizer { get; } public AlivePaths Paths { get; } public string? ShippedAttestation { get; set; } public ContentDrafts Drafts => _drafts ?? (_drafts = new ContentDrafts(Paths.Drafts)); public StoryNotes Notes => _notes ?? (_notes = new StoryNotes(Paths.StoryMemory)); public IAliveStore Store { get; } public WebPictures Pictures { get; private set; } public AdminPictures PictureUploads { get; private set; } public NpcPortraits Portraits { get; private set; } public ContentAuthoring Authoring { get; private set; } public StoryTools Story { get; private set; } public ContentService Content { get; } public SessionGateway? Gateway { get; private set; } private ServerHost(AlivePaths paths, IAliveStore store, ContentService content, AdminRoster roster, Authorizer authorizer, LedgerService ledger, QuestEngine quests, QuestViews questViews, DialogueRuntime dialogue, KillCredit kills, NpcPlacements placements, GrantService grants, QuestRewardPayer rewards, ShopService shops, TillPayments payments, BankService bank, QuestObjectives objectives, QuestLifecycle lifecycle, QuestGates gates, EffectRunner effects, ConditionEvaluator conditions, QuestWatch watch, QuestWork work) { Work = work; Watch = watch; Conditions = conditions; Lifecycle = lifecycle; Gates = gates; Effects = effects; Objectives = objectives; Shops = shops; Payments = payments; Bank = bank; Grants = grants; Rewards = rewards; Kills = kills; Placements = placements; TurnIns = new QuestTurnIns(quests, store, content, placements); Paths = paths; Store = store; Content = content; Roster = roster; Authorizer = authorizer; Ledger = ledger; Quests = quests; QuestViews = questViews; Dialogue = dialogue; } public bool PovXpTo(string platformId) { PovFacts? pov = Pov; if (pov != null && pov.Has("grant") && Gateway != null && Gateway.HasPlugin(platformId, "treextr.pathofvalheiman")) { return Gateway.ClientAtLeast(platformId, PovXpSince); } return false; } public static ServerHost Start(string root, IAliveLog log, IClock clock, KillOptions? kills = null, JobPayOptions? jobPay = null) { if (log == null) { throw new ArgumentNullException("log"); } AlivePaths alivePaths = new AlivePaths(root); alivePaths.EnsureCreated(); log.Info("ALIVE server " + AliveCoreVersion.Value + " starting in " + alivePaths.Root); SqliteAliveStore store = SqliteAliveStore.Open(alivePaths.Database, new StoreOpenOptions { BackupFolder = alivePaths.Backups, Log = log }); try { log.Info("ALIVE storage: " + store.EngineDescription + ", schema " + store.SchemaVersion + ", " + alivePaths.Database); ContentService content = new ContentService(alivePaths, (IAliveStore)(object)store, log, clock); content.Reload(); AdminRoster roster = new AdminRoster(log, (IAliveStore)(object)store, clock); AuditVerification val = store.VerifyAudit(); if (val.Intact) { log.Info("ALIVE audit: " + val.Detail + "."); } else { log.Failure("ALIVE audit: THE AUDIT LOG HAS BEEN ALTERED - " + val.Detail + ". Investigate before trusting it.", (Exception)null); } LedgerService ledger = new LedgerService(content, (IAliveStore)(object)store, log, clock); ledger.Reconcile(); QuestEngine questEngine = new QuestEngine((IAliveStore)(object)store, log, clock); RewardLocks locks = new RewardLocks(content, (IAliveStore)(object)store); QuestGates questGates = new QuestGates((IAliveStore)(object)store, content, locks, clock); Func<string, string, bool> questAvailable = questGates.Available; ConditionEvaluator conditionEvaluator = (questGates.Conditions = new ConditionEvaluator((IAliveStore)(object)store, ledger, roster) { QuestAvailable = questAvailable, UtcNow = () => clock.UtcNow }); QuestFlow flow = new QuestFlow(content) { Conditions = conditionEvaluator }; questEngine.Flow = flow; conditionEvaluator.QuestEndingOf = delegate(string who, string questId) { //IL_002a: 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_0036: 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_0049: Expected O, but got Unknown QuestDefinition val2 = flow.Definition(questId); if (val2 == null || val2.Endings.Count == 0) { return (string?)null; } SqliteAliveStore sqliteAliveStore = store; QuestInstanceQuery val3 = new QuestInstanceQuery(); val3.set_PlatformId(who); val3.set_QuestId(questId); val3.set_Limit(1); IReadOnlyList<QuestInstanceRecord> readOnlyList = sqliteAliveStore.SearchQuestInstances(val3); if (readOnlyList.Count != 0) { QuestEnding? obj2 = QuestFlow.EndingOf(val2, readOnlyList[0]); if (obj2 == null) { return (string?)null; } return obj2.EndingId; } return (string?)null; }; DialogueRuntime dialogueRuntime = new DialogueRuntime(content, conditionEvaluator, questEngine, (IAliveStore)(object)store, log, clock) { QuestAvailable = questAvailable, QuestLockedHint = questGates.LockedHint }; StoryWords words = new StoryWords(content, (IAliveStore)(object)store); dialogueRuntime.Words = words; conditionEvaluator.VarOf = words.Var; KillCredit killCredit = new KillCredit(questEngine, content, (IAliveStore)(object)store, log, clock, kills); NpcPlacements npcPlacements = new NpcPlacements((IAliveStore)(object)store, content, log, clock); dialogueRuntime.Reach = npcPlacements.InReach; dialogueRuntime.DistanceTo = npcPlacements.DistanceTo; dialogueRuntime.TalkRange = npcPlacements.Range; conditionEvaluator.BiomeOf = npcPlacements.BiomeOf; Func<string, string?> playerName = delegate(string id) { PlayerRecord? obj2 = store.FindPlayer(id); return (obj2 == null) ? null : obj2.CharacterName; }; dialogueRuntime.PlayerName = playerName; dialogueRuntime.CurrencySymbol = () => (from c in ledger.LedgerCurrencies() select c.Symbol).FirstOrDefault((string sym) => !string.IsNullOrEmpty(sym)); GrantService grants = new GrantService((IAliveStore)(object)store, content, log, clock); grants.Recover(); QuestRewardPayer questRewardPayer = new QuestRewardPayer(questEngine, grants, ledger, content, (IAliveStore)(object)store, log); JobPayOptions jobPayOptions = jobPay ?? new JobPayOptions(); questRewardPayer.PayCoinAsItems = jobPayOptions.PayCoinAsItems; questRewardPayer.CoinItem = jobPayOptions.CoinItem ?? string.Empty; dialogueRuntime.MailWaiting = grants.Waiting; dialogueRuntime.CollectMail = grants.Collect; TillPayments payments = new TillPayments(log, clock) { Returns = delegate(string who, IReadOnlyDictionary<string, int> items, string label) { grants.Give(who, 6, "till", Guid.NewGuid().ToString("D"), label, ((IEnumerable<KeyValuePair<string, int>>)items.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> i) => i.Key, StringComparer.Ordinal)).Select((Func<KeyValuePair<string, int>, GrantItem>)delegate(KeyValuePair<string, int> i) { //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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown GrantItem val2 = new GrantItem(); val2.set_Prefab(i.Key); val2.set_Count(i.Value); return val2; }).ToList()); } }; ShopService shops = new ShopService((IAliveStore)(object)store, content, conditionEvaluator, ledger, grants, npcPlacements, payments, log, clock) { Locks = locks }; BankService bank = new BankService(ledger, grants, npcPlacements, payments, (IAliveStore)(object)store, log, clock); dialogueRuntime.ShopOf = shops.ShopOf; EffectRunner effectRunner = new EffectRunner((IAliveStore)(object)store, ledger, grants, content, log, clock) { PlayerName = playerName, Words = words }; QuestLifecycle lifecycle = new QuestLifecycle(questEngine, (IAliveStore)(object)store, flow, questGates, conditionEvaluator, ledger, content, log, clock) { Effects = effectRunner }; effectRunner.Quests = lifecycle; lifecycle.Recover(); dialogueRuntime.Lifecycle = lifecycle; dialogueRuntime.Effects = effectRunner; QuestObjectives objectives = new QuestObjectives(questEngine, (IAliveStore)(object)store, content, npcPlacements, payments, log, clock); dialogueRuntime.Talked = delegate(string who, string npc, string node, bool first, string correlation) { objectives.Talked(who, npc, node, first, correlation); if (first) { lifecycle.MetNpc(who, npc, correlation); } }; dialogueRuntime.Deliveries = objectives.Deliveries; dialogueRuntime.Hand = objectives.Hand; QuestViews questViews = new QuestViews(content) { Lifecycle = lifecycle, Counter = store.Counter }; PlayerSteps steps = new PlayerSteps(); QuestWatch watch = new QuestWatch(questEngine, (IAliveStore)(object)store, content, npcPlacements, lifecycle, log, clock, steps); QuestWork work = new QuestWork(questEngine, (IAliveStore)(object)store, content, npcPlacements, lifecycle, log, clock) { Testing = killCredit.TestKills }; ledger.Posted = delegate(IReadOnlyList<LedgerPosting> legs) { watch.Posted(legs); }; shops.Traded = delegate(ShopTradeRecord trade) { watch.Traded(trade); }; ServerHost host = new ServerHost(alivePaths, (IAliveStore)(object)store, content, roster, new Authorizer(roster, (IAliveStore)(object)store, log, clock), ledger, questEngine, questViews, dialogueRuntime, killCredit, npcPlacements, grants, questRewardPayer, shops, payments, bank, objectives, lifecycle, questGates, effectRunner, conditionEvaluator, watch, work); words.VarStart = (string id) => host.Notes.StartOf(id); host.Pictures = new WebPictures(alivePaths.Pictures, log); host.Portraits = new NpcPortraits(clock); host.PictureUploads = new AdminPictures(host.Pictures, (IAliveStore)(object)store, roster, log, clock) { Portraits = host.Portraits }; host.Authoring = new ContentAuthoring(alivePaths, content, (IAliveStore)(object)store, roster, log, clock) { Published = delegate { shops.ContentChanged(); }, Placements = npcPlacements, Quests = questEngine, Drafts = host.Drafts }; host.Story = new StoryTools(content, (IAliveStore)(object)store, roster, log, clock); CreatureService creatures = new CreatureService((IAliveStore)(object)store, content, killCredit, grants, npcPlacements, payments, conditionEvaluator, log, clock); host.Creatures = creatures; conditionEvaluator.CreatureAlive = creatures.CreatureAlive; effectRunner.SpawnCreature = creatures.Encounter; creatures.OpenLairs = watch.Lairs; host.Authoring.Creatures = creatures; host.Authoring.Published = delegate { shops.ContentChanged(); creatures.ContentChanged(); }; PlaceService places = new PlaceService((IAliveStore)(object)store, conditionEvaluator, npcPlacements, roster, log, clock) { Payments = payments, NameOf = playerName }; places.Words = (string who, string text) => DialogueText.Fill(text, new Dictionary<string, string>(StringComparer.Ordinal) { ["player.name"] = playerName(who) ?? string.Empty }, (string kind, string name) => words.Lookup(kind, name, who)); host.Places = places; conditionEvaluator.InPlace = places.PlayerInside; creatures.SpotByKey = places.DaySpot; creatures.CreatureSpots = () => places.CreatureSpots; creatures.SpotGeneration = () => places.SpotGeneration; places.GameHour = () => shops.GameHour?.Invoke(); places.ShopHours = delegate(string shopId) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) AliveId key = default(AliveId); string text = default(string); if (AliveId.TryParse(shopId, ref key, ref text) && content.Current != null && content.Current.Published.TryGetValue(key, out var value)) { ContentDefinition definition = value.Definition; ShopDefinition val2 = (ShopDefinition)(object)((definition is ShopDefinition) ? definition : null); if (val2 != null && val2.OpenHours != null) { return (val2.OpenHours.From, val2.OpenHours.To); } } return ((double From, double To)?)null; }; npcPlacements.InPlace = places.Inside; npcPlacements.Spots = places.SpotsOf; effectRunner.PlaceMiddle = places.Middle; NpcLife life = new NpcLife(content, npcPlacements, places, (IAliveStore)(object)store, clock) { GameHour = () => shops.GameHour?.Invoke() }; life.Words = (string who, string text) => DialogueText.Fill(text, new Dictionary<string, string>(StringComparer.Ordinal) { ["player.name"] = playerName(who) ?? string.Empty }, (string kind, string name) => words.Lookup(kind, name, who)); host.Life = life; host.SentryKills = new SentryKills(log, clock); npcPlacements.Now = life.WhereNow; NpcTalks talks = new NpcTalks(content, npcPlacements, (IAliveStore)(object)store, life, log, clock) { Words = life.Words, Conversations = host.Dialogue.Talking }; host.Talks = talks; JobBoards jobs = new JobBoards((IAliveStore)(object)store, content, places, npcPlacements, host.Lifecycle, host.Gates, host.Quests, log, () => UnixMs(clock)) { WorldKey = (string key) => host.Conditions.WorldKey?.Invoke(key), Words = places.Words, Grants = host.Grants, Ledger = host.Ledger }; host.Jobs = jobs; LandCatalog landCatalog = new LandCatalog(); host.Lands = landCatalog; JobPool jobPool = new JobPool(content, landCatalog) { ThingName = (string prefab) => jobs.ThingName?.Invoke(prefab) ?? prefab, WorldKey = (string key) => host.Conditions.WorldKey?.Invoke(key) }; host.JobPool = jobPool; jobs.Pool = jobPool; host.Shops.BiomeItems = landCatalog.ItemsOf; JobTravel travel = new JobTravel((IAliveStore)(object)store, host.Quests, npcPlacements, steps, log, () => UnixMs(clock)); host.Travel = travel; jobs.Travel = travel; host.Rewards.Adjust = jobs.Adjust; host.Rewards.PaySaidElsewhere = jobs.SaysOwnPay; host.Rewards.ItemName = (string paidPrefab) => host.QuestViews.ItemName?.Invoke(paidPrefab) ?? paidPrefab; Reputation reputation = new Reputation((IAliveStore)(object)store, log, () => UnixMs(clock)) { KeepsReputation = places.KeepsReputation, NameOf = delegate(string whoseId) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) PlaceRecord placeRecord = places.Place(whoseId); if (placeRecord != null) { return placeRecord.Name; } PackLoadResult current = content.Current; AliveId key = default(AliveId); string text = default(string); LoadedDefinition value; return (current == null || !AliveId.TryParse(whoseId, ref key, ref text) || !current.Published.TryGetValue(key, out value)) ? string.Empty : value.Definition.Envelope.DisplayName; } }; host.Reputation = reputation; host.Rewards.Reputation = reputation; host.Lifecycle.Reputation = reputation; host.Effects.Reputation = reputation; jobs.Reputation = reputation; host.Lifecycle.BoardPlaces = jobs.PlacesOf; host.Dialogue.StandsIn = delegate(string standing) { PlaceRecord placeRecord = places.ReputationPlaceOf(standing); return (placeRecord == null) ? (((string, int)?)null) : new(string, int)?((placeRecord.Name, store.Relationship(standing, placeRecord.Key))); }; host.Rewards.PayOutstanding(); host.Kills.ExtraTargets = jobs.MadeUpTargets; jobs.MadeUpTargetsChanged = host.Kills.Refresh; host.Kills.Refresh(); places.JobsOut = jobs.OpenFrom; places.BoardRemoved = jobs.TakenDown; JobCounts jobCounts = new JobCounts((IAliveStore)(object)store, host.Quests, content, places, log, () => UnixMs(clock)) { Board = jobs.BoardRecord, Boards = jobs.BoardRecords }; host.JobCounts = jobCounts; jobs.Counts = jobCounts; host.Conditions.JobsDoneAtBoard = jobCounts.Count; host.Conditions.JobsDoneInPlace = jobCounts.CountInPlace; host.QuestViews.JobsStep = jobCounts.StepWords; host.QuestViews.PlacedBoardName = (long placedId) => jobs.BoardRecord(placedId)?.Label ?? string.Empty; host.QuestViews.JobNotice = jobs.NoticeOf; host.QuestViews.JobRewards = jobs.Adjust; host.QuestViews.JobStep = jobs.StepOf; host.QuestViews.JobStatus = jobs.CarriedOf; host.QuestViews.JobCoin = jobs.CoinWordsOf; host.Kills.PovOn = delegate { PovFacts? pov = host.Pov; return pov != null && pov.Has("creatures"); }; host.Kills.IsAliveCreature = (string uid) => host.Creatures.IsAlive(uid); host.PovBuilds.ServerHasPov = () => host.Pov != null; host.Conditions.PovBuild = host.PovBuilds.Of; host.Dialogue.PovBuild = host.PovBuilds.Of; host.Rewards.PovXpTo = host.PovXpTo; host.Effects.PovXpTo = host.PovXpTo; host.QuestViews.PovXpTo = host.PovXpTo; host.QuestViews.PovOn = () => host.Pov != null; host.Dialogue.JobHandIns = jobs.HandInsAt; host.Dialogue.JobTalk = jobs.TalkOf; life.Busy = talks.Busy; effectRunner.StartTalk = talks.Start; host.Authoring.WorldLines = delegate(LoadedDefinition loaded) { IEnumerable<string> first = PovLines(loaded, host.Pov).Concat(jobCounts.WorldLines(loaded)); ContentDefinition definition = loaded.Definition; NpcDefinition val2 = (NpcDefinition)(object)((definition is NpcDefinition) ? definition : null); IEnumerable<string> second; if (val2 == null) { NpcTalkDefinition val3 = (NpcTalkDefinition)(object)((definition is NpcTalkDefinition) ? definition : null); if (val3 == null) { QuestDefinition val4 = (QuestDefinition)(object)((definition is QuestDefinition) ? definition : null); if (val4 == null) { CreatureDefinition val5 = (CreatureDefinition)(object)((definition is CreatureDefinition) ? definition : null); second = ((val5 == null) ? Enumerable.Empty<string>() : CllcLines(val5, host.Creatures?.World)); } else { second = LairSpotLines(val4, places).Concat(jobs.ParcelLines(val4)); } } else { second = talks.Warnings(val3); } } else { second = life.Warnings(val2).Concat(ALIVE.Server.World.SentryKills.Warnings(val2, host.ItemInfo)).Concat(jobs.PoolLines(val2)); } return first.Concat(second); }; return host; } catch { store.Dispose(); throw; } } private static IEnumerable<string> PovLines(LoadedDefinition loaded, PovFacts? pov) { if (pov == null && PackLoader.UsesPov(loaded)) { yield return "Warning: this uses Path of Valheiman, which this server does not have. Its PoV parts are kept, and skipped: a kill filter counts any kill of the creature, PoV experience is not paid, and PoV checks are never met."; } } private unsafe static IEnumerable<string> LairSpotLines(QuestDefinition quest, PlaceService places) { for (int i = 0; i < quest.Objectives.Count; i = checked(i + 1)) { Objective val = quest.Objectives[i]; if (!val.Args.TryGetValue("spawn_when_near", out var value)) { continue; } SpawnWhenNear val2 = (SpawnWhenNear)((value is SpawnWhenNear) ? value : null); if (val2 != null && val2.Spot.HasValue) { string text = "Warning /objectives/" + i.ToString(CultureInfo.InvariantCulture) + "/spawn_when_near/at: "; AliveId value2 = val2.Spot.Value; SpotRecord spotRecord = places.DaySpot(((object)(*(AliveId*)(&value2))/*cast due to .constrained prefix*/).ToString()); if (spotRecord == null) { value2 = val2.Spot.Value; yield return text + "“" + ((AliveId)(ref value2)).Name + "” is not a creature spot in this world yet; the creature waits until it is. Make it on the World map (+ Creature spot) or in game with the ALIVE Admin Tool."; } else if (!spotRecord.ForCreatures) { yield return text + "“" + spotRecord.Name + "” is a spot for NPCs' days, not a creature spot; the creature waits there all the same."; } } } } private static IEnumerable<string> CllcLines(CreatureDefinition creature, ICreatureWorld? world) { CreatureCllc c = creature.Cllc; if (c != null && world != null && world.Cllc) { IReadOnlyList<string> off = world.CllcOff; if (c.Infusion != null && !creature.Boss && off.Contains("infusions")) { yield return "Warning /cllc/infusion: infusions are switched off in Creature Level & Loot Control's settings on this server, so it has no infusion."; } if (c.ExtraEffect != null && !creature.Boss && creature.Level > 1 && off.Contains("extra effects")) { yield return "Warning /cllc/extra_effect: extra effects are switched off in Creature Level & Loot Control's settings on this server, so it has no extra effect."; } if (c.BossAffix != null && creature.Boss && off.Contains("boss affixes")) { yield return "Warning /cllc/boss_affix: boss affixes are switched off in Creature Level & Loot Control's settings on this server, so it has no affix."; } } } public SessionGateway CreateGateway(IPeerTransport transport, SecurityOptions options, IAliveLog log, IClock clock, ISecureRandom random) { if (options == null) { throw new ArgumentNullException("options"); } if (log == null) { throw new ArgumentNullException("log"); } log.Info("ALIVE sessions: attestation " + options.Attestation.ToString() + (options.StrictBuilds ? " (strict builds)" : string.Empty) + ", plugin policy " + options.Plugins.Mode.ToString() + ", ALIVE client " + (options.RequireAliveClient ? "required" : "optional") + (options.SameReleaseOnly ? (", clients " + AliveCoreVersion.Value + " only") : string.Empty) + "."); SessionGateway gateway = new SessionGateway(options, new DirectoryAttestationStore(Paths.Attestation, ShippedAttestation), transport, log, clock, random, ManifestHash) { SuperAdminCheck = Roster.IsSuperAdmin, Authorize = (string platformId, string permission, string action, string correlationId) => Authorizer.Check(platformId, permission, action, correlationId).Granted, Holds = (string platformId, string permission) => Permissions.IsKnown(permission) && Roster.IsSuperAdmin(platformId) }; Gateway = gateway; Roster.Changed = delegate { gateway.SuperAdminsChanged(); }; gateway.SessionStarted = delegate(string platformId, string name) { Store.RecordSessionStart(platformId, name, UnixMs(clock)); Lifecycle.SessionStarted(platformId); Watch.SessionStarted(platformId); Places.SessionStarted(platformId); }; gateway.SessionAdded = delegate(string platformId) { Places.SessionStarted(platformId); }; gateway.SessionEnded = delegate(string platformId) { Lifecycle.SessionEnded(platformId); Watch.SessionEnded(platformId); Places.SessionEnded(platformId); Dialogue.CloseFor(platformId, 2); Shops.Close(platformId); Shops.ForgetPayFromBank(platformId); Payments.Cancel(platformId); Kills.SetTestKills(platformId, on: false); PovBuilds.Forget(platformId); Store.RecordSessionEnd(platformId, UnixMs(clock)); }; gateway.Activity = delegate(ActivityEntry entry) { Store.AppendActivity(entry); }; _notifier?.Dispose(); _notifier = new QuestNotifier(Quests, QuestViews, gateway, log); _notifier.Start(); Work.Gained = _notifier.Refresh; Travel.PassedHundred = delegate(long instanceId) { QuestInstanceRecord val = Store.QuestInstance(instanceId); if (val != null) { _notifier?.Refresh(val); } }; PlayerRequests.Register(gateway, Dialogue, Quests, QuestViews, TurnIns); Work.ReportsPickups = (string platformId) => gateway.ClientAtLeast(platformId, PlayerRequests.PickupsSince); PlayerRequests.RegisterPickups(gateway, Work); PlayerRequests.RegisterSentryKills(gateway, SentryKills); KillHits.Register(gateway, Kills); GrantRequests.Register(gateway, Grants); Grants.Push = gateway.PushTo; ShopRequests.Register(gateway, Shops); Dialogue.OpenShop = delegate(string platformId, string npcId, string shopId, string correlationId) { string refusal; ShopState val = Shops.Open(platformId, npcId, shopId, correlationId, out refusal); if (val == null) { return refusal; } gateway.PushTo(platformId, (IWireMessage)(object)val); return (string?)null; }; Shops.Push = gateway.PushTo; Dialogue.ShopShut = Shops.ShutByHours; Dialogue.ShopLine = Shops.PlayerLine; Bank.Push = gateway.PushTo; Objectives.Push = gateway.PushTo; Objectives.Handed = delegate(HandedIn handed) { DialogueStep dialogueStep = Dialogue.AfterHandIn(handed); if (dialogueStep?.Node != null) { gateway.PushTo(handed.PlatformId, PlayerRequests.Answer(dialogueStep, 0u)); } }; Effects.Push = gateway.PushTo; Reputation.Tell = delegate(string platformId, string line) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown SessionGateway sessionGateway = gateway; Notice val = new Notice(); val.set_Severity((byte)0); val.set_MessageKey("alive.say"); val.set_Params((IReadOnlyList<string>)new string[2] { WireText.Clip(line, 512), "top_left" }); sessionGateway.PushTo(platformId, (IWireMessage)(object)val); }; Rewards.Tell = delegate(string platformId, string line) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown SessionGateway sessionGateway = gateway; Notice val = new Notice(); val.set_Severity((byte)0); val.set_MessageKey("alive.say"); val.set_Params((IReadOnlyList<string>)new string[2] { WireText.Clip(line, 512), "top_left" }); sessionGateway.PushTo(platformId, (IWireMessage)(object)val); }; Dialogue.Ended = delegate(string platformId, DialogueEnd end) { gateway.PushTo(platformId, (IWireMessage)(object)end); }; Dialogue.AskItems = delegate(string platformId, string npcId, IReadOnlyDictionary<string, int> items, string label, Func<bool> arrived) { NpcPlacementRecord val = Placements.PlacementInReach(platformId, npcId); if (val == null) { return "You walked away."; } string refusal; PaymentRequest val2 = Payments.Ask(platformId, val.PlacementId, items, label, 0u, (bool ok) => ok && arrived(), out refusal); if (val2 == null) { return refusal; } gateway.PushTo(platformId, (IWireMessage)(object)val2); return string.Empty; }; TillRequests.Register(gateway, Payments, Bank); Dialogue.OpenBank = delegate(string platformId, string npcId) { string refusal; BankState val = Bank.Open(platformId, npcId, out refusal); if (val == null) { return refusal; } gateway.PushTo(platformId, (IWireMessage)(object)val); return (string?)null; }; Shops.PayOutstanding(); gateway.MailCountOf = Grants.Waiting; gateway.ReadyNotice = delegate(string platformId) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown int num = Grants.Waiting(platformId); if (num == 0) { return (Notice?)null; } Notice val = new Notice(); val.set_Severity((byte)0); val.set_MessageKey("alive.mail.waiting"); val.set_Params((IReadOnlyList<string>)new string[2] { num.ToString(CultureInfo.InvariantCulture), Grants.MailboxName() }); return val; }; AdminNpcCommands adminNpcCommands = new AdminNpcCommands(Store, Placements, Roster, clock); adminNpcCommands.UnderstandsBuiltOnly = (string platformId) => gateway.ClientAtLeast(platformId, AdminNpcCommands.BuiltOnlySince); adminNpcCommands.UnderstandsFolders = (string platformId) => gateway.ClientAtLeast(platformId, AdminNpcCommands.FoldersSince); adminNpcCommands.UnderstandsBoards = (string platformId) => gateway.ClientAtLeast(platformId, JobBoards.Since060); adminNpcCommands.Register(gateway); Authoring.Register(gateway); AdminQueries.Register(gateway, Content, Store, Ledger, Quests, Lifecycle, Drafts); AdminQuestCommands adminQuestCommands = new AdminQuestCommands(Store, Quests, Ledger, Roster, options, log, clock); adminQuestCommands.Lifecycle = Lifecycle; adminQuestCommands.Register(gateway); new AdminTestKills(Kills, Store, Roster, log, clock).Register(gateway); AdminDebug adminDebug = new AdminDebug(DebugLog.Server, Store, Roster, log, clock); adminDebug.NameOf = delegate(string platformId) { PlayerRecord obj = Store.FindPlayer(platformId); return ((obj != null) ? obj.CharacterName : null) ?? string.Empty; }; adminDebug.Register(gateway); Story.Register(gateway); PlayerFlags playerFlags = new PlayerFlags(Store, Roster, log, clock); playerFlags.Uses = () => StoryUses.OnServer(Paths.Content, Drafts, log); playerFlags.Register(gateway); Creatures.Push = gateway.PushTo; new AdminCreatureCommands(Store, Creatures, Roster, log, clock).Register(gateway); PictureUploads.Register(gateway); Places.Push = delegate(string platformId, IWireMessage message) { gateway.PushTo(platformId, message); }; Places.Understands = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.Since); Places.UnderstandsObjects = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.ObjectsSince); Places.UnderstandsHover = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.HoverSince); Places.UnderstandsHours = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.HoursSince); new AdminProtectCommands(Places).Register(gateway); Places.UnderstandsBoards = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.BoardsSince); JobRequests.Register(gateway, Jobs); Jobs.Objectives = Objectives; Jobs.Push = gateway.PushTo; JobCounts.Push = gateway.PushTo; Jobs.ReadsHandIns = (string platformId) => gateway.ClientAtLeast(platformId, JobBoards.Since059); Jobs.ReadsParcels = (string platformId) => gateway.ClientAtLeast(platformId, JobBoards.Since060); Dialogue.PostsJobs = (string platformId, string npcId) => Jobs.IsVillagerBoard(npcId) && gateway.ClientAtLeast(platformId, JobBoards.Since059); Dialogue.OpenBoard = delegate(string platformId, string npcId) { string refusal; BoardState val = Jobs.OpenVillager(platformId, npcId, out refusal); if (val == null) { return refusal; } gateway.PushTo(platformId, (IWireMessage)(object)val); return (string?)null; }; PovBuilds.Register(gateway); gateway.MoreFeatures = delegate { PovFacts? pov = Pov; return (uint)(((pov != null && pov.Has("progress")) ? 2 : 0) | 4); }; Life.Push = delegate(string platformId, IWireMessage message) { gateway.PushTo(platformId, message); }; Life.Understands = (string platformId) => gateway.ClientAtLeast(platformId, PlaceService.LifeSince); Life.UnderstandsNamed = (string platformId) => gateway.ClientAtLeast(platformId, NpcLife.TimetableSince); Life.GameVersion = gateway.ClientVersionOf; Talks.Push = delegate(string platformId, IWireMessage message) { gateway.PushTo(platformId, message); }; Talks.UnderstandsHolds = (string platformId) => gateway.ClientAtLeast(platformId, NpcLife.TimetableSince); return gateway; } public void StartDebug() { DebugLog.Server.Snapshot = () => ServerSnapshot.Lines(this); DebugLog.Server.UseFolder(Paths.Debug); } public ByteString ManifestHash() { string contentHash = Content.ContentHash; byte[] array = new byte[32]; if (contentHash.Length != 64) { return ByteString.CopyFrom(array); } checked { for (int i = 0; i < 32; i++) { array[i] = byte.Parse(contentHash.AsSpan(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); } return ByteString.CopyFrom(array); } } public void Dispose() { _notifier?.Dispose(); _notifier = null; Lifecycle.Dispose(); Rewards.Dispose(); Travel?.Dispose(); ((IDisposable)Store).Dispose(); } private static long UnixMs(IClock clock) { return new DateTimeOffset(DateTime.SpecifyKind(clock.UtcNow, DateTimeKind.Utc)).ToUnixTimeMilliseconds(); } } } namespace ALIVE.Server.World { public static class BossAltars { private static readonly (string Prefix, string Boss, string Label)[] Known = new(string, string, string)[11] { ("Eikthyrnir", "Eikthyr", "Eikthyr's altar"), ("GDKing", "The Elder", "The Elder's altar"), ("Bonemass", "Bonemass", "Bonemass's altar"), ("Dragonqueen", "Moder", "Moder's altar"), ("GoblinKing", "Yagluth", "Yagluth's altar"), ("Mistlands_DvergrBossEntrance", "The Queen", "The Queen's lair"), ("FaderLocation", "Fader", "Fader's altar"), ("DN_Bossroom", "Deep North boss room", "Deep North boss room"), ("AltarAsmodeus_TW", "Asmodeus", "Asmodeus's altar"), ("AltarSvalt_TW", "Svalt", "Svalt's altar"), ("AltarVrykolathas_TW", "Vrykolathas", "Vrykolathas's altar") }; public static string BossOf(string? prefab) { (string, string, string)? tuple = Find(prefab); if (!tuple.HasValue) { return string.Empty; } return tuple.Value.Item2; } public static string LabelOf(string? prefab) { (string, string, string)? tuple = Find(prefab); if (!tuple.HasValue) { return string.Empty; } return tuple.Value.Item3; } private static (string Prefix, string Boss, string Label)? Find(string? prefab) { if (string.IsNullOrEmpty(prefab)) { return null; } (string, string, string)[] known = Known; for (int i = 0; i < known.Length; i++) { (string, string, string) value = known[i]; if (prefab.StartsWith(value.Item1, StringComparison.Ordinal)) { return value; } } return null; } } public sealed class CreatureSpawn { public CreatureDefinition? Creature { get; init; } public string Prefab { get; init; } = string.Empty; public string Tag { get; init; } = string.Empty; public string Source { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double Facing { get; init; } public bool CllcPresent { get; init; } } public sealed class CreatureObject { public string Uid { get; init; } = string.Empty; public string FirstUid { get; init; } = string.Empty; public string Tag { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } } public interface ICreatureWorld { bool Ready { get; } bool Cllc { get; } IReadOnlyList<string> CllcOff { get; } IReadOnlyList<CreatureObject> Objects(); string? Spawn(CreatureSpawn spawn, out string refusal); void Remove(string uid); bool TryWhere(string uid, out double x, out double y, out double z); IReadOnlyList<PlayerAt> Players(); bool NearbyClientsReady(double x, double y, double z, double metres); void SetWorldKey(string key); bool? IsDay(); } public sealed class AltarStand { public long PlacementId { get; init; } public string Look { get; init; } = string.Empty; public string Title { get; init; } = string.Empty; public string Prompt { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } } public sealed class CreatureService { public const double NearMetres = 100.0; public const int MaxEncountersPerPlayer = 5; public const long EncounterRepeatMs = 60000L; public const double AltarReach = 7.0; public const double AltarHeard = 40.0; public const long DropWitnessMs = 60000L; public const double RenamedWithin = 40.0; public const double OnSpotWithin = 4.0; private const long QuestCheckEveryMs = 5000L; private const long ForgetEndedAfterMs = 604800000L; private readonly IAliveStore _store; private readonly ContentService _content; private readonly KillCredit _kills; private readonly GrantService _grants; private readonly NpcPlacements _placements; private readonly TillPayments _payments; private readonly ConditionEvaluator _conditions; private readonly IAliveLog _log; private readonly IClock _clock; private readonly Dictionary<string, Dictionary<string, long>> _near = new Dictionary<string, Dictionary<string, long>>(StringComparer.Ordinal); private readonly Dictionary<string, long> _encounterUses = new Dictionary<string, long>(StringComparer.Ordinal); private readonly Dictionary<long, string> _waitingSaid = new Dictionary<long, string>(); private long _nextQuestCheck; private bool _started; private long _spotsSeen = -1L; public const long LairCheckEveryMs = 2000L; public const long LairRetryMs = 15000L; private readonly Dictionary<string, long> _lairNext = new Dictionary<string, long>(StringComparer.Ordinal); private readonly Dictionary<string, string> _lairWaitingSaid = new Dictionary<string, string>(StringComparer.Ordinal); private long _nextLairCheck; public ICreatureWorld? World { get; set; } public Func<IReadOnlyList<SpotRecord>>? CreatureSpots { get; set; } public Func<long>? SpotGeneration { get; set; } public int MaxTotal { get; set; } = 60; public int MaxPerZone { get; set; } = 12; public Random Random { get; set; } = new Random(); public Func<string, IWireMessage, int>? Push { get; set; } public Func<IReadOnlyList<LairStep>>? OpenLairs { get; set; } public Func<string, SpotRecord?>? SpotByKey { get; set; } public event EventHandler? Changed; public CreatureService(IAliveStore store, ContentService content, KillCredit kills, GrantService grants, NpcPlacements placements, TillPayments payments, ConditionEvaluator conditions, IAliveLog log, IClock clock) { _store = store ?? throw new ArgumentNullException("store"); _content = content ?? throw new ArgumentNullException("content"); _kills = kills ?? throw new ArgumentNullException("kills"); _grants = grants ?? throw new ArgumentNullException("grants"); _placements = placements ?? throw new ArgumentNullException("placements"); _payments = payments ?? throw new ArgumentNullException("payments"); _conditions = conditions ?? throw new ArgumentNullException("conditions"); _log = log ?? throw new ArgumentNullException("log"); _clock = clock ?? throw new ArgumentNullException("clock"); } public CreatureDefinition? Creature(string id) { return Published<CreatureDefinition>(id, (AliveIdKind)13); } public SpawnerDefinition? Spawner(string id) { return Published<SpawnerDefinition>(id, (AliveIdKind)14); } public IReadOnlyList<CreatureDefinition> Creatures() { return All<CreatureDefinition>(); } public IReadOnlyList<SpawnerDefinition> Spawners() { return All<SpawnerDefinition>(); } public IReadOnlyList<AltarStand> Altars() { List<AltarStand> list = new List<AltarStand>(); foreach (SpawnerPlacementRecord item in _store.SpawnerPlacements()) { SpawnerDefinition val = Spawner(item.SpawnerId); if (!item.Enabled || val == null || !val.IsAltar || val.Look.Length == 0) { continue; } if (item.SpotKey.Length > 0) { SpotRecord spotRecord = SpotByKey?.Invoke(item.SpotKey); if (spotRecord != null && spotRecord.GroundUnknown) { continue; } } list.Add(new AltarStand { PlacementId = item.PlacementId, Look = val.Look, Title = ((ContentDefinition)val).Envelope.DisplayName, Prompt = val.Prompt, X = item.X, Y = item.Y, Z = item.Z, RotY = item.RotY }); } return list; } public void ContentChanged() { this.Changed?.Invoke(this, EventArgs.Empty); } public int AliveCount() { return _store.AliveCreatures().Count; } public int HandCount(string admin) { return _store.AliveCreatures().Count((AliveCreatureRecord c) => c.SpawnKind == "hand" && string.Equals(c.OwnerPlatformId, admin, StringComparison.Ordinal)); } public int AliveAt(long placementId) { return _store.AliveCreatures().Count((AliveCreatureRecord c) => c.PlacementId == placementId); } public bool CreatureAlive(string platformId, string creatureId, string scope) { foreach (AliveCreatureRecord item in _store.AliveCreatures()) { if (string.Equals(item.CreatureId, creatureId, StringComparison.Ordinal) && (!(scope != "any") || (item.SpawnKind == "encounter" && string.Equals(item.OwnerPlatformId, platformId, StringComparison.Ordinal)))) { return true; } } return false; } public void Start() { ICreatureWorld world = World; if (world == null || !world.Ready) { return; } _started = true; long num = NowMs(); checked { _store.PurgeEndedCreatures(num - 604800000); int leftOver; int num2 = FindRenamed(world, out leftOver); HashSet<long> hashSet = new HashSet<long>(from p in _store.SpawnerPlacements() select p.PlacementId); int num3 = leftOver; int num4 = 0; int num5 = 0; foreach (AliveCreatureRecord item in _store.AliveCreatures()) { if (!world.TryWhere(item.Uid, out var _, out var _, out var _)) { if (_store.EndAliveCreature(item.Uid, "gone", num)) { num4++; } } else if ((item.PlacementId != 0L && !hashSet.Contains(item.PlacementId)) || (item.QuestId.Length > 0 && item.Step.Length == 0 && !QuestRunning(item.OwnerPlatformId, item.QuestId)) || (Creature(item.CreatureId) == null && item.CreatureId.StartsWith("alive:", StringComparison.Ordinal))) { Take(item, "its spawner, quest or creature is gone"); num3++; } else { num5++; } } _log.Info("ALIVE creatures: " + num5 + " in the world" + ((num2 > 0) ? (" (" + num2 + " found under new names)") : string.Empty) + ((num3 > 0) ? (", took away " + num3 + " left over") : string.Empty) + ((num4 > 0) ? (", " + num4 + " no longer there") : string.Empty) + "; at most " + MaxTotal + " (" + MaxPerZone + " in one zone)."); } } private int FindRenamed(ICreatureWorld world, out int leftOver) { leftOver = 0; IReadOnlyList<CreatureObject> readOnlyList = world.Objects(); IReadOnlyList<AliveCreatureRecord> readOnlyList2 = _store.AliveCreatures(); HashSet<string> byUid = new HashSet<string>(readOnlyList.Select((CreatureObject o) => o.Uid), StringComparer.Ordinal); HashSet<string> claimed = new HashSet<string>(from val in readOnlyList2 where byUid.Contains(val.Uid) select val.Uid, StringComparer.Ordinal); int num = 0; checked { foreach (AliveCreatureRecord r in readOnlyList2) { if (!byUid.Contains(r.Uid)) { CreatureObject creatureObject = readOnlyList.FirstOrDefault((CreatureObject o) => !claimed.Contains(o.Uid) && string.Equals(o.FirstUid, r.Uid, StringComparison.Ordinal)) ?? (from o in readOnlyList where !claimed.Contains(o.Uid) && o.FirstUid.Length == 0 && string.Equals(o.Tag, r.CreatureId, StringComparison.Ordinal) && Distance(o.X, o.Y, o.Z, r.X, r.Y, r.Z) <= 40.0 orderby Distance(o.X, o.Y, o.Z, r.X, r.Y, r.Z) select o).FirstOrDefault(); if (creatureObject != null && _store.RenameAliveCreature(r.Uid, creatureObject.Uid)) { claimed.Add(creatureObject.Uid); num++; _log.Info("ALIVE creatures: " + r.CreatureId + " is object " + creatureObject.Uid + " now (it was " + r.Uid + " before the world was loaded)."); } } } foreach (CreatureObject item in readOnlyList) { if (!claimed.Contains(item.Uid)) { world.Remove(item.Uid); leftOver++; _log.Info("ALIVE creatures: took away " + item.Tag + " (" + item.Uid + "): nothing on this server made it, or it was forgotten before 0.53."); } } return num; } } public void Tick() { ICreatureWorld world = World; if (world == null || !world.Ready) { return; } if (!_started) { Start(); } long num = NowMs(); FollowSpots(num); IReadOnlyList<PlayerAt> readOnlyList = world.Players(); IReadOnlyList<AliveCreatureRecord> readOnlyList2 = _store.AliveCreatures(); bool flag = num >= _nextQuestCheck; checked { if (flag) { _nextQuestCheck = num + 5000; } foreach (AliveCreatureRecord item in readOnlyList2) { if (!world.TryWhere(item.Uid, out var x, out var y, out var z)) { continue; } long num2 = item.LastNearMs; foreach (PlayerAt item2 in readOnlyList) { double num3 = Distance(item2.X, item2.Y, item2.Z, x, y, z); if (num3 <= 100.0) { num2 = num; } if (num3 <= _kills.Options.CreditRadius) { Witness(item.Uid, item2.PlatformId, num); } } _store.SeeAliveCreature(item.Uid, x, y, z, num2); CreatureDefinition val = Creature(item.CreatureId); long num4 = unchecked((long)((val != null) ? val.DespawnAfterSeconds : 1800)) * 1000L; if (num - num2 > num4) { Take(item, "nobody was near it for " + unchecked(num4 / 60000).ToString(CultureInfo.InvariantCulture) + " min"); } else if (item.ExpiresMs > 0 && num >= item.ExpiresMs) { Take(item, "its time was up"); } else if (flag && item.QuestId.Length > 0 && item.Step.Length == 0 && !QuestRunning(item.OwnerPlatformId, item.QuestId)) { Take(item, "the quest it was for ended"); } } SpawnPoints(num, readOnlyList); Lairs(num, readOnlyList); } } public void QuestEnded(string platformId, string questId) { foreach (AliveCreatureRecord item in _store.AliveCreatures()) { if (item.Step.Length == 0 && string.Equals(item.QuestId, questId, StringComparison.Ordinal) && string.Equals(item.OwnerPlatformId, platformId, StringComparison.Ordinal)) { Take(item, "the quest it was for ended"); } } } private void SpawnPoints(long now, IReadOnlyList<PlayerAt> players) { ICreatureWorld world = World; bool flag = DebugLog.Server.On((DebugArea)4); checked { foreach (SpawnerPlacementRecord p in _store.SpawnerPlacements()) { SpawnerDefinition spawner = Spawner(p.SpawnerId); string text = "spawn:" + p.PlacementId.ToString(CultureInfo.InvariantCulture); string text2 = "spawn point #" + p.PlacementId.ToString(CultureInfo.InvariantCulture) + " (" + p.SpawnerId + ")"; if (!p.Enabled || spawner == null || spawner.IsAltar) { if (flag && (!p.Enabled || spawner == null)) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": " + ((!p.Enabled) ? "switched off" : "its spawner is not published")); } } else { if (now - p.LastSpawnMs < unchecked((long)spawner.EverySeconds) * 1000L) { continue; } if (!players.Any((PlayerAt pl) => Distance(pl.X, pl.Y, pl.Z, p.X, p.Y, p.Z) <= (double)spawner.PlayerWithin)) { if (flag) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": waits: no player within " + spawner.PlayerWithin.ToString(CultureInfo.InvariantCulture) + " m"); } continue; } if (AliveAt(p.PlacementId) >= spawner.MaxAlive) { if (flag) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": waits: " + spawner.MaxAlive.ToString(CultureInfo.InvariantCulture) + " of its creatures alive, its most"); } continue; } if (spawner.When != "always") { bool? flag2 = world.IsDay(); if (!flag2.HasValue || flag2.Value != (spawner.When == "day")) { if (flag) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": waits: it spawns only by " + spawner.When); } continue; } } if (spawner.Conditions != null && !ConditionsMet(spawner, p, players)) { if (flag) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": waits: its conditions are not met" + (SpawnerReader.AsksAboutPlayers(spawner.Conditions) ? (" for any player within " + spawner.PlayerWithin.ToString(CultureInfo.InvariantCulture) + " m") : string.Empty)); } continue; } if (flag) { DebugLog.Server.Changed((DebugArea)4, text, text2 + ": spawning"); } string uid; string text3 = SpawnHere(spawner, p, "spawner", string.Empty, string.Empty, 0L, out uid); string value; if (text3.Length == 0) { _waitingSaid.Remove(p.PlacementId); } else if (!_waitingSaid.TryGetValue(p.PlacementId, out value) || value != text3) { _waitingSaid[p.PlacementId] = text3; _log.Info("ALIVE creatures: spawn point #" + p.PlacementId + " (" + p.SpawnerId + ") waits: " + text3 + "."); } } } } } private bool ConditionsMet(SpawnerDefinition spawner, SpawnerPlacementRecord p, IReadOnlyList<PlayerAt> players) { string context = "spawner:" + p.PlacementId.ToString(CultureInfo.InvariantCulture); if (!SpawnerReader.AsksAboutPlayers(spawner.Conditions)) { return _conditions.Evaluate(spawner.Conditions, string.Empty, context).Met; } foreach (PlayerAt item in from pl in players where Distance(pl.X, pl.Y, pl.Z, p.X, p.Y, p.Z) <= (double)spawner.PlayerWithin orderby Distance(pl.X, pl.Y, pl.Z, p.X, p.Y, p.Z) select pl) { if (_conditions.Evaluate(spawner.Conditions, item.PlatformId, context).Met) { return true; } } return false; } private string SpawnHere(SpawnerDefinition spawner, SpawnerPlacementRecord p, string kind, string owner, string questId, long expiresMs, out string uid) { uid = string.Empty; SpawnerCreature val = Pick(spawner); if (val == null) { return "it has no creature this server can make"; } double num = Random.NextDouble() * Math.PI * 2.0; double num2 = ((spawner.Spread <= 0.0) ? 0.0 : (Math.Sqrt(Random.NextDouble()) * spawner.Spread)); string result = Make(val, p.X + Math.Cos(num) * num2, p.Y, p.Z + Math.Sin(num) * num2, Random.NextDouble() * 360.0, kind, ((kind == "altar") ? "altar:" : "spawner:") + p.PlacementId.ToString(CultureInfo.InvariantCulture), p.PlacementId, owner, questId, expiresMs, out uid); _store.SetSpawnerPlacementSpawned(p.PlacementId, NowMs()); return result; } private SpawnerCreature? Pick(SpawnerDefinition spawner) { List<SpawnerCreature> list = spawner.Creatures.Where((SpawnerCreature c) => !c.Id.HasValue || Creature(c.Creature) != null).ToList(); int num = list.Sum((SpawnerCreature c) => c.Weight); if (num <= 0) { return null; } int num2 = Random.Next(num); checked { foreach (SpawnerCreature item in list) { if (num2 < item.Weight) { return item; } num2 -= item.Weight; } return list[list.Count - 1]; } } private string Make(SpawnerCreature pick, double x, double y, double z, double facing, string kind, string source, long placementId, string owner, string questId, long expiresMs, out string uid) { uid = string.Empty; CreatureDefinition val = (pick.Id.HasValue ? Creature(pick.Creature) : null); if (pick.Id.HasValue && val == null) { return "there is no published creature " + pick.Creature; } return Make(val, ((val != null) ? val.Base : null) ?? pick.Creature, pick.Creature, x, y, z, facing, kind, source, placementId, owner, questId, expiresMs, out uid); } private string Make(CreatureDefinition? def, string prefab, string tag, double x, double y, double z, double facing, string kind, string source, long placementId, string owner, string questId, long expiresMs, out string uid, string step = "") { //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_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01be: 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_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Expected O, but got Unknown uid = string.Empty; ICreatureWorld world = World; if (world == null || !world.Ready) { return "the world is not ready"; } IReadOnlyList<AliveCreatureRecord> readOnlyList = _store.AliveCreatures(); if (readOnlyList.Count >= MaxTotal) { return "the server already has " + MaxTotal.ToString(CultureInfo.InvariantCulture) + " ALIVE creatures"; } int zx = Zone(x); int zz = Zone(z); if (readOnlyList.Count((AliveCreatureRecord c) => Zone(c.X) == zx && Zone(c.Z) == zz) >= MaxPerZone) { return "this part of the world already has " + MaxPerZone.ToString(CultureInfo.InvariantCulture); } if (!world.NearbyClientsReady(x, y, z, 100.0)) { return "a player near it has no ALIVE 0.46 client"; } if (_placements.World != null && _placements.World.TryGroundHeight(x, z, out var y2) && (y < y2 || y - y2 < 3.0)) { y = y2; } string refusal; string text = world.Spawn(new CreatureSpawn { Creature = def, Prefab = prefab, Tag = tag, Source = source, X = x, Y = y, Z = z, Facing = facing, CllcPresent = world.Cllc }, out refusal); if (text == null) { if (refusal.Length <= 0) { return "the game could not make it"; } return refusal; } uid = text; long num = NowMs(); IAliveStore store = _store; AliveCreatureRecord val = new AliveCreatureRecord(); val.set_Uid(text); val.set_CreatureId(tag); val.set_SpawnKind(kind); val.set_PlacementId(placementId); val.set_QuestId(questId); val.set_OwnerPlatformId(owner); val.set_State("alive"); val.set_SpawnedMs(num); val.set_LastNearMs(num); val.set_ExpiresMs(expiresMs); val.set_X(x); val.set_Y(y); val.set_Z(z); val.set_Step(step); store.AddAliveCreature(val); _log.Info("ALIVE creatures: made " + (((def != null) ? ((ContentDefinition)def).Envelope.DisplayName : null) ?? tag) + " (" + tag + ", " + text + ") at " + Where(x, y, z) + " for " + source + "."); return string.Empty; } public IReadOnlyList<string> HandSpawn(string admin, string creatureId, int count, double x, double y, double z, double facing, out string refusal) { refusal = string.Empty; CreatureDefinition val = Creature(creatureId); if (val == null) { refusal = "there is no published creature '" + creatureId + "'"; return Array.Empty<string>(); } if (!_placements.SpotAllowed(admin, x, y, z, out refusal)) { return Array.Empty<string>(); } List<string> list = new List<string>(); for (int i = 0; i < Math.Max(1, Math.Min(5, count)); i = checked(i + 1)) { double num = Random.NextDouble() * Math.PI * 2.0; double num2 = ((i == 0) ? 0.0 : (1.5 + Random.NextDouble())); string uid; string text = Make(val, val.Base, creatureId, x + Math.Cos(num) * num2, y, z + Math.Sin(num) * num2, facing, "hand", "hand:" + admin, 0L, admin, string.Empty, 0L, out uid); if (text.Length > 0) { refusal = text; break; } list.Add(uid); } return list; } public unsafe int Encounter(Effect effect, EffectContext context) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (effect == null) { throw new ArgumentNullException("effect"); } if (context == null) { throw new ArgumentNullException("context"); } string who = context.PlatformId; object value; string text = ((effect.Args.TryGetValue("creature", out value) && value is AliveId val) ? ((object)(*(AliveId*)(&val))/*cast due to .constrained prefix*/).ToString() : string.Empty); CreatureDefinition val2 = Creature(text); string text2 = ((context.QuestId.Length > 0) ? context.QuestId : context.NpcId); if (val2 == null) { return Refused(who, text, text2, "there is no published creature " + text); } checked { int val3 = (int)Math.Max(1L, Math.Min(5L, Whole(effect, "count", 1L))); string text3 = Word(effect, "where", "near_player"); object value2; double num = ((effect.Args.TryGetValue("distance", out value2) && value2 is double num2) ? num2 : 8.0); string text4 = Word(effect, "stays", "until_killed"); long num3 = NowMs(); string key = who + "\u001f" + text2 + "\u001f" + text; if (_encounterUses.TryGetValue(key, out var value3) && num3 - value3 < 60000) { return Refused(who, text, text2, "it was used less than a minute ago"); } int num4 = _store.AliveCreatures().Count((AliveCreatureRecord a) => a.SpawnKind == "encounter" && a.Step.Length == 0 && string.Equals(a.OwnerPlatformId, who, StringComparison.Ordinal)); if (num4 >= 5) { return Refused(who, text, text2, "they already have " + 5 + " creatures spawned for them"); } if (!Centre(who, text3, effect, context, out double x, out double y, out double z, out string why)) { return Refused(who, text, text2, why); } string questId = ((text4 == "quest_ends") ? context.QuestId : string.Empty); long expiresMs = ((text4 == "seconds") ? (num3 + Whole(effect, "seconds", 300L) * 1000) : 0); _encounterUses[key] = num3; int num5 = 0; for (int num6 = 0; num6 < Math.Min(val3, 5 - num4); num6++) { double num7 = Random.NextDouble() * Math.PI * 2.0; double num8 = ((text3 == "at_spawner") ? (Math.Sqrt(Random.NextDouble()) * num) : (num * (0.75 + Random.NextDouble() * 0.25))); string uid; string text5 = Make(val2, val2.Base, text, x + Math.Cos(num7) * num8, y, z + Math.Sin(num7) * num8, Random.NextDouble() * 360.0, "encounter", "encounter:" + ((text2.Length > 0) ? text2 : "effect"), 0L, who, questId, expiresMs, out uid); if (text5.Length > 0) { Refused(who, text, text2, text5); break; } num5++; } return num5; } } private bool Centre(string who, string where, Effect effect, EffectContext context, out double x, out double y, out double z, out string why) { double facing = (x = (y = (z = 0.0))); why = string.Empty; IWorldView world = _placements.World; if (world == null || !world.TryGetPlayer(who, out var x2, out var y2, out var z2, out facing)) { why = "the server cannot see the player"; return false; } if (!(where == "near_npc")) { if (where == "at_spawner") { SpawnerPlacementRecord val = _store.SpawnerPlacement(Whole(effect, "placement", 0L)); if (val == null) { why = "there is no spawner placement #" + Whole(effect, "placement", 0L).ToString(CultureInfo.InvariantCulture); return false; } x = val.X; y = val.Y; z = val.Z; return true; } x = x2; y = y2; z = z2; return true; } NpcPlacementRecord val2 = ((context.NpcId.Length > 0) ? _placements.PlacementInReach(who, context.NpcId) : null); if (val2 == null) { why = "there is no NPC beside them"; return false; } x = val2.X; y = val2.Y; z = val2.Z; return true; } private int Refused(string who, string creatureId, string from, string why) { _log.Info("ALIVE creatures: did not spawn " + creatureId + " for " + who + ((from.Length > 0) ? (" (" + from + ")") : string.Empty) + ": " + why + "."); return 0; } public int Clear(CreatureClearScope scope, string admin, long placementId) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 int num = 0; foreach (AliveCreatureRecord item in _store.AliveCreatures()) { if (((int)scope == 0) ? (item.SpawnKind == "hand" && string.Equals(item.OwnerPlatformId, admin, StringComparison.Ordinal)) : ((int)scope != 1 || item.PlacementId == placementId)) { Take(item, "an admin removed it"); num = checked(num + 1); } } return num; } private void Take(AliveCreatureRecord c, string why) { long num = NowMs(); if (_store.EndAliveCreature(c.Uid, "removed", num)) { _near.Remove(c.Uid); LairEmptied(c, num); World?.Remove(c.Uid); _log.Info("ALIVE creatures: took away " + c.CreatureId + " (" + c.Uid + "): " + why + "."); } } public string Died(string uid, double x, double y, double z, CreatureTraits? traits = null) { AliveCreatureRecord c = _store.AliveCreature(uid); if (c == null || c.State != "alive") { return "not one of ALIVE's creatures, or already dealt with"; } long num = NowMs(); if (!_store.EndAliveCreature(uid, "dead", num)) { return "already dealt with"; } CreatureDefinition val = Creature(c.CreatureId); _near.TryGetValue(uid, out Dictionary<string, long> value); _near.Remove(uid); IReadOnlyList<PlayerAt> source = World?.Players() ?? Array.Empty<PlayerAt>(); List<string> list = (from p in source where Distance(p.X, p.Y, p.Z, x, y, z) <= _kills.Options.CreditRadius select p.PlatformId).Distinct<string>(StringComparer.Ordinal).ToList(); if (c.SpawnKind == "hand") { list = list.Where((string p) => string.Equals(p, c.OwnerPlatformId, StringComparison.Ordinal) && _kills.TestKills(p)).ToList(); } else if (c.Step.Length > 0) { HashSet<string> hashSet = HoldersOf(c.QuestId, c.Step); list = list.Where(hashSet.Contains).ToList(); LairEmptied(c, num); } else if (c.QuestId.Length > 0) { list = list.Where((string p) => string.Equals(p, c.OwnerPlatformId, StringComparison.Ordinal)).ToList(); } string text = string.Empty; IReadOnlyList<string> readOnlyList = Array.Empty<string>(); checked { if (_kills.Options.RequireHit) { IReadOnlyCollection<string> struck = _kills.HittersOf(uid); int count = list.Count; List<string> near = list; list = list.Where((string p) => struck.Contains(p) || _kills.TestKills(p)).ToList(); if (list.Count < count) { text = ((list.Count == 0) ? "nobody near was seen to hurt it" : ((count - list.Count).ToString(CultureInfo.InvariantCulture) + " near did not hurt it")); } if (_kills.TamesCount && c.SpawnKind != "hand" && c.Step.Length == 0 && c.QuestId.Length == 0) { List<string> hurtIt = list; readOnlyList = (from p in _kills.TameFollowersNear(uid, c.CreatureId, x, y, z, near) where !hurtIt.Contains(p) select p).ToList(); } } _kills.ForgetHits(uid); string text2 = ((val != null) ? ((ContentDefinition)val).Envelope.DisplayName : null) ?? c.CreatureId; string basePrefab = ((val != null) ? val.Base : null) ?? c.CreatureId; int num2 = ((list.Count != 0 || readOnlyList.Count != 0) ? _kills.CreditAlive(uid, c.CreatureId, basePrefab, val != null && val.CountsAsBase, list, x, y, z, traits, readOnlyList) : 0); if (DebugLog.Server.On((DebugArea)4)) { DebugLog.Server.Write((DebugArea)4, text2 + " (" + c.CreatureId + ", " + c.SpawnKind + ((c.Step.Length > 0) ? (", lair of " + c.QuestId + "/" + c.Step) : string.Empty) + ") died at " + x.ToString("0", CultureInfo.InvariantCulture) + ", " + y.ToString("0", CultureInfo.InvariantCulture) + ", " + z.ToString("0", CultureInfo.InvariantCulture) + "; players within " + _kills.Options.CreditRadius.ToString("0", CultureInfo.InvariantCulture) + " m: " + string.Join(", ", from p in source where Distance(p.X, p.Y, p.Z, x, y, z) <= _kills.Options.CreditRadius select p.PlatformId) + "; credited: " + ((list.Count == 0) ? "nobody" : (string.Join(", ", list) + " (" + num2.ToString(CultureInfo.InvariantCulture) + " quest step(s) moved)"))); } List<string> list2 = new List<string>(); list2.Add((list.Count != 0) ? ("credited to " + string.Join(", ", list) + " (" + num2 + " quest step(s))" + ((text.Length > 0) ? ("; " + text) : string.Empty)) : ((text.Length > 0) ? text : ((c.Step.Length > 0) ? "nobody with its quest step was near" : "nobody shares it"))); List<string> list3 = list2; if (readOnlyList.Count > 0 && (list.Count > 0 || num2 > 0)) { list3.Add("a tame hurt it for " + string.Join(", ", readOnlyList) + ": jobs only, no drops" + ((list.Count == 0) ? (" (" + num2 + " job step(s))") : string.Empty)); } string text3 = ((val != null) ? val.DefeatKey : null); if (text3 != null && text3.Length > 0 && (c.SpawnKind != "hand" || list.Count > 0)) { World?.SetWorldKey(text3); list3.Add("world key " + text3 + " set"); } if (val != null && val.Drops != "as_base" && val.DropTable.Count > 0) { int num3 = 0; foreach (string item in list) { if (value != null && value.TryGetValue(item, out var value2) && num - value2 <= 60000) { List<GrantItem> list4 = Roll(val); if (list4.Count != 0) { _grants.Give(item, 8, "creature", Clip(uid + ":" + item, 64), "From " + text2, list4); num3++; } } } list3.Add((num3 == 0) ? "no drops given" : ("drops given to " + num3 + " player(s)")); } _log.Info("ALIVE creatures: " + text2 + " (" + c.CreatureId + ", " + uid + ") died at " + Where(x, y, z) + ": " + string.Join("; ", list3) + "."); return string.Join("; ", list3); } } public void KilledBySentry(string uid, double x, double y, double z) { AliveCreatureRecord val = _store.AliveCreature(uid); long num = NowMs(); if (val != null && !(val.State != "alive") && _store.EndAliveCreature(uid, "dead", num)) { _near.Remove(uid); _kills.ForgetHits(uid); if (val.Step.Length > 0) { LairEmptied(val, num); } CreatureDefinition? obj = Creature(val.CreatureId); string text = ((obj != null) ? ((ContentDefinition)obj).Envelope.DisplayName : null) ?? val.CreatureId; if (DebugLog.Server.On((DebugArea)4)) { DebugLog.Server.Write((DebugArea)4, text + " (" + val.CreatureId + ") was killed by a sentry at " + Where(x, y, z) + "; credited: nobody"); } _log.Info("ALIVE creatures: " + text + " (" + val.CreatureId + ", " + uid + ") was killed by a sentry at " + Where(x, y, z) + ": it counts for nobody, and drops nothing."); } } public void Gone(string uid, string why) { AliveCreatureRecord val = _store.AliveCreature(uid); long num = NowMs(); if (val != null && _store.EndAliveCreature(uid, "gone", num)) { _near.Remove(uid); LairEmptied(val, num); _log.Info("ALIVE creatures: " + val.CreatureId + " (" + uid + ") went without a death sign (" + why + "); nothing was credited."); } } public bool IsAlive(string uid) { AliveCreatureRecord obj = _store.AliveCreature(uid); return ((obj != null) ? obj.State : null) == "alive"; } private List<GrantItem> Roll(CreatureDefinition def) { //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown List<GrantItem> list = new List<GrantItem>(); checked { foreach (CreatureDrop row in def.DropTable) { if (row.Chance < 1.0 && Random.NextDouble() >= row.Chance) { continue; } int num = ((row.Min >= row.Max) ? row.Min : (row.Min + Random.Next(row.Max - row.Min + 1))); if (num > 0) { GrantItem val = ((IEnumerable<GrantItem>)list).FirstOrDefault((Func<GrantItem, bool>)((GrantItem i) => string.Equals(i.Prefab, row.Item, StringComparison.Ordinal))); if (val != null) { list.Remove(val); num += val.Count; } GrantItem val2 = new GrantItem(); val2.set_Prefab(row.Item); val2.set_Count(num); val2.set_Quality(1); list.Add(val2); } } return list.Take(16).ToList(); } } private void Witness(string uid, string platformId, long now) { if (!_near.TryGetValue(uid, out Dictionary<string, long> value)) { value = new Dictionary<string, long>(StringComparer.Ordinal); _near[uid] = value; } value[platformId] = now; } public SpawnerPlacementRecord? Place(string admin, string spawnerId, string label, (double X, double Y, double Z, double Facing)? spot, out string refusal) { refusal = string.Empty; if (Spawner(spawnerId) == null) { refusal = "there is no published spawner '" + spawnerId + "'"; return null; } double x; double y; double z; double facing; if (!spot.HasValue) { if (_placements.World == null || !_placements.World.TryGetPlayer(admin, out x, out y, out z, out facing)) { refusal = "the server cannot see where you are standing yet"; return null; } } else { (x, y, z, facing) = spot.Value; if (!_placements.SpotAllowed(admin, x, y, z, out refusal)) { return null; } } SpotRecord spotRecord = SpotNear(x, z); if (spotRecord != null) { x = spotRecord.X; z = spotRecord.Z; if (!spotRecord.GroundUnknown) { y = spotRecord.Y; } } long num = NowMs(); SpawnerPlacementRecord val = _store.AddSpawnerPlacement(spawnerId, label ?? string.Empty, x, y, z, Turn(facing), admin, num); if (spotRecord != null && _store.SetSpawnerPlacementSpot(val.PlacementId, spotRecord.Key, num)) { val = _store.SpawnerPlacement(val.PlacementId) ?? val; } _log.Info("ALIVE creatures: " + admin + " placed " + spawnerId + " (#" + val.PlacementId + ") at " + Where(x, y, z) + ((spotRecord != null) ? (" on the creature spot " + spotRecord.Key) : string.Empty) + "."); this.Changed?.Invoke(this, EventArgs.Empty); return val; } public SpawnerPlacementRecord? PlaceOnSpot(string by, string spawnerId, string spotKey, string label, out string refusal) { refusal = string.Empty; if (Spawner(spawnerId) == null) { refusal = "there is no published spawner '" + spawnerId + "'; publish it first"; return null; } SpotRecord spotRecord = SpotByKey?.Invoke(spotKey ?? string.Empty); if (spotRecord == null || !spotRecord.ForCreatures) { refusal = "this world has no creature spot " + spotKey; return null; } long num = NowMs(); SpawnerPlacementRecord val = _store.AddSpawnerPlacement(spawnerId, label ?? string.Empty, spotRecord.X, spotRecord.Y, spotRecord.Z, 0.0, by ?? string.Empty, num); _store.SetSpawnerPlacementSpot(val.PlacementId, spotRecord.Key, num); val = _store.SpawnerPlacement(val.PlacementId) ?? val; _log.Info("ALIVE creatures: " + by + " placed " + spawnerId + " (#" + val.PlacementId + ") on the creature spot " + spotRecord.Key + " at " + Where(spotRecord.X, spotRecord.Y, spotRecord.Z) + (spotRecord.GroundUnknown ? " (its height is found once a player is near)" : string.Empty) + "."); this.Changed?.Invoke(this, EventArgs.Empty); return val; } private SpotRecord? SpotNear(double x, double z) { IReadOnlyList<SpotRecord> readOnlyList = CreatureSpots?.Invoke(); if (readOnlyList == null) { return null; } SpotRecord result = null; double num = 16.0; foreach (SpotRecord item in readOnlyList) { double num2 = (item.X - x) * (item.X - x) + (item.Z - z) * (item.Z - z); if (!(num2 > num)) { num = num2; result = item; } } return result; } private void FollowSpots(long now) { long num = SpotGeneration?.Invoke() ?? 0; if (num == _spotsSeen || SpotByKey == null) { return; } _spotsSeen = num; bool flag = false; foreach (SpawnerPlacementRecord item in from p in _store.SpawnerPlacements() where p.SpotKey.Length > 0 select p) { SpotRecord spotRecord = SpotByKey(item.SpotKey); if (spotRecord == null || !spotRecord.ForCreatures) { _store.SetSpawnerPlacementSpot(item.PlacementId, string.Empty, now); _log.Info("ALIVE creatures: " + item.SpawnerId + " (#" + item.PlacementId + ") stays at " + Where(item.X, item.Y, item.Z) + "; the creature spot " + item.SpotKey + " is gone."); flag = true; continue; } double num2 = (spotRecord.GroundUnknown ? item.Y : spotRecord.Y); if (!(Math.Abs(spotRecord.X - item.X) < 0.05) || !(Math.Abs(spotRecord.Z - item.Z) < 0.05) || !(Math.Abs(num2 - item.Y) < 0.05)) { _store.MoveSpawnerPlacement(item.PlacementId, spotRecord.X, num2, spotRecord.Z, item.RotY, now); _log.Info("ALIVE creatures: " + item.SpawnerId + " (#" + item.PlacementId + ") moved with the creature spot " + spotRecord.Key + " to " + Where(spotRecord.X, num2, spotRecord.Z) + "."); flag = true; } } if (flag) { this.Changed?.Invoke(this, EventArgs.Empty); } } public SpawnerPlacementRecord? Move(string admin, long placementId, double x, double y, double z, double facing, out SpawnerPlacementRecord? before, out string refusal) { before = _store.SpawnerPlacement(placementId); if (before == null) { refusal = "no spawner placement " + placementId.ToString(CultureInfo.InvariantCulture) + " in the world"; return null; } if (!_placements.SpotAllowed(admin, x, y, z, out refusal)) { return null; } SpotRecord spotRecord = SpotNear(x, z); if (spotRecord != null) { x = spotRecord.X; z = spotRecord.Z; if (!spotRecord.GroundUnknown) { y = spotRecord.Y; } } long num = NowMs(); _store.MoveSpawnerPlacement(placementId, x, y, z, Turn(facing), num); if (!string.Equals(before.SpotKey, spotRecord?.Key ?? string.Empty, StringComparison.Ordinal)) { _store.SetSpawnerPlacementSpot(placementId, spotRecord?.Key ?? string.Empty, num); } SpawnerPlacementRecord val = _store.SpawnerPlacement(placementId); _log.Info("ALIVE creatures: " + admin + " moved " + val.SpawnerId + " (#" + placementId + ") to " + Where(x, y, z) + ((spotRecord != null) ? (" on the creature spot " + spotRecord.Key) : string.Empty) + "."); this.Changed?.Invoke(this, EventArgs.Empty); return val; } public SpawnerPlacementRecord? Remove(string admin, long placementId) { SpawnerPlacementRecord val = _store.SpawnerPlacement(placementId); if (val == null || !_store.RemoveSpawnerPlacement(placementId)) { return null; } Clear((CreatureClearScope)1, admin, placementId); _log.Info("ALIVE creatures: " + admin + " removed " + val.SpawnerId + " (#" + placementId + ")."); this.Changed?.Invoke(this, EventArgs.Empty); return val; } public int SpawnerDeleted(string spawnerId) { List<long> list = (from p in _store.SpawnerPlacements() where string.Equals(p.SpawnerId, spawnerId, StringComparison.Ordinal) select p.PlacementId).ToList(); foreach (long item in list) { Clear((CreatureClearScope)1, string.Empty, item); } int num = _store.RemoveSpawnerPlacements(spawnerId); if (num > 0) { this.Changed?.Invoke(this, EventArgs.Empty); } return num; } public AltarState? AltarOpen(string platformId, long placementId, uint seq, out string refusal) { SpawnerPlacementRecord placement; SpawnerDefinition val = AltarFor(platformId, placementId, out placement, out refusal); if (val == null || placement == null) { return null; } uint left; string why = WhyNot(val, placement, out left); return State(val, placement, seq, why, left); } public PaymentRequest? AltarOffer(string platformId, long placementId, uint seq, out AltarState? state, out string refusal) { state = null; SpawnerPlacementRecord placement; SpawnerDefinition val = AltarFor(platformId, placementId, out placement, out refusal); if (val == null || placement == null) { return null; } uint left; string text = WhyNot(val, placement, out left); if (text.Length > 0) { state = State(val, placement, seq, text, left); refusal = text; return null; } Dictionary<string, int> items = val.Offering.ToDictionary<SpawnerOffering, string, int>((SpawnerOffering o) => o.Item, (SpawnerOffering o) => o.Count, StringComparer.Ordinal); PaymentRequest val2 = _payments.Ask(platformId, AltarTill(placementId), items, "An offering at " + ((ContentDefinition)val).Envelope.DisplayName, seq, delegate(bool arrived) { //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) if (!arrived) { return false; } SpawnerPlacementRecord val3 = _store.SpawnerPlacement(placementId); SpawnerDefinition val4 = ((val3 == null) ? null : Spawner(val3.SpawnerId)); uint left2; string text2 = ((val3 == null || val4 == null) ? "the altar is gone" : WhyNot(val4, val3, out left2)); string uid; string text3 = ((text2.Length > 0) ? text2 : SpawnHere(val4, val3, "altar", platformId, string.Empty, 0L, out uid)); if (text3.Length > 0) { _log.Info("ALIVE creatures: altar #" + placementId + " took no offering from " + platformId + ": " + text3 + "; it is given back."); Push?.Invoke(platformId, (IWireMessage)(object)Say("Nothing answers. Your offering is given back.")); return false; } _log.Info("ALIVE creatures: " + platformId + " made an offering at altar #" + placementId + " (" + ((object)((ContentDefinition)val4).Id/*cast due to .constrained prefix*/).ToString() + ")."); foreach (PlayerAt item in World?.Players() ?? Array.Empty<PlayerAt>()) { if (Distance(item.X, item.Y, item.Z, val3.X, val3.Y, val3.Z) <= 40.0) { Push?.Invoke(item.PlatformId, (IWireMessage)(object)Say(val4.SummonedMessage)); } } Push?.Invoke(platformId, (IWireMessage)(object)State(val4, val3, 0u, WhyNot(val4, val3, out var left3), left3)); return true; }, out refusal); if (val2 == null) { return null; } state = State(val, placement, seq, "Waiting for your offering.", 0u); return val2; } public static long AltarTill(long placementId) { return checked(-placementId); } private SpawnerDefinition? AltarFor(string platformId, long placementId, out SpawnerPlacementRecord? placement, out string refusal) { refusal = string.Empty; placement = _store.SpawnerPlacement(placementId); SpawnerDefinition val = ((placement == null) ? null : Spawner(placement.SpawnerId)); if (placement == null || val == null || !val.IsAltar || !placement.Enabled) { refusal = "There is no altar there."; placement = null; return null; } IWorldView world = _placements.World; if (world == null || !world.TryGetPlayer(platformId, out var x, out var y, out var z, out var _) || Distance(x, y, z, placement.X, placement.Y, placement.Z) > 7.0) { refusal = "You walked away."; placement = null; return null; } return val; } private string WhyNot(SpawnerDefinition altar, SpawnerPlacementRecord placement, out uint left) { left = 0u; long num = NowMs(); checked { long num2 = placement.LastSpawnMs + unchecked((long)altar.CooldownSeconds) * 1000L; if (placement.LastSpawnMs > 0 && num < num2) { left = (uint)Math.Max(1L, unchecked(checked(num2 - num + 999) / 1000)); return "It is quiet. Come back in " + Duration(left) + "."; } if (altar.OneAtATime && AliveAt(placement.PlacementId) > 0) { return "What it called still lives."; } if (World == null || !World.Ready) { return "Nothing answers yet."; } if (Pick(altar) == null) { return "Nothing answers."; } return string.Empty; } } private AltarState State(SpawnerDefinition altar, SpawnerPlacementRecord placement, uint seq, string why, uint left) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown AltarState val = new AltarState(); val.set_InReplyToSeq(seq); checked { val.set_PlacementId((ulong)placement.PlacementId); val.set_Title(WireText.Clip(((ContentDefinition)altar).Envelope.DisplayName, 64)); val.set_Prompt(WireText.Clip(altar.Prompt, 128)); val.set_Calls(WireText.Clip(Calls(altar), 128)); val.set_Offering((IReadOnlyList<AltarItem>)altar.Offering.Take(4).Select((Func<SpawnerOffering, AltarItem>)delegate(SpawnerOffering o) { //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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown AltarItem val2 = new AltarItem(); val2.set_Item(o.Item); val2.set_Count((ushort)Math.Min(65535, o.Count)); return val2; }).ToList()); val.set_CanOffer(why.Length == 0); val.set_WhyNot(WireText.Clip(why, 256)); val.set_CooldownLeftSeconds(left); return val; } } private string Calls(SpawnerDefinition altar) { List<string> list = altar.Creatures.Select(delegate(SpawnerCreature c) { if (c.Id.HasValue) { CreatureDefinition? obj = Creature(c.Creature); return ((obj != null) ? ((ContentDefinition)obj).Envelope.DisplayName : null) ?? c.Creature; } return c.Creature; }).Distinct<string>(StringComparer.Ordinal).ToList(); if (list.Count != 1) { return "one of " + list.Count.ToString(CultureInfo.InvariantCulture) + " creatures"; } return list[0]; } private static Notice Say(string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown Notice val = new Notice(); val.set_Severity((byte)0); val.set_MessageKey("alive.say"); val.set_Params((IReadOnlyList<string>)new string[2] { WireText.Clip(text, 512), "center" }); return val; } private static string Duration(uint seconds) { if (seconds < 120) { return seconds.ToString(CultureInfo.InvariantCulture) + " seconds"; } return (checked(seconds + 59) / 60).ToString(CultureInfo.InvariantCulture) + " minutes"; } private bool QuestRunning(string platformId, string questId) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (platformId.Length == 0 || questId.Length == 0) { return false; } IAliveStore store = _store; QuestInstanceQuery val = new QuestInstanceQuery(); val.set_PlatformId(platformId); val.set_QuestId(questId); QuestState[] array = new QuestState[3]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); val.set_States((IReadOnlyList<QuestState>)(object)array); val.set_Limit(1); return store.SearchQuestInstances(val).Count > 0; } private T? Published<T>(string id, AliveIdKind kind) where T : class { //IL_0026: 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_003f: Unknown result type (might be due to invalid IL or missing references) PackLoadResult current = _content.Current; AliveId key = default(AliveId); string text = default(string); if (current == null || !AliveId.TryParse(id ?? string.Empty, ref key, ref text) || ((AliveId)(ref key)).Kind != kind) { return null; } if (!current.Published.TryGetValue(key, out var value)) { return null; } return value.Definition as T; } private IReadOnlyList<T> All<T>() where T : ContentDefinition { PackLoadResult current = _content.Current; if (current == null) { return Array.Empty<T>(); } return current.Published.Values.Select((LoadedDefinition l) => l.Definition).OfType<T>().OrderBy<T, string>((T d) => ((ContentDefinition)d).Envelope.DisplayName, StringComparer.OrdinalIgnoreCase) .ToList(); } private static long Whole(Effect effect, string name, long fallback) { if (effect.Args.TryGetValue(name, out var value) && value is long) { return (long)value; } return fallback; } private static string Word(Effect effect, string name, string fallback) { if (!effect.Args.TryGetValue(name, out var value) || !(value is string { Length: >0 } text)) { return fallback; } return text; } private static double Distance(double ax, double ay, double az, double bx, double by, double bz) { double num = ax - bx; double num2 = ay - by; double num3 = az - bz; return Math.Sqrt(num * num + num2 * num2 + num3 * num3); } private static int Zone(double coordinate) { return checked((int)Math.Floor((coordinate + 32.0) / 64.0)); } private static double Turn(double degrees) { double num = degrees % 360.0; if (!(num < 0.0)) { return num; } return num + 360.0; } private static string Where(double x, double y, double z) { return checked(((int)x).ToString(CultureInfo.InvariantCulture) + ", " + ((int)y).ToString(CultureInfo.InvariantCulture) + ", " + ((int)z).ToString(CultureInfo.InvariantCulture)); } private static string Clip(string s, int max) { if (s.Length > max) { return s.Substring(0, max); } return s; } private long NowMs() { return new DateTimeOffset(DateTime.SpecifyKind(_clock.UtcNow, DateTimeKind.Utc)).ToUnixTimeMilliseconds(); } public bool LairPoint(SpawnWhenNear lair, out double x, out double y, out double z, out bool flat) { //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) x = (y = (z = 0.0)); flat = false; if (lair == null) { return false; } if (lair.Spot.HasValue) { SpotRecord spotRecord = SpotByKey?.Invoke(((object)lair.Spot.Value/*cast due to .constrained prefix*/).ToString()); if (spotRecord == null) { return false; } x = spotRecord.X; y = spotRecord.Y; z = spotRecord.Z; flat = spotRecord.GroundUnknown; return true; } if (lair.At.Count < 3) { return false; } x = lair.At[0]; y = lair.At[1]; z = lair.At[2]; return true; } public bool NearLair(SpawnWhenNear lair, double x, double y, double z) { if (!LairPoint(lair, out var x2, out var y2, out var z2, out var flat)) { return false; } double num = x - x2; double num2 = z - z2; if (num * num + num2 * num2 <= lair.Within * lair.Within) { if (!flat) { return Math.Abs(y - y2) <= Math.Max(lair.Within, 10.0); } return true; } return false; } public static string LairKey(string questId, string objectiveId) { return questId + "/" + objectiveId; } public static bool InLair(SpawnWhenNear lair, double x, double y, double z) { if (lair == null || lair.At.Count < 3) { return false; } double num = x - lair.At[0]; double num2 = z - lair.At[2]; if (num * num + num2 * num2 <= lair.Within * lair.Within) { return Math.Abs(y - lair.At[1]) <= Math.Max(lair.Within, 10.0); } return false; } private void Lairs(long now, IReadOnlyList<PlayerAt> players) { if (OpenLairs == null || now < _nextLairCheck) { return; } checked { _nextLairCheck = now + 2000; IReadOnlyList<LairStep> readOnlyList = Holders(); if (readOnlyList == null) { return; } Dictionary<string, List<LairStep>> byKey = readOnlyList.GroupBy<LairStep, string>((LairStep s) => s.Key, StringComparer.Ordinal).ToDictionary<IGrouping<string, LairStep>, string, List<LairStep>>((IGrouping<string, LairStep> g) => g.Key, (IGrouping<string, LairStep> g) => g.ToList(), StringComparer.Ordinal); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (AliveCreatureRecord c in _store.AliveCreatures()) { if (c.Step.Length != 0) { string text = LairKey(c.QuestId, c.Step); if (byKey.ContainsKey(text)) { hashSet.Add(text); } else if (!players.Any((PlayerAt p) => Distance(p.X, p.Y, p.Z, c.X, c.Y, c.Z) <= 100.0)) { Take(c, "nobody has its quest step any more"); } } } bool flag = DebugLog.Server.On((DebugArea)4); foreach (KeyValuePair<string, List<LairStep>> item in byKey) { if (hashSet.Contains(item.Key)) { if (flag) { DebugLog.Server.Changed((DebugArea)4, "lair:" + item.Key, "lair " + item.Key + ": awake (its creature is in the world)"); } continue; } if (_lairNext.TryGetValue(item.Key, out var value) && now < value) { if (flag) { DebugLog.Server.Changed((DebugArea)4, "lair:" + item.Key, "lair " + item.Key + ": waiting before it may wake again"); } continue; } LairStep lairStep = null; PlayerAt hero = default(PlayerAt); double num = double.MaxValue; SpawnWhenNear lair = item.Value[0].Lair; if (!LairPoint(lair, out var x, out var y, out var z, out var _)) { LairWaits(item.Key, now, "this world has no creature spot " + lair.Spot.ToString() + " (make it on the World map, or in game with the ALIVE Admin Tool)"); if (flag) { DebugLog.Server.Changed((DebugArea)4, "lair:" + item.Key, "lair " + item.Key + ": waits for the creature spot " + lair.Spot.ToString() + ", which this world does not have"); } continue; } foreach (LairStep item2 in item.Value) { foreach (PlayerAt player in players) { if (string.Equals(player.PlatformId, item2.PlatformId, StringComparison.Ordinal) && NearLair(item2.Lair, player.X, player.Y, player.Z)) { double num2 = Distance(player.X, player.Y, player.Z, x, y, z); if (!(num2 >= num)) { num = num2; lairStep = item2; hero = player; } } } } if (lairStep != null) { Wake(item.Key, lairStep, hero, item.Value, players, now); } else { if (!flag) { continue; } SpawnWhenNear val = lair; string text2 = string.Empty; double num3 = double.MaxValue; foreach (LairStep item3 in item.Value) { foreach (PlayerAt player2 in players) { if (string.Equals(player2.PlatformId, item3.PlatformId, StringComparison.Ordinal)) { double num4 = Distance(player2.X, player2.Y, player2.Z, x, y, z); if (!(num4 >= num3)) { num3 = num4; text2 = player2.PlatformId; } } } } DebugLog.Server.Changed((DebugArea)4, "lair:" + item.Key, "lair " + item.Key + " (" + val.Creature + " at " + (val.Spot.HasValue ? (val.Spot.ToString() + ", ") : string.Empty) + x.ToString("0", CultureInfo.InvariantCulture) + ", " + y.ToString("0", CultureInfo.InvariantCulture) + ", " + z.ToString("0", CultureInfo.InvariantCulture) + "): asleep; on the step: " + string.Join(", ", item.Value.Select((LairStep s) => s.PlatformId).Distinct<string>(StringComparer.Ordinal)) + "; none within " + val.Within.ToString("0", CultureInfo.InvariantCulture) + " m" + ((text2.Length > 0) ? (" (nearest: " + text2 + ", about " + ((int)Math.Ceiling(num3 / 5.0) * 5).ToString(CultureInfo.InvariantCulture) + " m)") : " (none of them in the world)")); } } foreach (string item4 in (from p in _lairNext where p.Value <= now && !byKey.ContainsKey(p.Key) select p.Key).ToList()) { _lairNext.Remove(item4); _lairWaitingSaid.Remove(item4); } } } private void Wake(string key, LairStep step, PlayerAt hero, List<LairStep> holders, IReadOnlyList<PlayerAt> players, long now) { SpawnWhenNear lair = step.Lair; CreatureDefinition val = null; if (lair.Id.HasValue) { val = Creature(lair.Creature); if (val == null) { LairWaits(key, now, "there is no published creature " + lair.Creature); return; } } if (!LairPoint(lair, out var x, out var y, out var z, out var _)) { LairWaits(key, now, "this world has no creature spot " + lair.Spot.ToString()); return; } int num = 0; string text = string.Empty; checked { for (int i = 0; i < lair.Count; i++) { double num2 = Random.NextDouble() * Math.PI * 2.0; double num3 = ((lair.Spread <= 0.0) ? 0.0 : (Math.Sqrt(Random.NextDouble()) * lair.Spread)); text = Make(val, ((val != null) ? val.Base : null) ?? lair.Creature, lair.Creature, x + Math.Cos(num2) * num3, y, z + Math.Sin(num2) * num3, Random.NextDouble() * 360.0, "encounter", "lair:" + key, 0L, hero.PlatformId, step.QuestId, 0L, out string _, step.ObjectiveId); if (text.Length > 0) { break; } num++; } if (num == 0) { LairWaits(key, now, text); return; } _lairWaitingSaid.Remove(key); _lairNext[key] = now + 15000; _log.Info("ALIVE creatures: the lair of " + key + " woke " + num.ToString(CultureInfo.InvariantCulture) + " " + (((val != null) ? ((ContentDefinition)val).Envelope.DisplayName : null) ?? lair.Creat
plugins/attestation/0.61.0/admin/ALIVE.Client.Admin.dll.attest
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core; using ALIVE.Core.Abstractions; using ALIVE.Core.Assets; using ALIVE.Core.Client; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Diagnostics; using ALIVE.Core.Life; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using ALIVE.Core.Web; using ALIVE.Server.Util; using ALIVE.Server.World; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Client.Admin")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ALIVE.Server.Util { public sealed class PngWriter : IDisposable { private sealed class ChunkStream : Stream { private const int ChunkBytes = 65536; private readonly Stream _output; private readonly byte[] _buffer = new byte[65536]; private int _count; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal ChunkStream(Stream output) { _output = output; } public override void Write(byte[] buffer, int offset, int count) { checked { while (count > 0) { int num = Math.Min(count, 65536 - _count); Array.Copy(buffer, offset, _buffer, _count, num); _count += num; offset += num; count -= num; if (_count == 65536) { Emit(); } } } } public override void WriteByte(byte value) { _buffer[checked(_count++)] = value; if (_count == 65536) { Emit(); } } public override void Flush() { if (_count > 0) { Emit(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } private void Emit() { WriteChunk(_output, "IDAT", _buffer, _count); _count = 0; } } private static readonly byte[] Signature = new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }; private static readonly uint[] CrcTable = MakeCrcTable(); private readonly Stream _output; private readonly int _width; private readonly int _height; private readonly ChunkStream _chunks; private readonly Stream _deflate; private readonly bool _stored; private readonly byte[] _line; private readonly byte[] _previous; private uint _adlerA = 1u; private uint _adlerB; private int _rows; private bool _finished; public bool Stored => _stored; public PngWriter(Stream output, int width, int height, bool compress = true) { if (width < 1 || height < 1 || width > 16384 || height > 16384) { throw new ArgumentOutOfRangeException("width", "A picture is 1 to 16,384 points on a side."); } _output = output ?? throw new ArgumentNullException("output"); _width = width; _height = height; checked { _line = new byte[1 + width * 3]; _previous = new byte[width * 3]; _output.Write(Signature, 0, Signature.Length); byte[] array = new byte[13]; BigEndian(array, 0, (uint)width); BigEndian(array, 4, (uint)height); array[8] = 8; array[9] = 2; array[10] = 0; array[11] = 0; array[12] = 0; WriteChunk(_output, "IHDR", array, array.Length); _chunks = new ChunkStream(_output); _chunks.WriteByte(120); _chunks.WriteByte(1); Stream stream = null; if (compress) { try { stream = new DeflateStream(_chunks, CompressionLevel.Fastest, leaveOpen: true); } catch (Exception ex) when (ex is DllNotFoundException || ex is TypeInitializationException || ex is EntryPointNotFoundException || ex is NotSupportedException || ex is PlatformNotSupportedException) { stream = null; } } _stored = stream == null; _deflate = stream ?? _chunks; } } public void WriteRow(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException("rgb"); } checked { if (rgb.Length < _width * 3) { throw new ArgumentException("A row is three bytes for each point.", "rgb"); } if (_finished || _rows >= _height) { throw new InvalidOperationException("The picture already has all its rows."); } _line[0] = 2; for (int i = 0; i < _width * 3; i++) { _line[i + 1] = unchecked((byte)(rgb[i] - _previous[i])); _previous[i] = rgb[i]; } Adler(_line, _line.Length); if (_stored) { StoredBlock(_line, _rows == _height - 1); } else { _deflate.Write(_line, 0, _line.Length); } _rows++; } } public void Finish() { if (!_finished) { if (_rows != _height) { throw new InvalidOperationException("The picture has " + _rows + " of its " + _height + " rows."); } _finished = true; if (!_stored) { _deflate.Dispose(); } byte[] array = new byte[4]; BigEndian(array, 0, (_adlerB << 16) | _adlerA); _chunks.Write(array, 0, 4); _chunks.Flush(); WriteChunk(_output, "IEND", Array.Empty<byte>(), 0); _output.Flush(); } } public void Dispose() { if (!_stored && !_finished) { _deflate.Dispose(); } } public static uint Crc(byte[] data, int count) { uint num = uint.MaxValue; for (int i = 0; i < count; i = checked(i + 1)) { num = CrcTable[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return num ^ 0xFFFFFFFFu; } private void StoredBlock(byte[] data, bool last) { checked { int num; for (int i = 0; i < data.Length; i += num) { num = Math.Min(65535, data.Length - i); bool flag = last && i + num == data.Length; _chunks.WriteByte(flag ? ((byte)1) : ((byte)0)); _chunks.WriteByte((byte)(num & 0xFF)); _chunks.WriteByte((byte)(num >> 8)); _chunks.WriteByte((byte)(~num & 0xFF)); _chunks.WriteByte((byte)((~num >> 8) & 0xFF)); _chunks.Write(data, i, num); } } } private void Adler(byte[] data, int count) { for (int i = 0; i < count; i = checked(i + 1)) { _adlerA = checked(_adlerA + data[i]) % 65521; _adlerB = checked(_adlerB + _adlerA) % 65521; } } private static void WriteChunk(Stream output, string type, byte[] data, int count) { byte[] array = new byte[8]; checked { BigEndian(array, 0, (uint)count); for (int i = 0; i < 4; i++) { array[4 + i] = (byte)type[i]; } byte[] array2 = new byte[4 + count]; Array.Copy(array, 4, array2, 0, 4); Array.Copy(data, 0, array2, 4, count); byte[] array3 = new byte[4]; BigEndian(array3, 0, Crc(array2, array2.Length)); output.Write(array, 0, 8); output.Write(data, 0, count); output.Write(array3, 0, 4); } } private static void BigEndian(byte[] into, int at, uint value) { into[at] = (byte)(value >> 24); into[checked(at + 1)] = (byte)(value >> 16); into[checked(at + 2)] = (byte)(value >> 8); into[checked(at + 3)] = (byte)value; } private static uint[] MakeCrcTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0xEDB88320u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } } namespace ALIVE.Server.World { public readonly struct MapSample { public int Biome { get; } public float Height { get; } public bool Forest { get; } public MapSample(int biome, float height, bool forest) { Biome = biome; Height = height; Forest = forest; } } public static class WorldMapPainter { public const float SeaLevel = 30f; private static readonly byte[] Outside = new byte[3] { 6, 9, 11 }; public static bool Paint(Stream output, int size, double radius, Func<double, double, MapSample> sample, Action<double>? progress, Func<bool>? stop) { if (output == null) { throw new ArgumentNullException("output"); } if (sample == null) { throw new ArgumentNullException("sample"); } if (size < 2 || size > 8192) { throw new ArgumentOutOfRangeException("size"); } if (radius <= 0.0) { throw new ArgumentOutOfRangeException("radius"); } double num = radius * 2.0 / (double)size; float[] array = new float[size]; float[] array2 = new float[size]; checked { byte[] array3 = new byte[size * 3]; using (PngWriter pngWriter = new PngWriter(output, size, size)) { for (int i = 0; i < size; i++) { if (stop != null && stop()) { return false; } double num2 = radius - ((double)i + 0.5) * num; for (int j = 0; j < size; j++) { double num3 = 0.0 - radius + ((double)j + 0.5) * num; int num4 = j * 3; if (num3 * num3 + num2 * num2 > radius * radius) { array2[j] = -20f; array3[num4] = Outside[0]; array3[num4 + 1] = Outside[1]; array3[num4 + 2] = Outside[2]; continue; } MapSample s = sample(num3, num2); float num5 = (array2[j] = ((float.IsNaN(s.Height) || float.IsInfinity(s.Height)) ? 30f : s.Height)); float num6 = ((j > 0) ? array2[j - 1] : num5); float num7 = ((i > 0) ? array[j] : num5); Colour(s, num5, num5 - num6 + (num5 - num7), out var red, out var green, out var blue); array3[num4] = red; array3[num4 + 1] = green; array3[num4 + 2] = blue; } pngWriter.WriteRow(array3); float[] array4 = array; array = array2; array2 = array4; if ((i & 0x3F) == 0) { progress?.Invoke((double)i / (double)size); } } pngWriter.Finish(); } progress?.Invoke(1.0); return true; } } public static void Colour(MapSample s, float h, float rise, out byte red, out byte green, out byte blue) { float v; float v2; float v3; if (h < 30f) { float t = Math.Min(1f, (30f - h) / 40f); v = Mix(0.34f, 0.07f, t); v2 = Mix(0.58f, 0.17f, t); v3 = Mix(0.7f, 0.29f, t); } else { switch (s.Biome) { case 1: v = 0.57f; v2 = 0.66f; v3 = 0.36f; break; case 2: v = 0.55f; v2 = 0.42f; v3 = 0.33f; break; case 4: v = 0.93f; v2 = 0.94f; v3 = 0.96f; break; case 8: v = 0.36f; v2 = 0.42f; v3 = 0.24f; break; case 16: v = 0.86f; v2 = 0.78f; v3 = 0.47f; break; case 32: v = 0.62f; v2 = 0.2f; v3 = 0.15f; break; case 64: v = 0.86f; v2 = 0.91f; v3 = 0.97f; break; case 512: v = 0.36f; v2 = 0.33f; v3 = 0.38f; break; default: v = 0.6f; v2 = 0.6f; v3 = 0.55f; break; } if (s.Forest && s.Biome != 4 && s.Biome != 64) { v *= 0.82f; v2 *= 0.86f; v3 *= 0.8f; } if (h < 31.2f && s.Biome != 4) { v = Mix(v, 0.8f, 0.5f); v2 = Mix(v2, 0.74f, 0.5f); v3 = Mix(v3, 0.56f, 0.5f); } float num = 1f + Math.Max(-0.38f, Math.Min(0.38f, rise * 0.045f)); v *= num; v2 *= num; v3 *= num; } red = Byte(v); green = Byte(v2); blue = Byte(v3); } private static float Mix(float a, float b, float t) { return a + (b - a) * t; } private static byte Byte(float v) { return checked((byte)Math.Max(0, Math.Min(255, (int)(v * 255f + 0.5f)))); } } } namespace ALIVE.Client { [BepInPlugin("com.imaginaryrealms.alive.client.admin", "ALIVE Admin", "0.61.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("com.imaginaryrealms.alive.client.player")] [BepInIncompatibility("net.winterwolf.alive.client.player")] [BepInIncompatibility("net.winterwolf.alive.client.admin")] public sealed class AliveAdminPlugin : BaseUnityPlugin { private ClientHost? _host; private void Awake() { //IL_0187: Unknown result type (might be due to invalid IL or missing references) SettingsFile.Carry(((BaseUnityPlugin)this).Config, "net.winterwolf.alive.client.admin", "com.imaginaryrealms.alive.client.admin", ((BaseUnityPlugin)this).Logger); if (SettingsFile.BesideOldCopy("ALIVE Admin", ((BaseUnityPlugin)this).Logger)) { return; } AliveInput.Register((BaseUnityPlugin)(object)this, "com.imaginaryrealms.alive.client.admin", admin: true); ConsolePrefs.Bind(((BaseUnityPlugin)this).Config); ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "ShowTracker", true, "Show the quest list on screen while you play."); ConfigEntry<float> trackerX = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterX", 0.9f, "Where the tracker's centre sits, as a fraction of the screen's width from the left. Drag the tracker and this updates itself."); ConfigEntry<float> trackerY = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterY", 0.6f, "Where the tracker's centre sits, as a fraction of the screen's height from the bottom. Drag the tracker and this updates itself."); ConfigEntry<float> val2 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerScale", 1f, "How big the tracker is, between 0.75 and 1.5."); ConfigEntry<bool> val3 = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "Sounds", true, "Play a sound when a quest is accepted, finished or lost."); ConfigEntry<float> val4 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "SoundVolume", 0.5f, "How loud those sounds are, between 0 and 1."); ConfigEntry<bool> fromBank = ((BaseUnityPlugin)this).Config.Bind<bool>("Shops", "PayFromBank", false, "Pay shop prices in a banked currency (Coins and the like) from your bank rather than with what you carry. Also switched from the shop window; a shop can refuse it."); _host = ClientHost.Start((ClientRole)2, "com.imaginaryrealms.alive.client.admin", ((BaseUnityPlugin)this).Info.Location, ((BaseUnityPlugin)this).Logger); if (_host != null) { _host.TrackerEnabled = val.Value; _host.TrackerCenter = new Vector2(trackerX.Value, trackerY.Value); _host.TrackerScale = val2.Value; _host.SoundEnabled = val3.Value; _host.SoundVolume = val4.Value; _host.PayFromBank = fromBank.Value; _host.PayFromBankChanged = delegate(bool on) { fromBank.Value = on; }; _host.TrackerMoved = delegate(Vector2 anchor) { //IL_0006: 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) trackerX.Value = anchor.x; trackerY.Value = anchor.y; }; } } private void OnApplicationQuit() { _host?.Dispose(); _host = null; } } internal sealed class AdminConsole { private const int WindowId = 41247; private readonly AdminClient _admin; private readonly ShopEditorView _shops; private readonly ConsolePopups _popups = new ConsolePopups(41257); private static readonly Vector2 MinSize = new Vector2(640f, 420f); private static readonly float[] Presets = new float[5] { 1f, 1.25f, 1.5f, 1.75f, 2f }; private Rect _screen; private bool _placed; private float _scale = 1f; private int _gripControl; private Vector2 _gripFrom; private Vector2 _sizeFrom; private Texture2D? _background; private GUIStyle? _window; private Vector2 _scroll; private bool _openOnly; private ulong _confirmComplete; private ulong _confirmWipe; private string _giveFlag = string.Empty; private const string FlagBox = "alive_give_flag"; private const string CounterBox = "alive_set_counter"; private (string Control, string Value) _pendingName = (Control: string.Empty, Value: string.Empty); private string _activeNameBox = string.Empty; private string _openNameList = string.Empty; private string _lastTyped = string.Empty; private Vector2 _nameListScroll; private readonly Dictionary<string, NameRows> _nameRows = new Dictionary<string, NameRows>(StringComparer.Ordinal); private string _counterName = string.Empty; private string _counterValue = string.Empty; private uint _logCategories; private LogSearchItem? _detail; private Rect _detailRect; private Vector2 _detailScroll; private Action? _leave; private string _leaveWhat = string.Empty; private bool _leavePublishing; private bool _superAdmin; private string _hammerNote = string.Empty; private string _npcLabel = string.Empty; private string _spawnerLabel = string.Empty; private bool _confirmRemoveCreatures; private string _storyFlag = string.Empty; private bool _confirmClearAll; private string _storySwitch = string.Empty; private string _picturesAsked = string.Empty; private float _openedAt = -1f; private bool _drawnSinceOpened = true; private static GUIStyle? _tipStyle; private float _keptUpAt; private string _flagFind = string.Empty; private static readonly int[] LogSizes = new int[3] { 25, 50, 100 }; private DebugArea _serverAreas = (DebugArea)127; private DebugArea _gameAreas = (DebugArea)127; private bool _serverAreasRead; private string _serverNote = string.Empty; private string _gameNote = string.Empty; private string _gameSaid = string.Empty; internal bool Visible { get; private set; } internal Action<string, string>? PlaceWithTool { get; set; } internal Action? OpenEditor { get; set; } internal Action? StopEditor { get; set; } internal Func<string>? EditorLine { get; set; } internal Action<ulong, string>? MoveWithTool { get; set; } internal Func<string>? GiveHammer { get; set; } internal Action<string>? SpawnWithTool { get; set; } internal Action<string, string>? PlaceSpawnerWithTool { get; set; } internal Action<ulong, string>? MoveSpawnerWithTool { get; set; } internal AdminConsole(AdminClient admin) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) _admin = admin; _shops = new ShopEditorView(admin) { Popups = _popups }; _admin.Editor.AfterDelete = delegate { _admin.RefreshNpcs(); }; _shops.GoTo = delegate(EditorPage page) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Go((AdminTab)(page switch { EditorPage.Stories => 5, EditorPage.Npcs => 7, _ => 4, })); }; _shops.GuardWith = Guard; _admin.PicturesWanted = AskedForPictures; } private void AskedForPictures(IReadOnlyList<byte> kinds) { PictureRun pictures = _admin.Pictures; bool all; if (!pictures.Busy) { all = kinds.Count == 0; pictures.Creatures = Has(1) || Has(2); pictures.Items = Has(3); pictures.Pieces = Has(4); pictures.Objects = Has(5); List<string> list = new List<string>(); if (pictures.Creatures) { list.Add("creatures"); } if (pictures.Items) { list.Add("items"); } if (pictures.Pieces) { list.Add("building pieces"); } if (pictures.Objects) { list.Add("objects"); } _picturesAsked = "The browser editor asks for pictures of " + ((list.Count == 0) ? "everything" : string.Join(", ", list)) + ". It takes a few minutes; you can keep playing."; Visible = true; Go((AdminTab)8); } bool Has(byte k) { if (!all) { return kinds.Contains(k); } return true; } } internal void Toggle() { if (Visible) { Hide(); return; } Visible = true; _openedAt = Time.unscaledTime; _drawnSinceOpened = false; if (_admin.Players.Count == 0) { _admin.RefreshPlayers(); } } internal string Where() { //IL_00a3: 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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) string text = Screen.width.ToString(CultureInfo.InvariantCulture) + "×" + Screen.height.ToString(CultureInfo.InvariantCulture); if (!_placed) { Rect? val = ConsolePrefs.Window(); if (val.HasValue) { Rect valueOrDefault = val.GetValueOrDefault(); return "its window as it was left, " + Size(valueOrDefault) + ", on a " + text + " screen"; } return "its window in the middle of a " + text + " screen"; } return "its window " + Size(_screen) + " on a " + text + " screen"; } private static string Size(Rect r) { return checked(((int)((Rect)(ref r)).width).ToString(CultureInfo.InvariantCulture) + "×" + ((int)((Rect)(ref r)).height).ToString(CultureInfo.InvariantCulture) + " at " + ((int)((Rect)(ref r)).x).ToString(CultureInfo.InvariantCulture) + "," + ((int)((Rect)(ref r)).y).ToString(CultureInfo.InvariantCulture)); } internal bool ClosePopup() { if (Visible) { if (!_shops.CloseTreePopup()) { return _popups.CloseTop(); } return true; } return false; } internal void Hide() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (Visible) { if (_placed) { ConsolePrefs.SaveWindow(_screen); } Visible = false; GUIUtility.keyboardControl = 0; } } internal void OnSessionReady(bool superAdmin) { _superAdmin = superAdmin; if (Visible) { _admin.RefreshPlayers(); } if (superAdmin) { _admin.CountWaiting(); } } internal void OnSuperAdminChanged(bool superAdmin) { if (_superAdmin != superAdmin) { _superAdmin = superAdmin; if (superAdmin) { _admin.CountWaiting(); } } } internal void Draw() { //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_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0191: 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_01bf: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Invalid comparison between Unknown and I4 //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Expected O, but got Unknown //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Expected O, but got Unknown //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) if (!Visible) { return; } Place(); if (!_drawnSinceOpened) { _drawnSinceOpened = true; float num = Time.unscaledTime - _openedAt; if (num >= 0.5f) { IAliveLog? log = AliveProps.Log; if (log != null) { log.Info("ALIVE: the admin console was drawn " + num.ToString("0.0", CultureInfo.InvariantCulture) + " s after its key opened it; " + Where() + "."); } } } KeepUp(); float num2 = (ConsolePrefs.GrowWithWindow ? Mathf.Clamp(Mathf.Min(((Rect)(ref _screen)).width / ConsolePrefs.BaseSize.x, ((Rect)(ref _screen)).height / ConsolePrefs.BaseSize.y), 0.6f, 3f) : 1f); _scale = Mathf.Clamp(ConsolePrefs.TextScale * num2, 0.5f, 4f); GUISkin val = RuneSkin.Prepare(); GUISkin skin = GUI.skin; Matrix4x4 matrix = GUI.matrix; if ((Object)(object)val != (Object)null) { GUI.skin = val; } GUI.matrix = Matrix4x4.Scale(new Vector3(_scale, _scale, 1f)); GUI.depth = 0; Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref _screen)).x / _scale, ((Rect)(ref _screen)).y / _scale, ((Rect)(ref _screen)).width / _scale, ((Rect)(ref _screen)).height / _scale); Rect val3 = GUI.Window(41247, val2, new WindowFunction(DrawWindow), "ALIVE · ADMIN", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); _popups.Windows(val2); if (_gripControl == 0 || GUIUtility.hotControl != _gripControl) { ((Rect)(ref _screen)).x = ((Rect)(ref val3)).x * _scale; ((Rect)(ref _screen)).y = ((Rect)(ref val3)).y * _scale; } if (_detail != null) { if (((Rect)(ref _detailRect)).width <= 0f) { _detailRect = new Rect(((Rect)(ref val2)).x + ((Rect)(ref val2)).width - 560f, ((Rect)(ref val2)).y + 60f, 540f, 520f); } _detailRect = GUI.Window(41249, _detailRect, new WindowFunction(DrawDetail), "EVENT", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } FollowPublish(); if (_leave != null) { Rect val4 = default(Rect); ((Rect)(ref val4))..ctor(((Rect)(ref val2)).x + (((Rect)(ref val2)).width - 560f) / 2f, ((Rect)(ref val2)).y + 140f, 560f, 230f); GUI.ModalWindow(41248, val4, new WindowFunction(DrawLeave), "UNPUBLISHED CHANGES", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } GUI.matrix = matrix; GUI.skin = skin; if ((int)_admin.Tab == 5) { _shops.DrawTreeWindow(); } } private void Place() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!_placed) { _placed = true; Rect? val = ConsolePrefs.Window(); _screen = (Rect)(((??)val) ?? new Rect(0f, 0f, Mathf.Min(ConsolePrefs.BaseSize.x, (float)Screen.width - 40f), Mathf.Min(ConsolePrefs.BaseSize.y, (float)Screen.height - 40f))); if (!val.HasValue) { ((Rect)(ref _screen)).center = new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f); } } ((Rect)(ref _screen)).width = Mathf.Clamp(((Rect)(ref _screen)).width, Mathf.Min(MinSize.x, (float)Screen.width), (float)Screen.width); ((Rect)(ref _screen)).height = Mathf.Clamp(((Rect)(ref _screen)).height, Mathf.Min(MinSize.y, (float)Screen.height), (float)Screen.height); ((Rect)(ref _screen)).x = Mathf.Clamp(((Rect)(ref _screen)).x, 0f, Mathf.Max(0f, (float)Screen.width - ((Rect)(ref _screen)).width)); ((Rect)(ref _screen)).y = Mathf.Clamp(((Rect)(ref _screen)).y, 0f, Mathf.Max(0f, (float)Screen.height - ((Rect)(ref _screen)).height)); } private void ResetWindow() { ConsolePrefs.ForgetWindow(); _placed = false; Place(); } private GUIStyle Style() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_008d: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) if (_window != null && (Object)(object)_background != (Object)null) { return _window; } _background = new Texture2D(1, 1, (TextureFormat)4, false) { hideFlags = (HideFlags)61 }; _background.SetPixel(0, 0, new Color(0.07f, 0.07f, 0.08f, 0.97f)); _background.Apply(); _window = new GUIStyle(GUI.skin.window) { padding = new RectOffset(12, 12, 24, 16) }; _window.normal.background = _background; _window.onNormal.background = _background; _window.normal.textColor = Color.white; _window.onNormal.textColor = Color.white; return _window; } private static void Tip(float width, float height) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_007d: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_0054: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) string tooltip = GUI.tooltip; if (!string.IsNullOrEmpty(tooltip) && (int)Event.current.type == 7) { if (_tipStyle == null) { _tipStyle = new GUIStyle(GUI.skin.box) { wordWrap = true, alignment = (TextAnchor)0, padding = new RectOffset(8, 8, 6, 6) }; } float num = Mathf.Min(380f, width - 12f); float num2 = _tipStyle.CalcHeight(new GUIContent(tooltip), num); Vector2 mousePosition = Event.current.mousePosition; float num3 = Mathf.Clamp(mousePosition.x + 14f, 6f, Mathf.Max(6f, width - num - 6f)); float num4 = ((mousePosition.y + 22f + num2 > height - 6f) ? Mathf.Max(6f, mousePosition.y - num2 - 10f) : (mousePosition.y + 22f)); GUI.Box(new Rect(num3, num4, num, num2), tooltip, _tipStyle); } } private void DrawWindow(int id) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } float num = ((Rect)(ref _screen)).width / _scale; float num2 = ((Rect)(ref _screen)).height / _scale; try { _popups.Begin(num, num2); Rect val = default(Rect); ((Rect)(ref val))..ctor(num - 20f, num2 - 20f, 18f, 18f); Grip(val); if (GUI.Button(new Rect(num - 42f, 7f, 30f, 22f), "✕")) { Hide(); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); Rail(); GUILayout.Space(14f); GUILayout.BeginVertical(Array.Empty<GUILayoutOption>()); Page(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); Texture2D grip = RuneSkin.Grip; if ((Object)(object)grip != (Object)null && (Object)(object)RuneSkin.Current != (Object)null) { GUI.DrawTexture(val, (Texture)(object)grip); } else { GUI.Label(val, "◢"); } Tip(num, num2); _popups.End(); } finally { GUI.skin = skin; } GUI.DragWindow(new Rect(0f, 0f, 10000f, 32f)); } private void Grip(Rect rect) { //IL_001b: 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_0052: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected I4, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0160: 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_0126: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) int controlID = GUIUtility.GetControlID((FocusType)2); Event current = Event.current; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(((Rect)(ref _screen)).x + current.mousePosition.x * _scale, ((Rect)(ref _screen)).y + current.mousePosition.y * _scale); EventType typeForControl = current.GetTypeForControl(controlID); switch ((int)typeForControl) { case 0: if (current.button == 0 && ((Rect)(ref rect)).Contains(current.mousePosition)) { GUIUtility.hotControl = controlID; _gripControl = controlID; _gripFrom = val; _sizeFrom = new Vector2(((Rect)(ref _screen)).width, ((Rect)(ref _screen)).height); current.Use(); } break; case 3: if (GUIUtility.hotControl == controlID) { ((Rect)(ref _screen)).width = Mathf.Max(MinSize.x, _sizeFrom.x + (val.x - _gripFrom.x)); ((Rect)(ref _screen)).height = Mathf.Max(MinSize.y, _sizeFrom.y + (val.y - _gripFrom.y)); current.Use(); } break; case 1: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; _gripControl = 0; ConsolePrefs.SaveWindow(_screen); current.Use(); } break; case 2: break; } } private void Rail() { //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_021e: 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) GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Space(4f); NavTo("Players", (AdminTab)0, delegate { _admin.RefreshPlayers(); }); NavTo("Quests", (AdminTab)1, delegate { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); }); NavTo("Activity", (AdminTab)2, delegate { _admin.RefreshLog(_logCategories); }); NavTo("NPCs", (AdminTab)3, delegate { _admin.RefreshNpcs(); _admin.Editor.RefreshLists(); }); NavTo("Creatures", (AdminTab)10, delegate { _admin.RefreshCreatures(); }); GUILayout.Space(10f); GUILayout.Label("CONTENT EDITOR", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Shops", (AdminTab)4, null); NavTo("Quest editor", (AdminTab)5, null); NavTo("NPC creator", (AdminTab)7, null); NavTo("Pictures", (AdminTab)8, null); NavTo("Test tools", (AdminTab)9, delegate { _admin.Editor.RefreshLists(); }); EditorButton(); GUILayout.Space(10f); GUILayout.Label("YOU", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Preferences", (AdminTab)6, null); NavTo("Debug log", (AdminTab)11, delegate { _admin.AskDebug(); }); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.1f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(52f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.1f; } GUILayout.EndHorizontal(); RuneSkin.Line(_superAdmin ? "● SuperAdmin" : "○ Not an admin here", _superAdmin ? RuneSkin.Moss : RuneSkin.Rust); if (_admin.TestKills) { RuneSkin.Line("⚔ Test mode on", RuneSkin.Amber); } GUILayout.Label("Esc closes · drag the corner to resize", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndVertical(); } private static string Percent(float scale) { return checked((int)(scale * 100f + 0.5f)).ToString(CultureInfo.InvariantCulture) + "%"; } private void NavTo(string label, AdminTab tab, Action? opened) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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) bool flag = _admin.Tab == tab; if (!GUILayout.Button(label, RuneSkin.Or(flag ? RuneSkin.NavOn : RuneSkin.Nav, GUI.skin.button), Array.Empty<GUILayoutOption>())) { return; } if (flag) { opened?.Invoke(); return; } Guard("Going to " + label, delegate { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Go(tab); opened?.Invoke(); }); } private void Guard(string what, Action go) { ContentEditor editor = _admin.Editor; if (editor.Form == null || !editor.Dirty) { go(); return; } _leave = go; _leaveWhat = what; _leavePublishing = false; } private void DrawLeave(int id) { //IL_006e: 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) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } try { JsonForm form = _admin.Editor.Form; string text = ((form == null) ? "this" : ((form.DisplayName.Length > 0) ? form.DisplayName : form.Id)); GUILayout.Space(6f); RuneSkin.Line("Changes have been made to " + text + " that are not published yet.", RuneSkin.Amber); GUILayout.Label(_leaveWhat + " would leave them behind. What would you like to do?", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.Space(10f); if (_leavePublishing) { RuneSkin.Line((_admin.Editor.Status.Length > 0) ? _admin.Editor.Status : "Publishing…", RuneSkin.Steel); return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Publish, then go on", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.Publish(_admin.Reason); } if (GUILayout.Button("Save as a draft, then go on", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.SaveDraft(_admin.Reason); } if (GUILayout.Button("Go on without publishing", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { Action leave = _leave; _leave = null; _admin.Editor.Close(); leave?.Invoke(); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leave = null; } GUILayout.EndHorizontal(); } finally { GUI.skin = skin; } } private void FollowPublish() { ContentEditor editor = _admin.Editor; if (_leavePublishing && _leave != null && !editor.Busy) { _leavePublishing = false; if (editor.Dirty) { _leave = null; return; } Action leave = _leave; _leave = null; leave(); } } private void Go(AdminTab tab) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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) if (_admin.Tab != tab) { _admin.Tab = tab; _scroll = Vector2.zero; _shops.LeftPage(); } } private static string PageTitle(AdminTab tab) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown return (int)tab switch { 0 => "Players", 1 => "Quests in progress", 3 => "NPCs in the world", 10 => "Creatures and spawners", 4 => "Shops, trades and money", 5 => "Quests and conversations", 7 => "NPC creator", 8 => "Pictures for the browser editor", 9 => "Test tools", 6 => "Preferences", 11 => "Debug log", _ => "Activity", }; } private void DrawPreferences() { //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Text"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(56f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.05f; } GUILayout.Space(16f); float[] presets = Presets; foreach (float num in presets) { bool flag = Mathf.Abs(ConsolePrefs.TextScale - num) < 0.01f; if (GUILayout.Toggle(flag, Percent(num), GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(64f) }) && !flag) { ConsolePrefs.TextScale = num; } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Resizing the window", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); bool flag2 = GUILayout.Toggle(ConsolePrefs.GrowWithWindow, "makes the text bigger or smaller with it", Array.Empty<GUILayoutOption>()); if (flag2 != ConsolePrefs.GrowWithWindow) { ConsolePrefs.GrowWithWindow = flag2; } GUILayout.EndHorizontal(); GUILayout.Label(ConsolePrefs.GrowWithWindow ? "Drag the window's corner: at its usual size the text is the size above; twice as big, twice the size." : "Drag the window's corner for more room; the text stays the size above.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Font", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Averia Serif (Valheim's)", ConsolePrefs.Font == "averia", delegate { ConsolePrefs.Font = "averia"; }); Choice("Averia Serif light", ConsolePrefs.Font == "averia_light", delegate { ConsolePrefs.Font = "averia_light"; }); Choice("Plain", ConsolePrefs.Font == "plain", delegate { ConsolePrefs.Font = "plain"; }); GUILayout.EndHorizontal(); RuneSkin.Header("Look and colours"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Look", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Rune-carved", ConsolePrefs.Look == "rune", delegate { ConsolePrefs.Look = "rune"; }); Choice("Plain (Unity's own)", ConsolePrefs.Look == "plain", delegate { ConsolePrefs.Look = "plain"; }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Accent", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color, Color, Color)[] accents = RuneSkin.Accents; for (int num2 = 0; num2 < accents.Length; num2++) { (string, string, Color, Color, Color) tuple = accents[num2]; var (text, _, _, _, _) = tuple; if (RuneSkin.Swatch(tuple.Item3, 22f, ConsolePrefs.Accent == text)) { ConsolePrefs.Accent = text; } GUILayout.Label(tuple.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(62f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text colour", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color)[] textColours = RuneSkin.TextColours; for (int num3 = 0; num3 < textColours.Length; num3++) { (string, string, Color) tuple3 = textColours[num3]; var (text2, _, _) = tuple3; if (RuneSkin.Swatch(tuple3.Item3, 22f, ConsolePrefs.TextColour == text2)) { ConsolePrefs.TextColour = text2; } GUILayout.Label(tuple3.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(82f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Panel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.Opacity) + " solid", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity += 0.05f; } GUILayout.Label("(lower lets the world show through)", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (ConsolePrefs.Look == "plain") { GUILayout.Label("The accent, text colour, font and panel apply to the rune-carved look.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Window"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(checked(((int)((Rect)(ref _screen)).width).ToString(CultureInfo.InvariantCulture) + " × " + ((int)((Rect)(ref _screen)).height).ToString(CultureInfo.InvariantCulture)) + " pixels, drawn at " + Percent(_scale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Usual size, middle of the screen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Space(10f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Everything back to the defaults", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) })) { ConsolePrefs.Reset(); ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Label("These are saved on this computer, in the ALIVE Admin config file under [Console]. They change only your console.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private static void Choice(string label, bool chosen, Action choose) { if (GUILayout.Toggle(chosen, label, GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }) && !chosen) { choose(); } } private void KeepUp() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_006e: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected I4, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Invalid comparison between Unknown and I4 if (Event.current == null || (int)Event.current.type != 7) { return; } float unscaledTime = Time.unscaledTime; float num = (((int)_admin.Tab == 3 || (int)_admin.Tab == 10) ? 15f : 10f); if (unscaledTime - _keptUpAt < num) { return; } _keptUpAt = unscaledTime; if (GUIUtility.keyboardControl != 0 || _leave != null) { return; } AdminTab tab = _admin.Tab; switch ((int)tab) { default: if ((int)tab == 10) { _admin.Quietly((Action)_admin.RefreshCreatures); } break; case 0: _admin.Quietly((Action)_admin.RefreshPlayers); if (_admin.FlagsPlayer.Length > 0) { _admin.Quietly((Action)delegate { _admin.ShowFlags(_admin.FlagsPlayer); }); } break; case 1: _admin.Quietly((Action)delegate { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } }); break; case 2: _admin.Quietly((Action)delegate { _admin.RefreshLog(_logCategories); }); break; case 3: _admin.Quietly((Action)_admin.RefreshNpcs); break; } } private void EditorButton() { //IL_00c6: 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) if (OpenEditor == null) { return; } GUILayout.Space(6f); bool enabled = GUI.enabled; GUI.enabled = enabled && _superAdmin; if (GUILayout.Button("Open the editor\nin my browser", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), Array.Empty<GUILayoutOption>())) { OpenEditor(); } GUI.enabled = enabled; if (!_superAdmin) { GUILayout.Label("For SuperAdmins only", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); return; } string text = EditorLine?.Invoke() ?? string.Empty; if (text.Length != 0) { RuneSkin.Line(text, text.Contains("not connected") ? RuneSkin.Rust : RuneSkin.Moss); if (StopEditor != null && GUILayout.Button("Stop it", Array.Empty<GUILayoutOption>())) { StopEditor(); } } } private void Page() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected I4, but got Unknown //IL_00c4: 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_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Invalid comparison between Unknown and I4 //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Invalid comparison between Unknown and I4 //IL_01e2: 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_010f: 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_02ed: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label(PageTitle(_admin.Tab), RuneSkin.Or(RuneSkin.Title, GUI.skin.label), Array.Empty<GUILayoutOption>()); _scroll = GUILayout.BeginScrollView(_scroll, Array.Empty<GUILayoutOption>()); AdminTab tab = _admin.Tab; switch ((int)tab) { case 0: DrawPlayers(); break; case 1: DrawQuests(); break; case 3: DrawNpcs(); break; case 10: DrawCreatures(); break; case 4: case 5: case 7: { ShopEditorView shops = _shops; AdminTab tab2 = _admin.Tab; EditorPage page = (((int)tab2 == 5) ? EditorPage.Stories : (((int)tab2 == 7) ? EditorPage.Npcs : EditorPage.Shops)); shops.Page = page; _shops.Draw(); if (_shops.WantsTop) { _shops.WantsTop = false; _scroll = Vector2.zero; } break; } case 6: DrawPreferences(); break; case 8: PicturesSection(); break; case 9: DrawTestTools(); break; case 11: DrawDebug(); break; default: DrawLog(); break; } GUILayout.EndScrollView(); GUILayout.Space(6f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Note for the audit log", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); _admin.Reason = GUILayout.TextField(_admin.Reason ?? string.Empty, 256, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (_superAdmin) { GUILayout.Label("Optional. Every change is recorded with your Steam id either way.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } else { RuneSkin.Line(AdminClient.NotAnAdmin(_admin.PlatformId), RuneSkin.Rust); } if (_admin.PendingOpId.Length > 0) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); RuneSkin.Line("Waiting for another SuperAdmin: " + _admin.PendingOpId, RuneSkin.Amber); if (GUILayout.Button("Approve", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, true); } if (GUILayout.Button("Refuse", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, false); } GUILayout.EndHorizontal(); } if (_admin.Status.Length > 0) { RuneSkin.Line(_admin.Status, RuneSkin.Tone(_admin.Status)); } } private void DrawPlayers() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Name or Steam id", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); _admin.PlayerQuery = GUILayout.TextField(_admin.PlayerQuery ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Search", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshPlayers(); } GUILayout.EndHorizontal(); foreach (PlayerSearchItem player in _admin.Players) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((player.Online ? "● " : "○ ") + ((player.LastName.Length == 0) ? "(no name yet)" : player.LastName), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(player.PlatformId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(player.SessionCount + " visit(s), last " + Ago(player.LastSeenUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); if (GUILayout.Button("Quests", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshQuests(player.PlatformId, false); } if (GUILayout.Button("Flags…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; _admin.ShowFlags(player.PlatformId); } GUILayout.EndHorizontal(); } if (_admin.Players.Count == 0) { GUILayout.Label("Nobody matched. The list holds players who have joined with ALIVE at least once.", Array.Empty<GUILayoutOption>()); } if (_admin.FlagsPlayer.Length > 0) { DrawFlags(); } } private void DrawFlags() { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_08c1: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); string text = ((_admin.FlagsName.Length > 0) ? _admin.FlagsName : _admin.FlagsPlayer); GUILayout.Space(10f); RuneSkin.Header(text + "'s ALIVE flags" + ((_admin.FlagsTotal >= 0) ? (" · " + _admin.FlagsTotal) : string.Empty)); GUILayout.Label(_admin.FlagsPlayer + ". A flag is a yes-or-no mark ALIVE keeps for each player: quests and conversations give and take them and read them to decide what happens. The browser editor's Story memory page shows where each one is set and read.", val, Array.Empty<GUILayoutOption>()); foreach (string flagLine in _admin.FlagLines) { RuneSkin.Line(flagLine, RuneSkin.Tone(flagLine)); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Find", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); _flagFind = GUILayout.TextField(_flagFind ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }); if (GUILayout.Button("⟳ Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (_admin.FlagsTotal < 0) { GUILayout.Label("Asking the server…", val, Array.Empty<GUILayoutOption>()); } else if (_admin.FlagsTotal == 0) { GUILayout.Label(text + " holds no ALIVE flags.", val, Array.Empty<GUILayoutOption>()); } string find = (_flagFind ?? string.Empty).Trim(); List<PlayerFlagItem> list = (from f in _admin.PlayerFlags where find.Length == 0 || f.Flag.Contains(find, StringComparison.OrdinalIgnoreCase) orderby (!string.Equals(f.Flag, _admin.LitFlag, StringComparison.Ordinal)) ? 1 : 0 select f).ToList(); if (find.Length > 0 && list.Count == 0 && _admin.FlagsTotal > 0) { GUILayout.Label("None of their flags is called that.", val, Array.Empty<GUILayoutOption>()); } foreach (PlayerFlagItem item in list) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text2 = (item.Flag.StartsWith("alive:flag/", StringComparison.Ordinal) ? item.Flag.Substring("alive:flag/".Length) : item.Flag); bool flag = string.Equals(item.Flag, _admin.LitFlag, StringComparison.Ordinal); Color contentColor = GUI.contentColor; if (flag) { GUI.contentColor = RuneSkin.Amber; } GUILayout.Label((flag ? "● " : string.Empty) + text2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUI.contentColor = contentColor; GUILayout.Label("set " + Ago(item.SetUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Clear", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ClearFlags(item.Flag); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal > _admin.PlayerFlags.Count) { GUILayout.Label("…and " + checked(_admin.FlagsTotal - _admin.PlayerFlags.Count) + " more, oldest first, not shown.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Give a flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _giveFlag = NameBox("alive_give_flag", _giveFlag); GUI.enabled = _giveFlag.Trim().Length > 0 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Give", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.GiveFlag(_giveFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); NameSuggestions("alive_give_flag", _giveFlag, _admin.KnownFlags, "alive:flag/", "flags", delegate(string v) { _giveFlag = v; }); GUILayout.Space(6f); GUILayout.Label("Counters: numbers ALIVE keeps for each player, which quests and conversations add to and compare.", val, Array.Empty<GUILayoutOption>()); foreach (PlayerCounterItem playerCounter in _admin.PlayerCounters) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text3 = (playerCounter.Counter.StartsWith("alive:counter/", StringComparison.Ordinal) ? playerCounter.Counter.Substring("alive:counter/".Length) : playerCounter.Counter); GUILayout.Label(text3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUILayout.Label(playerCounter.Value.ToString(CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Change…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _counterName = text3; _counterValue = playerCounter.Value.ToString(CultureInfo.InvariantCulture); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal >= 0 && _admin.PlayerCounters.Count == 0) { GUILayout.Label(text + " holds no ALIVE counters.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Set a counter", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _counterName = NameBox("alive_set_counter", _counterName); GUILayout.Label("to", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(20f) }); _counterValue = GUILayout.TextField(_counterValue, 12, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); long result; bool flag2 = long.TryParse(_counterValue.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out result); GUI.enabled = _counterName.Trim().Length > 0 && flag2 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Set", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.SetCounter(_counterName, result); } GUI.enabled = true; GUILayout.EndHorizontal(); if (_counterValue.Trim().Length > 0 && !flag2) { GUILayout.Label("A counter is a whole number, such as 3 or -1. 0 takes it away.", val, Array.Empty<GUILayoutOption>()); } NameSuggestions("alive_set_counter", _counterName, _admin.KnownCounters, "alive:counter/", "counters", delegate(string v) { _counterName = v; }); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _admin.FlagsTotal > 0; if (GUILayout.Button("Clear all…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _confirmClearAll = !_confirmClearAll; } GUI.enabled = true; if (GUILayout.Button("Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmClearAll = false; _admin.HideFlags(); } GUILayout.EndHorizontal(); if (_confirmClearAll && _admin.FlagsTotal > 0) { RuneSkin.Line("Clear all " + _admin.FlagsTotal + " flags " + text + " holds? Quests and conversations that read them will treat " + text + " as if they never had them.", RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Clear them all", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmClearAll = false; _admin.ClearFlags(string.Empty); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; } GUILayout.EndHorizontal(); } } private string NameBox(string control, string value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Invalid comparison between Unknown and I4 //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 if ((int)Event.current.type == 8 && _pendingName.Control == control) { value = _pendingName.Value; _pendingName = (Control: string.Empty, Value: string.Empty); _activeNameBox = string.Empty; if (GUI.GetNameOfFocusedControl() == control) { GUIUtility.keyboardControl = 0; } } GUI.SetNextControlName(control); string text = GUILayout.TextField(value, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if ((int)Event.current.type == 8 && GUI.GetNameOfFocusedControl() == control && !string.Equals(text, _lastTyped, StringComparison.Ordinal)) { _activeNameBox = control; } if ((int)Event.current.type == 8) { _lastTyped = ((GUI.GetNameOfFocusedControl() == control) ? text : _lastTyped); } bool flag = _openNameList == control; if (GUILayout.Button(flag ? "Hide list" : "List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(72f) })) { _openNameList = (flag ? string.Empty : control); } return text; } private void NameSuggestions(string control, string value, IReadOnlyList<string> known, string prefix, string what, Action<string> chosen) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0116: 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_0150: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 8) { _nameRows[control] = NameRows.Of(control == _openNameList, control == _activeNameBox, value, known, prefix); } if (!_nameRows.TryGetValue(control, out NameRows value2) || !value2.Shown) { return; } GUIStyle val = RuneSkin.Or(RuneSkin.Row, GUI.skin.button); GUIStyle val2 = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(110f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(value2.Open ? 306f : 280f) }); if (value2.Open && value2.Names.Count == 0) { GUILayout.Label((value2.Known == 0) ? ("The server knows no " + what + " yet: none is set or read by its quests and conversations, and no player holds one.") : ("None of the " + what + " the server knows has that in its name."), val2, Array.Empty<GUILayoutOption>()); } else if (value2.Open) { _nameListScroll = GUILayout.BeginScrollView(_nameListScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(Mathf.Min(220f, 26f * (float)value2.Names.Count + 8f)) }); foreach (string name in value2.Names) { if (GUILayout.Button(name, val, Array.Empty<GUILayoutOption>())) { Choose(control, name, chosen); } } GUILayout.EndScrollView(); } else { foreach (string name2 in value2.Names) { if (GUILayout.Button(name2, val, Array.Empty<GUILayoutOption>())) { Choose(control, name2, chosen); } } if (value2.More > 0) { GUILayout.Label("…and " + value2.More.ToString(CultureInfo.InvariantCulture) + " more: type more, or open the list.", val2, Array.Empty<GUILayoutOption>()); } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } private void Choose(string control, string name, Action<string> chosen) { chosen(name); _pendingName = (Control: control, Value: name); _openNameList = string.Empty; _activeNameBox = string.Empty; } private void DrawQuests() { //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: Unknown result type (might be due to invalid IL or missing references) //IL_065f: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((_admin.QuestPlayer.Length == 0) ? "Every player" : ("Player " + _admin.QuestPlayer), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); bool flag = GUILayout.Toggle(_openOnly, "Only unfinished", Array.Empty<GUILayoutOption>()); if (flag != _openOnly) { _openOnly = flag; _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } } if (_admin.QuestPlayer.Length > 0 && GUILayout.Button("All players", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.RefreshQuests(string.Empty, _openOnly); } string text = ((_admin.WaitingCount > 0) ? ("Waiting for me (" + _admin.WaitingCount.ToString(CultureInfo.InvariantCulture) + ")") : "Waiting for me"); if (GUILayout.Button(text, (GUIStyle)((_admin.WaitingCount > 0) ? ((object)RuneSkin.Or(RuneSkin.Primary, GUI.skin.button)) : ((object)GUI.skin.button)), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) })) { _admin.RefreshWaiting(); } GUILayout.EndHorizontal(); TestKillsRow(); if (_admin.ShowingWaiting) { RuneSkin.Line("Quests with a step waiting for an admin to check it. Mark the step done when the player has done it.", RuneSkin.Amber); } foreach (QuestInstanceRow quest in _admin.Quests) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(quest.QuestId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(230f) }); GUILayout.Label(StateName(quest.State) + " (try " + quest.Attempt + ")", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Progress(quest), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); bool flag2 = quest.State != 0 && QuestStates.IsOpen((QuestState)quest.State); if (flag2 && GUILayout.Button("Clear progress", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.ResetQuest(quest.InstanceId, false); } if (GUILayout.Button(flag2 ? "Full reset" : "Let them retake", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(flag2 ? 80f : 120f) })) { _admin.ResetQuest(quest.InstanceId, true); } if (flag2 && GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.CancelQuest(quest.InstanceId); } if (GUILayout.Button("Take rewards", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.RevokeQuest(quest.InstanceId); } if (GUILayout.Button("Close to player", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, true, 0uL); } if (GUILayout.Button("Reopen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, false, 0uL); } if ((quest.State == 2 || quest.State == 3 || quest.State == 7 || quest.State == 9) && GUILayout.Button("Complete…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmComplete = ((_confirmComplete == quest.InstanceId) ? 0 : quest.InstanceId); } if (quest.State == 7 && GUILayout.Button("Resume", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ResumeQuest(quest.InstanceId); } GUI.enabled = _superAdmin; if (GUILayout.Button("Wipe…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = ((_confirmWipe == quest.InstanceId) ? 0 : quest.InstanceId); } GUI.enabled = true; GUILayout.EndHorizontal(); if (quest.Status.Length > 0) { RuneSkin.Line(" " + quest.Status, RuneSkin.Amber); } if (_confirmWipe == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Wipe " + quest.QuestId + " from " + quest.PlatformId + "'s history, as if they never took it? Every attempt, its steps and the flags it uses go, and rewards it has not handed over are not handed over. What they were given stays theirs. This cannot be undone; the audit log keeps the record.", RuneSkin.Amber); if (GUILayout.Button("Wipe it", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmWipe = 0uL; _admin.WipeQuest(quest.InstanceId); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = 0uL; } GUILayout.EndHorizontal(); } if (_confirmComplete == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Complete it for " + quest.PlatformId + " as if they had finished it? The rewards are paid; nothing it asked for is taken.", RuneSkin.Amber); if (GUILayout.Button("Complete and pay", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmComplete = 0uL; _admin.CompleteQuest(quest.InstanceId, ""); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmComplete = 0uL; } GUILayout.EndHorizontal(); } foreach (QuestObjectiveRow objective in quest.Objectives) { if (objective.Manual) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); GUILayout.Label("Step \"" + objective.ObjectiveId + "\"" + ((objective.Text.Length > 0) ? (": " + objective.Text) : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(520f) }); if (GUILayout.Button("Mark it done", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.CompleteQuest(quest.InstanceId, objective.ObjectiveId); } GUILayout.EndHorizontal(); } } } if (_admin.Quests.Count == 0) { GUILayout.Label(_admin.ShowingWaiting ? "Nothing is waiting for you to check." : "No quest instances yet.", Array.Empty<GUILayoutOption>()); } } private void TestKillsRow() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); bool flag = GUILayout.Toggle(_admin.TestKills, "Test mode: what I do counts for my quests at once, even with creatures and items I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); if (flag != _admin.TestKills) { _admin.SetTestKills(flag); } GUILayout.EndHorizontal(); GUILayout.Label(_admin.TestKills ? "On for you until you log off: your kills, what you pick up for gathering steps, and taming count at once. Each is in the activity log (kill.test, quest.gather_test). Players beside you are checked as always." : "Off: you are checked like everyone else. A creature that appears right beside a player must be watched a while before its death counts, and only what was gathered in the world counts for gathering steps.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private void DrawTestTools() { //IL_0397: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); RuneSkin.Header("Meet an NPC again for the first time"); GUILayout.Label("The NPC forgets you: how often you have spoken, the lines you heard and the answers you chose in their conversation, and the flags that conversation gives. Only you: players keep what they have.", val, Array.Empty<GUILayoutOption>()); IReadOnlyList<ContentListItem> readOnlyList = _admin.Editor.Listed((AliveIdKind)1); foreach (ContentListItem item in readOnlyList) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((item.DisplayName.Length > 0) ? item.DisplayName : item.Id, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if (GUILayout.Button("Forget me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.UseStoryTool((byte)1, item.Id); } GUILayout.EndHorizontal(); } if (readOnlyList.Count == 0) { GUILayout.Label("(no NPCs yet, or the list is still loading)", val, Array.Empty<GUILayoutOption>()); } GUILayout.Space(8f); RuneSkin.Header("Your own flags"); GUILayout.Label("Give yourself a flag, or take one away, to try a branch without playing up to it. Every flag, with what sets it and what reads it, is on the browser editor's Story memory page.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storyFlag = GUILayout.TextField(_storyFlag, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storyFlag.Trim().Length > 0; if (GUILayout.Button("Give me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)2, _storyFlag); } if (GUILayout.Button("Take away", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)3, _storyFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); if (GUILayout.Button("See all my flags", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { string playerQuery = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : string.Empty); _admin.PlayerQuery = playerQuery; Go((AdminTab)0); _admin.RefreshPlayers(); } GUILayout.Space(8f); RuneSkin.Header("Server switches"); GUILayout.Label("One on/off for every player, read by conversations as \"Server switch is on\". Switching it changes what every player meets at once.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Switch", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storySwitch = GUILayout.TextField(_storySwitch, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storySwitch.Trim().Length > 0; if (GUILayout.Button("On for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)4, _storySwitch); } if (GUILayout.Button("Off for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)5, _storySwitch); } GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.Space(8f); RuneSkin.Header("Kills"); TestKillsRow(); if (_admin.StoryLines.Count == 0) { return; } GUILayout.Space(8f); foreach (string storyLine in _admin.StoryLines) { RuneSkin.Line(storyLine, RuneSkin.Moss); } } private void DrawNpcs() { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Place an NPC"); GUILayout.Label("Place here puts the NPC where you stand, facing you. Place… lets you aim: the NPC follows where you look, the wheel turns it, a click puts it down, right-click stops. The server takes any spot within 30 m of you.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _npcLabel = GUILayout.TextField(_npcLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.FlexibleSpace(); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshNpcs(); } GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } _shops.DrawDeleteBox(); if (_admin.Editor.DeleteId.Length == 0 && _admin.Editor.Status.StartsWith("Deleted", StringComparison.Ordinal)) { RuneSkin.Line(_admin.Editor.Status, RuneSkin.Moss); } string text = _npcLabel ?? string.Empty; foreach (string item in _admin.Placeable) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(NpcName(item), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(item, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceNpc(item, text); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceWithTool != null) { PlaceWithTool(item, text); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(item); } ContentListItem val = Listed(item); GUI.enabled = val != null && !_admin.Editor.Busy; if (GUILayout.Button("Delete…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && val != null) { _admin.Editor.AskDelete(val.Id, val.Version, NpcName(item)); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.Placeable.Count == 0) { GUILayout.Label("The loaded content has no NPCs to place.", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("In the world"); foreach (NpcPlacementRow placement in _admin.Placements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((placement.Enabled ? "● " : "○ ") + placement.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label((placement.Label.Length == 0) ? "-" : placement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(Metres(placement.XCm) + ", " + Metres(placement.YCm) + ", " + Metres(placement.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUILayout.Label("placed " + Ago(placement.PlacedUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); if (GUILayout.Button("Teleport to NPC", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) })) { _admin.GoToNpc(placement.PlacementId); } if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveWithTool != null) { MoveWithTool(placement.PlacementId, placement.NpcId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveNpc(placement.PlacementId); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(placement.NpcId); } GUILayout.EndHorizontal(); } if (_admin.Placements.Count == 0) { GUILayout.Label("No NPC has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void DrawCreatures() { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("Creatures and spawners are made in the browser editor on the server machine and published there. Here you try them and place them.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshCreatures(); } GUILayout.FlexibleSpace(); GUILayout.Label(_admin.CreaturesAlive.ToString(CultureInfo.InvariantCulture) + " of at most " + _admin.CreatureLimit.ToString(CultureInfo.InvariantCulture) + " ALIVE creatures alive · " + _admin.CreaturesMine.ToString(CultureInfo.InvariantCulture) + " spawned by you", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } if (!_admin.CllcOnServer && _admin.CreaturesKnown) { GUILayout.Label("Creature Level & Loot Control is not on this server: creatures' settings for it are skipped.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Creatures"); GUILayout.Label("Spawn with the Admin Tool: aim, click for one, Shift+click for five, right-click to stop. A creature you spawn gives no loot, kill credit or world key, unless your test mode is on (Test tools).", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); foreach (CreatureRow creatureRow in _admin.CreatureRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(creatureRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(creatureRow.Base + ((creatureRow.Level > 1) ? (" " + new string('★', Math.Min(9, checked(creatureRow.Level - 1)))) : string.Empty) + (creatureRow.Boss ? " · boss" : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(creatureRow.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && SpawnWithTool != null; if (GUILayout.Button("Spawn with the Admin Tool", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) })) { if (NpcHammer.Held() == null && GiveHammer != null) { _hammerNote = GiveHammer(); } SpawnWithTool(creatureRow.Id); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.CreatureRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No creatures yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Remove the ones I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) })) { _admin.ClearCreatures((CreatureClearScope)0, 0uL); } GUI.enabled = _superAdmin; if (!_confirmRemoveCreatures) { if (GUILayout.Button("Remove every ALIVE creature…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { _confirmRemoveCreatures = true; } } else { if (GUILayout.Button("Yes, remove them all", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) })) { _confirmRemoveCreatures = false; _admin.ClearCreatures((CreatureClearScope)2, 0uL); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmRemoveCreatures = false; } } GUI.enabled = true; GUILayout.EndHorizontal(); RuneSkin.Header("Spawn points and altars"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _spawnerLabel = GUILayout.TextField(_spawnerLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.EndHorizontal(); foreach (SpawnerRow spawnerRow in _admin.SpawnerRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(spawnerRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(spawnerRow.Altar ? ("altar" + ((spawnerRow.Look.Length > 0) ? (" (" + spawnerRow.Look + ")") : string.Empty)) : "spawn point", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceSpawner(spawnerRow.Id, _spawnerLabel ?? string.Empty); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceSpawnerWithTool != null) { PlaceSpawnerWithTool(spawnerRow.Id, _spawnerLabel ?? string.Empty); } GUILayout.EndHorizontal(); } if (_admin.SpawnerRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No spawners yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Placed"); foreach (SpawnerPlacementRow spawnerPlacement in _admin.SpawnerPlacements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(_admin.SpawnerName(spawnerPlacement.SpawnerId), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label((spawnerPlacement.Label.Length == 0) ? "-" : spawnerPlacement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Metres(spawnerPlacement.Spot.XCm) + ", " + Metres(spawnerPlacement.Spot.YCm) + ", " + Metres(spawnerPlacement.Spot.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(spawnerPlacement.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && _admin.TeleportTo != null; if (GUILayout.Button("Teleport to", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.TeleportTo((double)spawnerPlacement.Spot.XCm / 100.0, (double)spawnerPlacement.Spot.YCm / 100.0, (double)spawnerPlacement.Spot.ZCm / 100.0, (double)spawnerPlacement.Spot.FacingCentiDeg / 100.0); } GUI.enabled = true; if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveSpawnerWithTool != null) { MoveSpawnerWithTool(spawnerPlacement.PlacementId, spawnerPlacement.SpawnerId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveSpawner(spawnerPlacement.PlacementId); } if (spawnerPlacement.Alive > 0 && GUILayout.Button("Remove its creatures", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _admin.ClearCreatures((CreatureClearScope)1, spawnerPlacement.PlacementId); } GUILayout.EndHorizontal(); } if (_admin.SpawnerPlacements.Count == 0) { GUILayout.Label("No spawner has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void PicturesSection() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Invalid comparison between Unknown and I4 //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Invalid comparison between Unknown and I4 //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) PictureRun pictures = _admin.Pictures; if (_picturesAsked.Length > 0 && !pictures.Busy) { RuneSkin.Line(_picturesAsked, RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin; if (GUILayout.Button("Take pictures", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _picturesAsked = string.Empty; pictures.Start(); } GUI.enabled = true; if (GUILayout.Button("Not now", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _picturesAsked = string.Empty; } GUILayout.EndHorizontal(); GUILayout.Space(8f); } GUILayout.Label("The browser editor on the server machine shows a picture of each creature, item, building piece and object. The server has no graphics, so your game takes them and sends them. It takes a few minutes; you can keep playing.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUI.enabled = !pictures.Busy; GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); pictures.Creatures = GUILayout.Toggle(pictures.Creatures, "Creatures & characters", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Items = GUILayout.Toggle(pictures.Items, "Items", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Pieces = GUILayout.Toggle(pictures.Pieces, "Building pieces", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Objects = GUILayout.Toggle(pictures.Objects, "Objects", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.RetakeAll = GUILayout.Toggle(pictures.RetakeAll, "Take again
plugins/attestation/0.61.0/admin/ALIVE.Core.dll.attest
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core.Abstractions; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content; using ALIVE.Core.Content.Conditions; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Currencies; using ALIVE.Core.Content.Dialogue; using ALIVE.Core.Content.Economy; using ALIVE.Core.Content.Effects; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Json; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Content.Packs; using ALIVE.Core.Content.Pricing; using ALIVE.Core.Content.Quests; using ALIVE.Core.Content.Schema; using ALIVE.Core.Content.Shops; using ALIVE.Core.Content.Trades; using ALIVE.Core.Content.Validation; using ALIVE.Core.Diagnostics; using ALIVE.Core.Economy; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [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("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Core")] [assembly: InternalsVisibleTo("ALIVE.Core.Tests")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } } namespace ALIVE.Core { public static class AliveCoreVersion { public static readonly string Value = ReadFromAssembly(); private static string ReadFromAssembly() { return typeof(AliveCoreVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0"; } } public static class AliveGuid { public const string Server = "com.imaginaryrealms.alive.server"; public const string Player = "com.imaginaryrealms.alive.client.player"; public const string Admin = "com.imaginaryrealms.alive.client.admin"; public static bool IsPlayer(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.player"); } return true; } public static bool IsAdmin(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.admin")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } public static bool IsAlive(string? id) { if (!IsPlayer(id) && !IsAdmin(id) && !Is(id, "com.imaginaryrealms.alive.server")) { return Is(id, "net.winterwolf.alive.server"); } return true; } public static bool IsOld(string? id) { if (!Is(id, "net.winterwolf.alive.server") && !Is(id, "net.winterwolf.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } private static bool Is(string? id, string guid) { return string.Equals(id, guid, StringComparison.Ordinal); } } public static class AliveOldGuid { public const string Server = "net.winterwolf.alive.server"; public const string Player = "net.winterwolf.alive.client.player"; public const string Admin = "net.winterwolf.alive.client.admin"; } public static class SettingsCarry { public static string? FromOldId(string configFolder, string oldId, string newId) { if (string.IsNullOrEmpty(configFolder) || string.IsNullOrEmpty(oldId) || string.IsNullOrEmpty(newId)) { return null; } string text = Path.Combine(configFolder, newId + ".cfg"); string text2 = Path.Combine(configFolder, oldId + ".cfg"); if (File.Exists(text) || !File.Exists(text2)) { return null; } File.Copy(text2, text, overwrite: false); return "settings carried over from " + oldId + ".cfg to " + newId + ".cfg, as ALIVE's id changed in 0.61.0. The old file is no longer read and may be deleted."; } } public static class OldCopies { public static readonly Version FirstWithNewIds = new Version(0, 61, 0); private static readonly string[] PluginFiles = new string[3] { "ALIVE.Server.dll", "ALIVE.Client.Player.dll", "ALIVE.Client.Admin.dll" }; public static IReadOnlyList<string> Find(string pluginFolder, Func<string, Version?> versionOf) { if (versionOf == null) { throw new ArgumentNullException("versionOf"); } List<string> list = new List<string>(); if (string.IsNullOrEmpty(pluginFolder) || !Directory.Exists(pluginFolder)) { return list; } string[] pluginFiles = PluginFiles; foreach (string searchPattern in pluginFiles) { IEnumerable<string> files; try { files = Directory.GetFiles(pluginFolder, searchPattern, SearchOption.AllDirectories); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { continue; } foreach (string item in files) { Version version = versionOf(item); if (version != null && version < FirstWithNewIds) { list.Add(item); } } } list.Sort(StringComparer.OrdinalIgnoreCase); return list; } public static Version? VersionOfFile(string path) { try { return AssemblyName.GetAssemblyName(path).Version; } catch (Exception ex) when (ex is IOException || ex is BadImageFormatException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is SecurityException) { return null; } } public static string Refusal(string plugin, string version, IReadOnlyList<string> copies) { return plugin + " " + version + " is not starting: an older copy of ALIVE (from before 0.61.0, when its id was net.winterwolf.alive.*) is still in BepInEx/plugins: " + string.Join("; ", copies ?? Array.Empty<string>()) + ". Delete that copy's folder, keep the one your mod manager installed, and start again."; } } public static class AliveNames { public const string Server = "ALIVE Server"; public const string Player = "ALIVE Player"; public const string Admin = "ALIVE Admin"; } public static class AliveWorld { public const string Prefab = "ALIVE_Signpost"; public const string BasePrefab = "piece_banner01"; public const string FallbackPrefab = "sign"; public const string PersonPrefab = "ALIVE_Villager"; public const string PersonBase = "Player"; public const string ModelPrefab = "ALIVE_Model"; public const string ModelBase = "piece_chest_wood"; public const string DvergrShape = "Dverger"; public const string ShapeKey = "alive_shape"; public const string TillPrefab = "ALIVE_Till"; public const string TillBase = "piece_chest_wood"; public const string TillKey = "alive_till"; public const int TillWidth = 8; public const int TillHeight = 4; public const string SubtitleKey = "alive_subtitle"; public const string ModelKey = "alive_model"; public const string HairKey = "alive_hair"; public const string BeardKey = "alive_beard"; public const string SkinKey = "alive_skin"; public const string HairColorKey = "alive_hair_color"; public const string ScaleKey = "alive_scale"; public const string FaceKey = "alive_face"; public const string EquipmentKeyPrefix = "alive_eq_"; public const string EquipmentColorKeyPrefix = "alive_eqc_"; public const string NpcKey = "alive_npc"; public const string NameKey = "alive_name"; public const string PromptKey = "alive_prompt"; public const string HoverKey = "alive_hover"; public const string NoUseKey = "alive_nouse"; public const string LifeKey = "alive_life"; public const string LifeKey2 = "alive_life2"; public const string LifeKey3 = "alive_life3"; public const string LifeKey4 = "alive_life4"; public const string HomeKey = "alive_home"; public const string HomeTurnKey = "alive_home_turn"; public const string LabelShowKey = "alive_label"; public const string LabelTextKey = "alive_label_text"; public const string LabelSubKey = "alive_label_sub"; public const string LabelColorKey = "alive_label_color"; public const string LabelSubColorKey = "alive_label_subcolor"; public const string LabelSizeKey = "alive_label_size"; public const string LabelHeightKey = "alive_label_height"; public const string LabelRangeKey = "alive_label_range"; public const string LabelStyleKey = "alive_label_style"; public const int LabelBold = 1; public const int LabelItalic = 2; public const int LabelOutline = 4; public const string PlacementKey = "alive_placement"; public const string HammerPrefab = "ALIVE_NpcHammer"; public const string HammerBase = "Hammer"; public const string BoardPiecePrefab = "ALIVE_JobBoard"; public const string BoardPieceBase = "sign"; public const string CreatureKey = "alive_creature"; public const string CreatureSpawnKey = "alive_spawn"; public const string CreatureFirstKey = "alive_cr_uid"; public const string CreatureDamageKey = "alive_cr_damage"; public const string CreatureScaleKey = "alive_cr_scale"; public const string CreatureResistKey = "alive_cr_resist"; public const string CreatureFactionKey = "alive_cr_faction"; public const string CreaturePassiveKey = "alive_cr_passive"; public const string CreatureAngryKey = "alive_cr_angry"; public const string CreatureNoDropsKey = "alive_cr_nodrops"; public const string CreatureColorsKey = "alive_cr_colors"; public const string AltarKey = "alive_altar"; public const string SentryKey = "alive_sentry"; public const string FightKey = "alive_fight"; public const string FightWithKey = "alive_fight_with"; public const string DownKey = "alive_down_until"; public const string SentryHealthKey = "alive_sentry_hp"; public const string SentryRestKey = "alive_sentry_rest"; public const string SentryPrefab = "ALIVE_Sentry"; public const string CreatureNoEliteKey = "alive_cr_noelite"; public const string SentryOfKey = "alive_sentry_of"; public const string FightFromKey = "alive_fight_from"; public const string FightKitKey = "alive_fight_kit"; public const string FightDoneKey = "alive_fight_done"; } } namespace ALIVE.Core.Web { public sealed class LocalHttpServer : IDisposable { public const int MaxHeadBytes = 16384; public const int MaxBodyBytes = 4194304; public const int MaxConnections = 8; private const int TimeoutMs = 15000; private readonly Func<LocalRequest, LocalResponse> _handle; private readonly IAliveLog _log; private TcpListener? _listener; private int _open; private volatile bool _stopping; private static readonly string[] LineBreak = new string[1] { "\r\n" }; public int Port { get; private set; } public LocalHttpServer(Func<LocalRequest, LocalResponse> handle, IAliveLog log) { _handle = handle ?? throw new ArgumentNullException("handle"); _log = log ?? throw new ArgumentNullException("log"); } public void Start(int port) { if (_listener != null) { throw new InvalidOperationException("The editor's server is already listening."); } TcpListener tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(16); _listener = tcpListener; Port = ((IPEndPoint)tcpListener.LocalEndpoint).Port; Thread thread = new Thread(AcceptLoop); thread.IsBackground = true; thread.Name = "ALIVE web editor"; thread.Start(); } public void Dispose() { _stopping = true; try { _listener?.Stop(); } catch (SocketException) { } _listener = null; } private void AcceptLoop() { while (!_stopping) { TcpClient client; try { TcpListener listener = _listener; if (listener == null) { break; } client = listener.AcceptTcpClient(); } catch (Exception) when (_stopping) { break; } catch (Exception ex2) { _log.Warning("ALIVE web editor: a connection could not be taken: " + ex2.Message); continue; } if (Interlocked.Increment(ref _open) > 8) { Interlocked.Decrement(ref _open); client.Close(); } else { ThreadPool.QueueUserWorkItem(delegate { Serve(client); }); } } } private void Serve(TcpClient client) { try { client.ReceiveTimeout = 15000; client.SendTimeout = 15000; using (client) { using NetworkStream stream = client.GetStream(); string refusal; LocalRequest localRequest = Read(stream, out refusal); LocalResponse response; if (localRequest == null) { response = LocalResponse.Text(400, refusal ?? "That request could not be read."); } else { try { response = _handle(localRequest); } catch (Exception exception) { _log.Failure("ALIVE web editor: answering " + localRequest.Method + " " + localRequest.Path + " failed.", exception); response = LocalResponse.Text(500, "Something went wrong on the server; its log says what."); } } Write(stream, response); } } catch (IOException) { } catch (SocketException) { } catch (ObjectDisposedException) { } finally { Interlocked.Decrement(ref _open); } } public static LocalRequest? Read(Stream stream, out string? refusal) { refusal = null; List<byte> list = new List<byte>(1024); checked { while (!EndsTheHead(list)) { int num = stream.ReadByte(); if (num < 0) { refusal = "The request ended early."; return null; } list.Add((byte)num); if (list.Count > 16384) { refusal = "The request's headers are too long."; return null; } } string[] array = Encoding.ASCII.GetString(list.ToArray(), 0, list.Count - 4).Split(LineBreak, StringSplitOptions.None); string[] array2 = array[0].Split(new char[1] { ' ' }); if (array2.Length != 3 || !array2[2].StartsWith("HTTP/1.", StringComparison.Ordinal)) { refusal = "That is not an HTTP request."; return null; } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < array.Length; i++) { int num2 = array[i].IndexOf(':'); if (num2 > 0) { string key = array[i].Substring(0, num2).Trim(); string text = array[i].Substring(num2 + 1).Trim(); dictionary[key] = (dictionary.TryGetValue(key, out var value) ? (value + ", " + text) : text); } } int result = 0; if (dictionary.TryGetValue("Content-Length", out var value2) && (!int.TryParse(value2, NumberStyles.None, CultureInfo.InvariantCulture, out result) || result > 4194304)) { refusal = "The request's body is too large."; return null; } if (dictionary.ContainsKey("Transfer-Encoding")) { refusal = "Chunked requests are not taken; send a Content-Length."; return null; } byte[] array3 = new byte[result]; int num3; for (int j = 0; j < result; j += num3) { num3 = stream.Read(array3, j, result - j); if (num3 <= 0) { refusal = "The request's body ended early."; return null; } } string text2 = array2[1]; int num4 = text2.IndexOf('?'); string stringToUnescape = ((num4 < 0) ? text2 : text2.Substring(0, num4)); return new LocalRequest(array2[0].ToUpperInvariant(), Uri.UnescapeDataString(stringToUnescape), Query((num4 < 0) ? string.Empty : text2.Substring(num4 + 1)), dictionary, Encoding.UTF8.GetString(array3)); } } private static bool EndsTheHead(List<byte> head) { int count = head.Count; checked { if (count >= 4 && head[count - 4] == 13 && head[count - 3] == 10 && head[count - 2] == 13) { return head[count - 1] == 10; } return false; } } private static Dictionary<string, string> Query(string query) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); string[] array = query.Split(new char[1] { '&' }); foreach (string text in array) { if (text.Length != 0) { int num = text.IndexOf('='); string key = Uri.UnescapeDataString(((num < 0) ? text : text.Substring(0, num)).Replace('+', ' ')); string value = ((num < 0) ? string.Empty : Uri.UnescapeDataString(text.Substring(checked(num + 1)).Replace('+', ' '))); dictionary[key] = value; } } return dictionary; } private static void Write(Stream stream, LocalResponse response) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("HTTP/1.1 ").Append(response.Status.ToString(CultureInfo.InvariantCulture)).Append(' ') .Append(Reason(response.Status)) .Append("\r\n"); stringBuilder.Append("Content-Type: ").Append(response.ContentType).Append("\r\n"); stringBuilder.Append("Content-Length: ").Append(response.Bytes.Length.ToString(CultureInfo.InvariantCulture)).Append("\r\n"); stringBuilder.Append("Connection: close\r\n"); if (!response.Headers.ContainsKey("Cache-Control")) { stringBuilder.Append("Cache-Control: no-store\r\n"); } stringBuilder.Append("X-Content-Type-Options: nosniff\r\n"); stringBuilder.Append("X-Frame-Options: DENY\r\n"); stringBuilder.Append("Referrer-Policy: no-referrer\r\n"); stringBuilder.Append("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'\r\n"); foreach (KeyValuePair<string, string> header in response.Headers) { stringBuilder.Append(header.Key).Append(": ").Append(header.Value) .Append("\r\n"); } stringBuilder.Append("\r\n"); byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString()); stream.Write(bytes, 0, bytes.Length); stream.Write(response.Bytes, 0, response.Bytes.Length); stream.Flush(); } private static string Reason(int status) { return status switch { 200 => "OK", 303 => "See Other", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 409 => "Conflict", 413 => "Payload Too Large", 415 => "Unsupported Media Type", 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Error", }; } } public sealed class LocalRequest { public string Method { get; } public string Path { get; } public IReadOnlyDictionary<string, string> Query { get; } public IReadOnlyDictionary<string, string> Headers { get; } public string Body { get; } public LocalRequest(string method, string path, IReadOnlyDictionary<string, string> query, IReadOnlyDictionary<string, string> headers, string body) { Method = method; Path = path; Query = query; Headers = headers; Body = body; } public string Header(string name) { if (!Headers.TryGetValue(name, out string value)) { return string.Empty; } return value; } public string Cookie(string name) { string[] array = Header("Cookie").Split(new char[1] { ';' }); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && string.Equals(text.Substring(0, num).Trim(), name, StringComparison.Ordinal)) { return text.Substring(checked(num + 1)).Trim(); } } return string.Empty; } } public sealed class LocalResponse { public int Status { get; } public string ContentType { get; } public byte[] Bytes { get; } public Dictionary<string, string> Headers { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public LocalResponse(int status, string contentType, byte[] body) { Status = status; ContentType = contentType; Bytes = body ?? Array.Empty<byte>(); } public static LocalResponse Text(int status, string text) { return new LocalResponse(status, "text/plain; charset=utf-8", Encoding.UTF8.GetBytes(text ?? string.Empty)); } public static LocalResponse Json(int status, string json) { return new LocalResponse(status, "application/json; charset=utf-8", Encoding.UTF8.GetBytes(json ?? "{}")); } public static LocalResponse Html(int status, string html) { return new LocalResponse(status, "text/html; charset=utf-8", Encoding.UTF8.GetBytes(html ?? string.Empty)); } } public static class LoopbackGate { public enum Verdict { WrongHost, OtherOrigin, ChangeFromElsewhere, Opening, Locked, Through } public const string KeyCookie = "alive_key"; public const string OpeningPage = "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"; public static Verdict Check(LocalRequest request, int port, string key) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(key)) { return Verdict.Locked; } string text = port.ToString(CultureInfo.InvariantCulture); string a = request.Header("Host"); if (!string.Equals(a, "127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) && !string.Equals(a, "localhost:" + text, StringComparison.OrdinalIgnoreCase)) { return Verdict.WrongHost; } string text2 = request.Header("Origin"); bool flag = string.Equals(text2, "http://127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, "http://localhost:" + text, StringComparison.OrdinalIgnoreCase); if (text2.Length > 0 && !flag) { return Verdict.OtherOrigin; } if (!IsRead(request) && !flag) { return Verdict.ChangeFromElsewhere; } if (request.Path == "/" && request.Query.TryGetValue("key", out string value)) { if (!Same(value, key)) { return Verdict.Locked; } return Verdict.Opening; } if (!Same(request.Cookie("alive_key"), key)) { return Verdict.Locked; } return Verdict.Through; } public static bool IsRead(LocalRequest request) { if (request != null) { if (!(request.Method == "GET")) { return request.Method == "HEAD"; } return true; } return false; } public static LocalResponse Opened(string key) { LocalResponse localResponse = LocalResponse.Html(200, "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"); localResponse.Headers["Set-Cookie"] = "alive_key=" + key + "; Path=/; HttpOnly; SameSite=Strict"; return localResponse; } public static string Link(int port, string key) { return "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture) + "/?key=" + key; } public static bool Same(string? a, string b) { if (a == null || b == null || a.Length != b.Length) { return false; } int num = 0; for (int i = 0; i < a.Length; i = checked(i + 1)) { num |= a[i] ^ b[i]; } return num == 0; } } } namespace ALIVE.Core.Storage { public enum ActivityCategory { Session, Shop, Quest, Dialogue, Economy, Admin, Anticheat, Npc } public sealed class ActivityEntry { public const int MaxDetailChars = 512; public const int MaxSubjectChars = 128; public const int MaxEventChars = 64; public long AtUnixMs { get; init; } public string PlatformId { get; init; } = string.Empty; public ActivityCategory Category { get; init; } public string Event { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string SubjectSub { get; init; } = string.Empty; public string Detail { get; init; } = string.Empty; public int Outcome { get; init; } public int? PosX { get; init; } public int? PosZ { get; init; } public string Correlation { get; init; } = string.Empty; public int Severity { get; init; } } public sealed class ActivityRecord { public long ActivityId { get; } public ActivityEntry Entry { get; } public ActivityRecord(long activityId, ActivityEntry entry) { ActivityId = activityId; Entry = entry ?? throw new ArgumentNullException("entry"); } } public enum TextMatch { None, Exact, Prefix, Contains } public sealed class ActivityQuery { public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public string PlatformId { get; init; } = string.Empty; public uint Categories { get; init; } public string Text { get; init; } = string.Empty; public TextMatch Match { get; init; } public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public enum PendingOpState { Pending, Approved, Rejected, Expired, Applied } public sealed class NewPendingOp { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class PendingOpRecord { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public PendingOpState State { get; init; } public string Approver { get; init; } = string.Empty; public string DecideNote { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } public long? DecidedMs { get; init; } } public enum DecideOutcome { Ok, NotFound, AlreadyDecided, Expired, SelfApproval } public sealed class DecideResult { public DecideOutcome Outcome { get; } public PendingOpRecord? Op { get; } public DecideResult(DecideOutcome outcome, PendingOpRecord? op) { Outcome = outcome; Op = op; } } public sealed class QuestDenialRecord { public string PlatformId { get; } public string QuestId { get; } public long? UntilMs { get; } public string Reason { get; } public string Actor { get; } public long CreatedMs { get; } public QuestDenialRecord(string platformId, string questId, long? untilMs, string reason, string actor, long createdMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); QuestId = questId ?? throw new ArgumentNullException("questId"); UntilMs = untilMs; Reason = reason ?? string.Empty; Actor = actor ?? string.Empty; CreatedMs = createdMs; } public bool AppliesAt(long nowMs) { if (UntilMs.HasValue) { return UntilMs.Value > nowMs; } return true; } } public enum AuditTier { System, Super, Admin, Player } public sealed class AuditEntry { public const int MaxSnapshotChars = 4096; public DateTime AtUtc { get; init; } public string Actor { get; init; } = string.Empty; public AuditTier Tier { get; init; } public string Action { get; init; } = string.Empty; public string Permission { get; init; } = string.Empty; public bool Granted { get; init; } = true; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string Before { get; init; } = string.Empty; public string After { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public string CorrelationId { get; init; } = string.Empty; } public sealed class AuditRecord { public long AuditId { get; } public AuditEntry Entry { get; } public string RowHash { get; } public AuditRecord(long auditId, AuditEntry entry, string rowHash) { AuditId = auditId; Entry = entry ?? throw new ArgumentNullException("entry"); RowHash = rowHash ?? throw new ArgumentNullException("rowHash"); } } public sealed class AuditVerification { public bool Intact => !FirstBrokenId.HasValue; public long Rows { get; } public long? FirstBrokenId { get; } public string Detail { get; } public AuditVerification(long rows, long? firstBrokenId, string detail) { Rows = rows; FirstBrokenId = firstBrokenId; Detail = detail; } } public static class AuditHash { public static byte[] Genesis => new byte[32]; public static byte[] Compute(byte[] previous, long auditId, AuditEntry e) { if (previous == null || previous.Length != 32) { throw new ArgumentException("The previous hash must be 32 bytes.", "previous"); } if (e == null) { throw new ArgumentNullException("e"); } string[] array = new string[13] { auditId.ToString(CultureInfo.InvariantCulture), e.AtUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), e.Actor, TierName(e.Tier), e.Action, e.Permission, e.Granted ? "1" : "0", e.SubjectKind, e.SubjectId, e.Before, e.After, e.Reason, e.CorrelationId }; using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(previous, 0, 32, null, 0); string[] array2 = array; foreach (string s in array2) { byte[] bytes = Encoding.UTF8.GetBytes(s); byte[] bytes2 = BitConverter.GetBytes(checked((uint)bytes.Length)); if (!BitConverter.IsLittleEndian) { Array.Reverse((Array)bytes2); } sHA.TransformBlock(bytes2, 0, 4, null, 0); sHA.TransformBlock(bytes, 0, bytes.Length, null, 0); } sHA.TransformFinalBlock(Array.Empty<byte>(), 0, 0); return sHA.Hash; } public static string TierName(AuditTier tier) { return tier switch { AuditTier.Super => "SUPER", AuditTier.Admin => "ADMIN", AuditTier.Player => "PLAYER", _ => "SYSTEM", }; } public static bool TryParseTier(string name, out AuditTier tier) { switch (name) { case "SUPER": tier = AuditTier.Super; return true; case "ADMIN": tier = AuditTier.Admin; return true; case "SYSTEM": tier = AuditTier.System; return true; case "PLAYER": tier = AuditTier.Player; return true; default: tier = AuditTier.System; return false; } } } public sealed class SpawnerPlacementRecord { public long PlacementId { get; init; } public string SpawnerId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } public long LastSpawnMs { get; init; } public string SpotKey { get; init; } = string.Empty; } public static class CreatureSpawnKinds { public const string Hand = "hand"; public const string Spawner = "spawner"; public const string Altar = "altar"; public const string Encounter = "encounter"; } public static class CreatureStates { public const string Alive = "alive"; public const string Dead = "dead"; public const string Removed = "removed"; public const string Gone = "gone"; } public sealed class AliveCreatureRecord { public string Uid { get; init; } = string.Empty; public string CreatureId { get; init; } = string.Empty; public string SpawnKind { get; init; } = string.Empty; public long PlacementId { get; init; } public string QuestId { get; init; } = string.Empty; public string Step { get; init; } = string.Empty; public string OwnerPlatformId { get; init; } = string.Empty; public string State { get; init; } = "alive"; public long SpawnedMs { get; init; } public long LastNearMs { get; init; } public long ExpiresMs { get; init; } public double X { get; init; } public double Y { get; init; } public double Z { get; init; } } public enum GrantState { Pending = 1, Offered, Delivered, Mailbox, Stalled, Expired } public static class GrantReasons { public const byte QuestReward = 1; public const byte AdminGift = 2; public const byte Purchase = 3; public const byte Barter = 4; public const byte Withdrawal = 5; public const byte Returned = 6; public const byte Sale = 7; public const byte Effect = 8; } public sealed class GrantItem { public string Prefab { get; init; } = string.Empty; public int Count { get; init; } = 1; public int Quality { get; init; } = 1; public int Variant { get; init; } } public sealed class NewGrant { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class GrantRecord { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public GrantState State { get; init; } public int Attempts { get; init; } public long CreatedMs { get; init; } public long UpdatedMs { get; init; } public long ExpiresMs { get; init; } public string Detail { get; init; } = string.Empty; } public interface IAliveStore : IDisposable { int SchemaVersion { get; } string EngineDescription { get; } void RecordContentLoad(ContentLoadRecord record); IReadOnlyList<ContentLoadRecord> RecentContentLoads(int max); AuditRecord AppendAudit(AuditEntry entry); AuditVerification VerifyAudit(); IReadOnlyList<AuditRecord> RecentAudit(int max); PlayerRecord RecordSessionStart(string platformId, string characterName, long nowMs); void RecordSessionEnd(string platformId, long nowMs); PlayerRecord? FindPlayer(string platformId); IReadOnlyList<PlayerRecord> SearchPlayers(PlayerQuery query); long AppendActivity(ActivityEntry entry); IReadOnlyList<ActivityRecord> SearchActivity(ActivityQuery query); PostResult Post(IReadOnlyList<LedgerPosting> legs, IReadOnlyDictionary<string, LedgerBounds> bounds, IReadOnlyList<ActivityEntry> activity, long nowMs); long Balance(string platformId, string currencyId); IReadOnlyList<WalletRecord> Wallets(string platformId); (int Players, long Total) CurrencyHeld(string currencyId); IReadOnlyList<LedgerRecord> SearchLedger(LedgerQuery query); IReadOnlyList<LedgerRecord> LedgerGroup(string groupId); bool WalletReconciles(string platformId, string currencyId); ReconcileReport Reconcile(long nowMs); QuestInstanceRecord? CreateQuestInstance(NewQuestInstance instance); bool SaveJobPosting(JobPosting posting); JobPosting? LatestJobPosting(long placedId); bool MarkJobHanded(long instanceId, long morning); int JobsHandedSince(string platformId, long fromMorning); int JobsHandedOn(string platformId, long morning); IReadOnlyList<KeyValuePair<string, string>> JobTakers(long placedId, long posting); void RetireJobPostings(long placedId); void StartJobTravel(long instanceId); void SaveJobTravel(long instanceId, double countedMetres); void FreezeJobTravel(long instanceId, double countedMetres, long doneMs); JobTravelRow? JobTravel(long instanceId); IReadOnlyList<JobTravelRow> OpenJobTravel(); bool AddJobDone(string platformId, string boardKey, long nowMs); int JobsDone(string platformId, string boardKey); bool FillJobDoneOnce(IReadOnlyDictionary<long, string> boardKeyByPlacedId, long nowMs); QuestInstanceRecord? QuestInstance(long instanceId); QuestInstanceRecord? OpenQuestInstance(string platformId, string questId); IReadOnlyList<QuestInstanceRecord> SearchQuestInstances(QuestInstanceQuery query); QuestWipe WipeQuest(string platformId, string questId, string note, long nowMs); QuestInstanceRecord ApplyQuestTransition(QuestTransition transition); IReadOnlyList<QuestEventRecord> QuestEvents(long instanceId, int max); bool SetQuestClock(long instanceId, QuestClock clock); bool ClaimObjectiveEffects(string platformId, string questId, string objectiveId, long nowMs, long windowMs); NpcPlacementRecord AddPlacement(NewNpcPlacement placement); IReadOnlyList<NpcPlacementRecord> Placements(bool includeRemoved = false); NpcPlacementRecord? Placement(long placementId); void SetPlacementObject(long placementId, string zdoId, long nowMs); bool MovePlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemovePlacement(long placementId, long nowMs); SpawnerPlacementRecord AddSpawnerPlacement(string spawnerId, string label, double x, double y, double z, double rotY, string placedBy, long nowMs); IReadOnlyList<SpawnerPlacementRecord> SpawnerPlacements(); SpawnerPlacementRecord? SpawnerPlacement(long placementId); bool MoveSpawnerPlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemoveSpawnerPlacement(long placementId); int RemoveSpawnerPlacements(string spawnerId); void SetSpawnerPlacementObject(long placementId, string zdoId, long nowMs); void SetSpawnerPlacementSpawned(long placementId, long nowMs); bool SetSpawnerPlacementSpot(long placementId, string spotKey, long nowMs); void AddAliveCreature(AliveCreatureRecord creature); IReadOnlyList<AliveCreatureRecord> AliveCreatures(); AliveCreatureRecord? AliveCreature(string uid); void SeeAliveCreature(string uid, double x, double y, double z, long lastNearMs); bool RenameAliveCreature(string uid, string newUid); bool EndAliveCreature(string uid, string state, long nowMs); int PurgeEndedCreatures(long endedBeforeMs); GrantRecord AddGrant(NewGrant grant); GrantRecord? Grant(string grantId); IReadOnlyList<GrantRecord> Grants(string platformId, IReadOnlyList<GrantState> states, int limit = 200); int CountGrantsFrom(string sourceKind, string sourceIdPrefix); bool MoveGrant(string grantId, GrantState fromState, GrantState toState, long nowMs, bool countAttempt, string detail); ShopStockRecord? ShopStock(string shopId, string entryId); bool SetShopStock(ShopStockRecord stock, long? expectedRestockedMs); long ShopCredit(string platformId, string shopId); int ShopTradeCount(string platformId, ShopTradeKind kind, string refId, long sinceMs); long LastShopTradeMs(string platformId, ShopTradeKind kind, string refId); bool ApplyPlayerState(PlayerStateChange change); string? RewardRolls(string groupId); bool HasFlag(string platformId, string flagId); void AddCounters(string platformId, IReadOnlyDictionary<string, long> deltas, long atMs); IReadOnlyList<string> Flags(string platformId); IReadOnlyList<HeldFlag> FlagsHeld(string platformId); IReadOnlyList<string> ClearFlags(string platformId, IReadOnlyList<string>? flags); bool GiveFlag(string platformId, string flagId, long atMs); long SetCounter(string platformId, string counterId, long value); IReadOnlyList<KeyValuePair<string, long>> CountersOf(string platformId, string prefix, int most); IReadOnlyList<HeldName> HeldFlags(); IReadOnlyList<HeldName> HeldCounters(string prefix); int CountFlagHolders(string flagId); int CountCounterHolders(string counterId); IReadOnlyList<string> ClearFlagEverywhere(string flagId); IReadOnlyList<string> ClearCounterEverywhere(string counterId); bool DeleteServerSwitch(string switchId); int ForgetPlayerState(string platformId, IReadOnlyList<string> counters, IReadOnlyList<string> counterPrefixes, IReadOnlyList<string> flags); bool ServerSwitchOn(string switchId); IReadOnlyList<ServerSwitchRecord> ServerSwitches(); void SetServerSwitch(string switchId, bool isOn, string actor, long nowMs); IReadOnlyList<string> EditorFolders(); bool AddEditorFolder(string folder, string madeBy, long atMs); bool RemoveEditorFolder(string folder); void RenameEditorFolder(string oldFolder, string newFolder); string? PlayerVar(string platformId, string varId); void SetPlayerVar(string platformId, string varId, string value, long atMs); int CountVarHolders(string varId); IReadOnlyList<string> ClearVarEverywhere(string varId); long Counter(string platformId, string counterId); int Relationship(string platformId, string npcId); void SetRelationship(string platformId, string id, int value, long nowMs); IReadOnlyList<RelationshipRow> RelationshipsWith(string id); int CountRelationshipsWith(string id); int ForgetRelationshipsWith(string id); bool HasUnlock(string platformId, byte kind, string reference); void SetRewardChoice(long instanceId, string platformId, int choice, long atMs); int? RewardChoice(long instanceId); int ShopTradeCountSinceGameDay(string platformId, ShopTradeKind kind, string refId, long fromGameDay); ShopCommitOutcome CommitShopTrade(ShopCommit commit); IReadOnlyDictionary<string, int> SoldByItem(string platformId, SellWindow window); IReadOnlyDictionary<string, int> SoldByItemAt(string platformId, string shopId, SellWindow window); long SoldValue(string platformId, SellWindow window); long MerchantPaid(string shopId, SellWindow window); void SetShopTradeGrant(string tradeId, string grantId); IReadOnlyList<ShopTradeRecord> UngrantedShopTrades(int limit); PendingOpRecord CreatePendingOp(NewPendingOp op); PendingOpRecord? PendingOp(string opId); DecideResult DecidePendingOp(string opId, string approver, bool approve, string note, long nowMs); void MarkPendingOpApplied(string opId, long nowMs); int ExpirePendingOps(long nowMs); void SetQuestDenial(string platformId, string questId, long? untilMs, string reason, string actor, long nowMs); bool ClearQuestDenial(string platformId, string questId); QuestDenialRecord? QuestDenial(string platformId, string questId); IReadOnlyList<QuestDenialRecord> QuestDenials(string platformId); IReadOnlyList<WorldRow> WorldPlaces(); long SaveWorldPlace(long id, string key, string body, string by, long nowMs); bool RemoveWorldPlace(long id); IReadOnlyList<WorldRow> WorldLocks(); long SaveWorldLock(long id, string uid, string body, string by, long nowMs); bool RemoveWorldLock(long id); IReadOnlyList<WorldRow> WorldObjects(); long SaveWorldObject(long id, string uid, string body, string by, long nowMs); bool RemoveWorldObject(long id); IReadOnlyList<WorldRow> WorldSpots(); long SaveWorldSpot(long id, string key, string body, string by, long nowMs); bool RemoveWorldSpot(long id); void RenameWorldThings(bool objects, IReadOnlyList<KeyValuePair<long, string>> names); bool LockOpened(long lockId, string platformId); void MarkLockOpened(long lockId, string platformId, long nowMs); long PlaceSeen(long placeId, string platformId); void MarkPlaceSeen(long placeId, string platformId, long nowMs); } public sealed class ContentLoadRecord { public DateTime AtUtc { get; } public IReadOnlyList<string> Packs { get; } public IReadOnlyList<string> FailedPacks { get; } public int Published { get; } public int Quarantined { get; } public int Errors { get; } public int Warnings { get; } public string ContentHash { get; } public ContentLoadRecord(DateTime atUtc, IReadOnlyList<string> packs, IReadOnlyList<string> failedPacks, int published, int quarantined, int errors, int warnings, string contentHash) { AtUtc = atUtc; Packs = packs ?? throw new ArgumentNullException("packs"); FailedPacks = failedPacks ?? throw new ArgumentNullException("failedPacks"); Published = published; Quarantined = quarantined; Errors = errors; Warnings = warnings; ContentHash = contentHash ?? throw new ArgumentNullException("contentHash"); } } public enum LedgerReason { ShopBuy = 1, ShopSell, Barter, QuestReward, AdminGrant, Decay, Refund, Reconcile, StartingBalance, Deposit, Withdrawal, Penalty, Effect } public enum LedgerSourceKind { None, Shop, Quest, TradeRecipe, Admin, System, Bank } public sealed class LedgerPosting { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long DeltaMinor { get; init; } public LedgerReason Reason { get; init; } public LedgerSourceKind SourceKind { get; init; } public string SourceId { get; init; } = string.Empty; public string SourceSub { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Note { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; } public sealed class LedgerRecord { public long TxnId { get; } public LedgerPosting Posting { get; } public long BalanceAfterMinor { get; } public long AtUnixMs { get; } public LedgerRecord(long txnId, LedgerPosting posting, long balanceAfterMinor, long atUnixMs) { TxnId = txnId; Posting = posting ?? throw new ArgumentNullException("posting"); BalanceAfterMinor = balanceAfterMinor; AtUnixMs = atUnixMs; } } public sealed class WalletRecord { public string PlatformId { get; } public string CurrencyId { get; } public long BalanceMinor { get; } public long LifetimeInMinor { get; } public long LifetimeOutMinor { get; } public long UpdatedMs { get; } public WalletRecord(string platformId, string currencyId, long balanceMinor, long lifetimeInMinor, long lifetimeOutMinor, long updatedMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); BalanceMinor = balanceMinor; LifetimeInMinor = lifetimeInMinor; LifetimeOutMinor = lifetimeOutMinor; UpdatedMs = updatedMs; } } public sealed class LedgerBounds { public long MinMinor { get; } public long MaxMinor { get; } public LedgerBounds(long minMinor, long maxMinor) { if (maxMinor < minMinor) { throw new ArgumentOutOfRangeException("maxMinor", maxMinor, "The ceiling is below the floor."); } MinMinor = minMinor; MaxMinor = maxMinor; } } public enum PostOutcome { Posted, AlreadyPosted, BelowFloor, AboveCeiling, UnknownPlayer, UnknownCurrency } public sealed class PostResult { public PostOutcome Outcome { get; } public bool Accepted { get { if (Outcome != PostOutcome.Posted) { return Outcome == PostOutcome.AlreadyPosted; } return true; } } public IReadOnlyList<LedgerRecord> Legs { get; } public string Detail { get; } public PostResult(PostOutcome outcome, IReadOnlyList<LedgerRecord> legs, string detail) { Outcome = outcome; Legs = legs ?? throw new ArgumentNullException("legs"); Detail = detail ?? string.Empty; } } public sealed class LedgerQuery { public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public sealed class WalletDiscrepancy { public string PlatformId { get; } public string CurrencyId { get; } public long WalletMinor { get; } public long LedgerMinor { get; } public WalletDiscrepancy(string platformId, string currencyId, long walletMinor, long ledgerMinor) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); WalletMinor = walletMinor; LedgerMinor = ledgerMinor; } } public sealed class ReconcileReport { public int WalletsChecked { get; } public IReadOnlyList<WalletDiscrepancy> Repaired { get; } public bool Balanced => Repaired.Count == 0; public ReconcileReport(int walletsChecked, IReadOnlyList<WalletDiscrepancy> repaired) { WalletsChecked = walletsChecked; Repaired = repaired ?? throw new ArgumentNullException("repaired"); } } public sealed class NewNpcPlacement { public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } } public sealed class NpcPlacementRecord { public long PlacementId { get; init; } public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } } public sealed class PlayerRecord { public long PlayerId { get; } public string PlatformId { get; } public string CharacterName { get; } public long FirstSeenMs { get; } public long LastSeenMs { get; } public long SessionCount { get; } public PlayerRecord(long playerId, string platformId, string characterName, long firstSeenMs, long lastSeenMs, long sessionCount) { PlayerId = playerId; PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CharacterName = characterName ?? throw new ArgumentNullException("characterName"); FirstSeenMs = firstSeenMs; LastSeenMs = lastSeenMs; SessionCount = sessionCount; } } public enum PlayerQueryKind { PlatformId = 1, NamePrefix } public sealed class PlayerQuery { public PlayerQueryKind Kind { get; init; } = PlayerQueryKind.NamePrefix; public string Text { get; init; } = string.Empty; public string AlternateText { get; init; } = string.Empty; public string? AfterName { get; init; } public string AfterPlatformId { get; init; } = string.Empty; public int Limit { get; init; } = 50; } public static class UnlockKinds { public const byte Quest = 1; public const byte ShopEntry = 2; } public sealed class RelationshipRow { public string PlatformId { get; init; } = string.Empty; public int Value { get; init; } public long ChangedMs { get; init; } } public sealed class PlayerStateChange { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public IReadOnlyList<string> Flags { get; init; } = Array.Empty<string>(); public IReadOnlyList<string> ClearFlags { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, long> Counters { get; init; } = new Dictionary<string, long>(); public IReadOnlyDictionary<string, long> Relationships { get; init; } = new Dictionary<string, long>(); public IReadOnlyList<KeyValuePair<byte, string>> Unlocks { get; init; } = Array.Empty<KeyValuePair<byte, string>>(); public string Rolls { get; init; } = string.Empty; public long AtMs { get; init; } } public static class GrantPrefixes { public const string Skill = "@skill:"; public const string PovTree = "@pov:tree:"; public const string PovProfession = "@pov:prof:"; public static bool IsSkill(string? prefab) { return prefab?.StartsWith("@skill:", StringComparison.Ordinal) ?? false; } public static bool IsPov(string? prefab) { if (prefab != null) { if (!prefab.StartsWith("@pov:tree:", StringComparison.Ordinal)) { return prefab.StartsWith("@pov:prof:", StringComparison.Ordinal); } return true; } return false; } public static bool IsNotItem(string? prefab) { if (!IsSkill(prefab)) { return IsPov(prefab); } return true; } } public enum QuestState { NotOffered, Offered, Active, ReadyToTurnIn, Completed, Failed, Abandoned, Paused, Cooldown, Stale } public enum QuestEventKind { Offered, Accepted, Progress, ObjectiveDone, Ready, Completed, Failed, Abandoned, Paused, Resumed, Stale, Migrated, AdminAdjusted } public enum MigrationPolicy { Snapshot, FollowLive } public sealed class ObjectiveProgress { public string ObjectiveId { get; init; } = string.Empty; public long Current { get; init; } public long Required { get; init; } public long? CompletedMs { get; init; } public bool Optional { get; init; } public int OrderIndex { get; init; } public bool Revealed { get; init; } = true; public bool IsDone => CompletedMs.HasValue; } public static class QuestClockDomains { public const string None = ""; public const string Online = "online"; public const string Real = "real"; public const string World = "world"; } public static class QuestHolds { public const string None = ""; public const string Deadline = "deadline"; public const string Window = "window"; public const string Manual = "manual"; } public sealed class QuestClock { public static QuestClock Empty { get; } = new QuestClock(); public string Domain { get; init; } = ""; public long? DeadlineMs { get; init; } public long? LeftMs { get; init; } public long? WorldDeadlineS { get; init; } public string OnDeadline { get; init; } = string.Empty; public long GraceMs { get; init; } public long BudgetMs { get; init; } public string Hold { get; init; } = ""; public bool HasDeadline => Domain.Length > 0; public bool Running { get { if (!DeadlineMs.HasValue) { return WorldDeadlineS.HasValue; } return true; } } public QuestClock With(long? deadlineMs, long? leftMs, long? worldDeadlineS, string hold) { return new QuestClock { Domain = Domain, DeadlineMs = deadlineMs, LeftMs = leftMs, WorldDeadlineS = worldDeadlineS, OnDeadline = OnDeadline, GraceMs = GraceMs, BudgetMs = BudgetMs, Hold = (hold ?? "") }; } } public sealed class NewQuestInstance { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } = QuestState.Offered; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public QuestClock? Clock { get; init; } public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } } public sealed class JobTake { public string Board { get; init; } = string.Empty; public long PlacedId { get; init; } public long Posting { get; init; } public string BoardNpc { get; init; } = string.Empty; public string HandIn { get; init; } = string.Empty; public long? HandedMorning { get; init; } public string Rolled { get; init; } = string.Empty; } public sealed class JobPosting { public const long NeverDue = long.MinValue; public long PlacedId { get; init; } public long Number { get; init; } public long Due { get; init; } public long PostedMs { get; init; } public IReadOnlyList<string> Notices { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, string> Rolls { get; init; } = new Dictionary<string, string>(StringComparer.Ordinal); } public sealed class JobTravelRow { public long InstanceId { get; init; } public double CountedMetres { get; init; } public long? DoneMs { get; init; } } public sealed class QuestInstanceRecord { public long InstanceId { get; init; } public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } public int Attempt { get; init; } = 1; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long? OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? LastProgressMs { get; init; } public long? CooldownUntilMs { get; init; } public bool Tracked { get; init; } = true; public string RewardGroupId { get; init; } = string.Empty; public string StaleReason { get; init; } = string.Empty; public QuestClock Clock { get; init; } = QuestClock.Empty; public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } public bool IsOpen => QuestStates.IsOpen(State); } public sealed class QuestEventRecord { public long EventId { get; } public long InstanceId { get; } public QuestEventKind Kind { get; } public string Detail { get; } public string Actor { get; } public string Correlation { get; } public long AtUnixMs { get; } public QuestEventRecord(long eventId, long instanceId, QuestEventKind kind, string detail, string actor, string correlation, long atUnixMs) { EventId = eventId; InstanceId = instanceId; Kind = kind; Detail = detail ?? string.Empty; Actor = actor ?? string.Empty; Correlation = correlation ?? string.Empty; AtUnixMs = atUnixMs; } } public sealed class QuestTransition { public long InstanceId { get; init; } public QuestState State { get; init; } public QuestEventKind Kind { get; init; } public string Detail { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; public long AtUnixMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? CooldownUntilMs { get; init; } public string? RewardGroupId { get; init; } public string? StaleReason { get; init; } public bool ClearTimestamps { get; init; } public IReadOnlyDictionary<string, long>? Progress { get; init; } public IReadOnlyCollection<string>? Reveal { get; init; } public QuestClock? Clock { get; init; } public bool ClearCooldown { get; init; } } public sealed class QuestInstanceQuery { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public IReadOnlyList<QuestState> States { get; init; } = Array.Empty<QuestState>(); public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public static class QuestStates { public static bool IsOpen(QuestState state) { if (state != QuestState.Offered && state != QuestState.Active && state != QuestState.ReadyToTurnIn && state != QuestState.Paused) { return state == QuestState.Stale; } return true; } public static bool IsTerminal(QuestState state) { if (state != QuestState.Completed && state != QuestState.Failed && state != QuestState.Abandoned) { return state == QuestState.Cooldown; } return true; } public static string Name(QuestState state) { return state switch { QuestState.Offered => "offered", QuestState.Active => "active", QuestState.ReadyToTurnIn => "ready_to_turn_in", QuestState.Completed => "completed", QuestState.Failed => "failed", QuestState.Abandoned => "abandoned", QuestState.Paused => "paused", QuestState.Cooldown => "cooldown", QuestState.Stale => "stale", _ => throw new ArgumentOutOfRangeException("state", state, "NOT_OFFERED is the absence of a row and is never stored."), }; } public static QuestState Parse(string name) { return name switch { "offered" => QuestState.Offered, "active" => QuestState.Active, "ready_to_turn_in" => QuestState.ReadyToTurnIn, "completed" => QuestState.Completed, "failed" => QuestState.Failed, "abandoned" => QuestState.Abandoned, "paused" => QuestState.Paused, "cooldown" => QuestState.Cooldown, "stale" => QuestState.Stale, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest state."), }; } public static string EventName(QuestEventKind kind) { return kind switch { QuestEventKind.Offered => "offered", QuestEventKind.Accepted => "accepted", QuestEventKind.Progress => "progress", QuestEventKind.ObjectiveDone => "objective_done", QuestEventKind.Ready => "ready", QuestEventKind.Completed => "completed", QuestEventKind.Failed => "failed", QuestEventKind.Abandoned => "abandoned", QuestEventKind.Paused => "paused", QuestEventKind.Resumed => "resumed", QuestEventKind.Stale => "stale", QuestEventKind.Migrated => "migrated", QuestEventKind.AdminAdjusted => "admin_adjusted", _ => throw new ArgumentOutOfRangeException("kind", kind, "Unknown quest event kind."), }; } public static QuestEventKind ParseEvent(string name) { return name switch { "offered" => QuestEventKind.Offered, "accepted" => QuestEventKind.Accepted, "progress" => QuestEventKind.Progress, "objective_done" => QuestEventKind.ObjectiveDone, "ready" => QuestEventKind.Ready, "completed" => QuestEventKind.Completed, "failed" => QuestEventKind.Failed, "abandoned" => QuestEventKind.Abandoned, "paused" => QuestEventKind.Paused, "resumed" => QuestEventKind.Resumed, "stale" => QuestEventKind.Stale, "migrated" => QuestEventKind.Migrated, "admin_adjusted" => QuestEventKind.AdminAdjusted, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest event kind."), }; } } public enum ShopTradeKind { Buy = 1, Barter, Sell } public sealed class ShopStockRecord { public string ShopId { get; init; } = string.Empty; public string EntryId { get; init; } = string.Empty; public int Qty { get; init; } public long RestockedMs { get; init; } } public sealed class ShopTradePart { public byte Kind { get; init; } public string Id { get; init; } = string.Empty; public long Amount { get; init; } } public sealed class ShopTradeRecord { public const string NoGrant = "-"; public string TradeId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string ShopId { get; init; } = string.Empty; public string NpcId { get; init; } = string.Empty; public ShopTradeKind Kind { get; init; } public string RefId { get; init; } = string.Empty; public int Qty { get; init; } public IReadOnlyList<ShopTradePart> Paid { get; init; } = Array.Empty<ShopTradePart>(); public IReadOnlyList<ShopTradePart> Got { get; init; } = Array.Empty<ShopTradePart>(); public long CreditBefore { get; init; } public long CreditAfter { get; init; } public string GrantId { get; init; } = string.Empty; public long GameDay { get; init; } = -1L; public long ValueVu { get; init; } public long AtMs { get; init; } } public enum ShopCommitOutcome { Committed = 1, OutOfStock, CreditChanged } public sealed class ShopCommit { public ShopTradeRecord Trade { get; init; } = new ShopTradeRecord(); public int StockTake { get; init; } public string StockEntryId { get; init; } = string.Empty; public long CreditExpected { get; init; } public IReadOnlyList<ActivityEntry> Activity { get; init; } = Array.Empty<ActivityEntry>(); } public sealed class SellWindow { public long SinceMs { get; init; } public long FromGameDay { get; init; } = -1L; } public sealed class ServerSwitchRecord { public string SwitchId { get; init; } = string.Empty; public bool On { get; init; } public long ChangedMs { get; init; } public string ChangedBy { get; init; } = string.Empty; } public sealed class HeldName { public string Name { get; init; } = string.Empty; public int Holders { get; init; } } public sealed class HeldFlag { public string FlagId { get; init; } = string.Empty; public long SetMs { get; init; } } public sealed class QuestWipe { public IReadOnlyList<long> Instances { get; init; } = Array.Empty<long>(); public int Events { get; init; } public int GrantsClosed { get; init; } } public sealed class WorldRow { public long Id { get; init; } public string Key { get; init; } = string.Empty; public string Body { get; init; } = string.Empty; public string UpdatedBy { get; init; } = string.Empty; public long UpdatedMs { get; init; } } } namespace ALIVE.Core.Protocol { public static class AliveProtocol { public const ushort ProtoVersion = 1; public const byte EnvelopeVersion = 1; public const ushort Magic = 42782; public const int MaxFrameBytes = 8192; public const int MaxPayloadBytes = 4194304; public const int MaxPayloadBytesC2S = 262144; public const int MaxChunks = 64; public const int MaxChunksC2S = 8; public const int CompressMinBytes = 512; public const int MaxStringBytes = 4096; public const int MaxCollectionSize = 1024; public const string RpcChannelServer = "ALIVE.s2c"; public const string RpcChannelPlayer = "ALIVE.c2s.player"; public const string RpcChannelAdmin = "ALIVE.c2s.admin"; } public static class AttestationDigest { public const byte SpecNonceThenFile = 1; public static ByteString Response(ByteString serverNonce, byte[] fileBytes) { if (serverNonce == null) { throw new ArgumentNullException("serverNonce"); } if (fileBytes == null) { throw new ArgumentNullException("fileBytes"); } using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(serverNonce.Raw, 0, serverNonce.Length, null, 0); sHA.TransformFinalBlock(fileBytes, 0, fileBytes.Length); return ByteString.Own(sHA.Hash); } public static ByteString Combined(IReadOnlyList<ByteString> responses) { if (responses == null) { throw new ArgumentNullException("responses"); } WireWriter wireWriter = new WireWriter(); foreach (ByteString response in responses) { wireWriter.WriteRaw(response); } return Sha256(wireWriter.ToArray()); } public static ByteString PluginSet(IReadOnlyList<PluginReport> plugins) { if (plugins == null) { throw new ArgumentNullException("plugins"); } WireWriter wireWriter = new WireWriter(); foreach (PluginReport plugin in plugins) { wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.PluginId))); wireWriter.WriteU8(0); wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.Version))); wireWriter.WriteU8(0); wireWriter.WriteRaw(plugin.FileHash); } return Sha256(wireWriter.ToArray()); } private static ByteString Sha256(byte[] data) { using SHA256 sHA = SHA256.Create(); return ByteString.Own(sHA.ComputeHash(data)); } } public sealed class ByteString : IEquatable<ByteString> { private readonly byte[] _bytes; public static ByteString Empty { get; } = new ByteString(Array.Empty<byte>()); public int Length => _bytes.Length; public byte this[int index] => _bytes[index]; public bool IsAllZero { get { byte[] bytes = _bytes; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] != 0) { return false; } } return true; } } internal byte[] Raw => _bytes; private ByteString(byte[] owned) { _bytes = owned; } public static ByteString CopyFrom(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (bytes.Length != 0) { return new ByteString((byte[])bytes.Clone()); } return Empty; } public static ByteString CopyFrom(byte[] bytes, int offset, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || count < 0 || offset > checked(bytes.Length - count)) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return Empty; } byte[] array = new byte[count]; Buffer.BlockCopy(bytes, offset, array, 0, count); return new ByteString(array); } public static ByteString Zeros(int length) { if (length != 0) { return new ByteString(new byte[length]); } return Empty; } internal static ByteString Own(byte[] bytes) { if (bytes.Length != 0) { return new ByteString(bytes); } return Empty; } public byte[] ToArray() { return (byte[])_bytes.Clone(); } public bool FixedTimeEquals(ByteString? other) { if (other == null || other._bytes.Length != _bytes.Length) { return false; } int num = 0; for (int i = 0; i < _bytes.Length; i = checked(i + 1)) { num |= _bytes[i] ^ other._bytes[i]; } return num == 0; } internal void CopyTo(byte[] destination, int offset) { Buffer.BlockCopy(_bytes, 0, destination, offset, _bytes.Length); } public bool Equals(ByteString? other) { return FixedTimeEquals(other); } public override bool Equals(object? obj) { if (obj is ByteString other) { return FixedTimeEquals(other); } return false; } public override int GetHashCode() { int num = -2128831035; byte[] bytes = _bytes; foreach (byte b in bytes) { num = (num ^ b) * 16777619; } return num; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(checked(_bytes.Length * 2)); byte[] bytes = _bytes; foreach (byte b in bytes) { stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } public static class Crc32C { private const uint Polynomial = 2197175160u; private static readonly uint[] Table = BuildTable(); public static uint Compute(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } checked { if (offset < 0 || count < 0 || offset > data.Length - count) { throw new ArgumentOutOfRangeException("count"); } uint num = uint.MaxValue; int num2 = offset + count; for (int i = offset; i < num2; i++) { num = Table[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return ~num; } } private static uint[] BuildTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0x82F63B78u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } public enum DecodeOutcome { Complete, Pending, Dropped, Rejected } public sealed class DecodeResult { public DecodeOutcome Outcome { get; } public ErrorCode Error { get; } public bool HardSignal { get; } public string Detail { get; } public FrameHeader? Header { get; } public ByteString? Payload { get; } private DecodeResult(DecodeOutcome outcome, ErrorCode error, bool hardSignal, string detail, FrameHeader? header, ByteString? payload) { Outcome = outcome; Error = error; HardSignal = hardSignal; Detail = detail; Header = header; Payload = payload; } internal static DecodeResult Complete(FrameHeader header, ByteString payload) { return new DecodeResult(DecodeOutcome.Complete, ErrorCode.None, hardSignal: false, string.Empty, header, payload); } internal static DecodeResult Pending() { return new DecodeResult(DecodeOutcome.Pending, ErrorCode.None, hardSignal: false, string.Empty, null, null); } internal static DecodeResult Dropped(string detail) { return new DecodeResult(DecodeOutcome.Dropped, ErrorCode.None, hardSignal: false, detail, null, null); } internal static DecodeResult Reject(ErrorCode error, bool hard, string detail) { return new DecodeResult(DecodeOutcome.Rejected, error, hard, detail, null, null); } } public static class Envelope { public const int HeaderBytes = 44; public const int ChunkHeaderBytes = 12; public const int CrcBytes = 4; public const int IdemKeyBytes = 16; public const byte FlagCompressed = 1; public const byte FlagChunk = 2; public const byte FlagAdmin = 4; public const byte ReservedFlags = 248; public static int SingleBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 4); } public static int ChunkBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 12 - 4); } } public enum ErrorCode { None = 0, Malformed = 1000, UnsupportedEnvVersion = 1001, ReservedBitsSet = 1002, TrailingBytes = 1003, WrongDirection = 1004, UnknownMsgType = 1005, SizeLimit = 1006, SenderIdMismatch = 1007, BadCrc = 1008, UnsupportedMsgVersion = 1009, NoSession = 2001, NotReady = 2002, SessionExpired = 2003, SessionMismatch = 2004, ProtoVersionMismatch = 2101, AttestationFailed = 2102, DualClientDetected = 2103, PluginPolicyDenied = 2104, AttestTimeout = 2105, SyncTimeout = 2106, ClientRequired = 2107, Banned = 2108, ServerFullAlive = 2109, ClientVersionMismatch = 2110, FieldInvalid = 3001, NotFound = 3002, QtyOutOfRange = 3003, ItemNotAllowed = 3004, StringTooLong = 3011, ContentSchemaInvalid = 3006, ContentBoundsExceeded = 3007, CollectionTooLarge = 3012, CharsetViolation = 3013, IdempotencyConflict = 3009, IdempotencyMissing = 3010, NotAuthorized = 4001, NotOwner = 4002, NotOffered = 4003, OutOfRange = 4005, OptionNotOffered = 4009, DualControlRequired = 4011, SuperAdminRequired = 4012, SelfApprovalForbidden = 4013, ShopClosed = 5001, StaleVersion = 5002, PriceChanged = 5003, OutOfStock = 5004, InsufficientFunds = 5005, ObjectivesIncomplete = 5006, NotActive = 5010, AlreadyCompleted = 5011, InstanceNotFound = 5016, NothingToRevoke = 5017, ApprovalExpired = 5020, LimitReached = 5021, RateLimited = 6001, BurstLimited = 6002, MemoryBudget = 6004, Internal = 7001 } public static class FieldRules { public static bool IsVersion(string? value) { if (value == null || value.Length == 0 || value.Length > 32) { return false; } int i = 0; int num = 0; checked { while (true) { int num2 = i; for (; i < value.Length && value[i] >= '0' && value[i] <= '9'; i++) { } int num3 = i - num2; if (num3 < 1 || num3 > 5) { return false; } num++; if (i == value.Length) { return num <= 4; } if (value[i] != '.' || num >= 4) { break; } i++; } if (value[i] != '-') { return false; } int num4 = value.Length - i - 1; if (num4 < 1 || num4 > 16) { return false; } for (int j = i + 1; j < value.Length; j++) { char c = value[j]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.') { return false; } } return true; } } public static bool IsPluginId(string? value) { return IsToken(value, 128, allowUpper: true, leadingUnderscore: true); } public static bool IsIdentifier(string? value) { return IsToken(value, 64, allowUpper: false); } public static bool IsBuildId(string? value) { if (value != null) { if (value.Length != 0) { return IsToken(value, 40, allowUpper: true); } return true; } return false; } private static bool IsToken(string? value, int max, bool allowUpper, bool leadingUnderscore = false) { if (value == null || value.Length == 0 || value.Length > max) { return false; } for (int i = 0; i < value.Length; i = checked(i + 1)) { char c = value[i]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && (!allowUpper || c < 'A' || c > 'Z') && (i <= 0 || (c != '.' && c != '_' && c != '-')) && (!(i == 0 && leadingUnderscore) || c != '_')) { return false; } } return true; } } public sealed class Frame { public FrameHeader Header { get; } public bool Compressed { get; } public int PayloadLength { get; } public ChunkInfo? Chunk { get; } public ByteString Body { get; } internal Frame(FrameHeader header, bool compressed, int payloadLength, ChunkInfo? chunk, ByteString body) { Header = header; Compressed = compressed; PayloadLength = payloadLength; Chunk = chunk; Body = body; } } public sealed class ChunkInfo { public uint ChunkId { get; } public int Index { get; } public int Count { get; } public int TotalLength { get; } internal ChunkInfo(uint chunkId, int index, int count, int totalLength) { ChunkId = chunkId; Index = index; Count = count; TotalLength = totalLength; } } public static class FrameCodec { public static IReadOnlyList<byte[]> Encode(FrameHeader header, ByteString payload, FrameLimits limits, uint chunkId) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (limits == null) { throw new ArgumentNullException("limits"); } if (header.IdemKey == null || header.IdemKey.Length != 16) { throw new ArgumentException("The idempotency key must be 16 bytes.", "header"); } if (payload.Length > limits.MaxPayloadBytes) { throw new ArgumentOutOfRangeException("payload", "Payload of " + payload.Length + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } bool flag = false; byte[] array = payload.Raw; if (payload.Length >= 512) { byte[] array2 = Deflate(array); if (array2.Length < array.Length) { array = array2; flag = true; } } byte b = checked((byte)((flag ? 1 : 0) | (header.Admin ? 4 : 0))); if (array.Length <= Envelope.SingleBodyLimit(limits.MaxFrameBytes)) { return new byte[1][] { Build(header, b, payload.Length, null, array, 0, array.Length) }; } int num = Envelope.ChunkBodyLimit(limits.MaxFrameBytes); int num2 = checked(array.Length + num - 1) / num; if (num2 > limits.MaxChunks) { throw new ArgumentOutOfRangeException("payload", "Payload needs " + num2 + " chunks; the limit is " + limits.MaxChunks + "."); } byte[][] array3 = new byte[num2][]; checked { for (int i = 0; i < num2; i++) { int num3 = i * num; int length = Math.Min(num, array.Length - num3); array3[i] = Build(header, (byte)(b | 2), payload.Length, new ChunkInfo(chunkId, i, num2, array.Length), array, num3, length); } return array3; } } public static bool TryDecode(byte[]? frame, FrameLimits limits, [NotNullWhen(true)] out Frame? decoded, [NotNullWhen(false)] out DecodeResult? failure) { decoded = null; failure = Check(frame, limits); if (failure != null) { return false; } Frame decoded2; DecodeResult decodeResult = Parse(frame, limits, out decoded2); if (decodeResult != null || decoded2 == null) { failure = decodeResult ?? DecodeResult.Reject(ErrorCode.Malformed, hard: true, "The envelope could not be read."); return false; } decoded = decoded2; failure = null; return true; } private static DecodeResult? Check(byte[]? frame, FrameLimits limits) { if (limits == null) { throw new ArgumentNullException("limits"); } if (frame == null || frame.Length < 2) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame is too short to hold an envelope."); } if ((frame[0] | (frame[1] << 8)) != 42782) { return DecodeResult.Dropped("Not an ALIVE frame (magic mismatch)."); } if (frame.Length < 48) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame of " + frame.Length + " bytes is shorter than an envelope."); } if (frame.Length > limits.MaxFrameBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Frame of " + frame.Length + " bytes exceeds the limit of " + limits.MaxFrameBytes + "."); } int num = checked(frame.Length - 4); WireReader wireReader = new WireReader(frame, num, 4); if (wireReader.ReadU32() != Crc32C.Compute(frame, 0, num)) { return DecodeResult.Reject(ErrorCode.BadCrc, hard: false, "CRC mismatch: the frame was corrupted or truncated."); } return null; } private static DecodeResult? Parse(byte[] frame, FrameLimits limits, out Frame? decoded) { decoded = null; checked { int num = frame.Length - 4; try { WireReader wireReader = new WireReader(frame, 2, num - 2); byte b = wireReader.ReadU8(); if (b != 1) { return DecodeResult.Reject(ErrorCode.UnsupportedEnvVersion, hard: false, "Envelope version " + b + " is not supported."); } byte b2 = wireReader.ReadU8(); if ((b2 & 0xF8) != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "Reserved flag bits were set."); } ushort msgType = wireReader.ReadU16(); byte msgVersion = wireReader.ReadU8(); if (wireReader.ReadU8() != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "The reserved header byte was not zero."); } uint seq = wireReader.ReadU32(); uint ackSeq = wireReader.ReadU32(); ulong sessionId = wireReader.ReadU64(); ByteString idemKey = wireReader.ReadFixed(16); uint num2 = wireReader.ReadU32(); if (num2 > (uint)limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Declared payload of " + num2 + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } ChunkInfo chunk = null; if ((b2 & 2) != 0) { uint chunkId = wireReader.ReadU32(); ushort num3 = wireReader.ReadU16(); ushort num4 = wireReader.ReadU16(); uint num5 = wireReader.ReadU32(); if (num4 == 0 || num4 > limits.MaxChunks) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunk count " + num4 + " is outside 1-" + limits.MaxChunks + "."); } if (num3 >= num4) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk index " + num3 + " is not below the count " + num4 + "."); } if (num5 == 0 || num5 > limits.MaxChunkedBodyBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked body of " + num5 + " bytes is outside the limit."); } if (wireReader.Remaining == 0) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk frame carried no bytes."); } chunk = new ChunkInfo(chunkId, num3, num4, (int)num5); } FrameHeader header = new FrameHeader { Admin = ((b2 & 4) != 0), MsgType = msgType, MsgVersion = msgVersion, Seq = seq, AckSeq = ackSeq, SessionId = sessionId, IdemKey = idemKey }; decoded = new Frame(header, (b2 & 1) != 0, (int)num2, chunk, wireReader.ReadRest()); return null; } catch (WireException ex) { return DecodeResult.Reject(ex.Code, hard: true, ex.Message); } } } public static DecodeResult DecodeSingle(byte[]? frame, FrameLimits limits) { if (!TryDecode(frame, limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk arrived where a single frame was required."); } return Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } internal static DecodeResult Open(FrameHeader header, byte[] body, bool compressed, int payloadLength) { if (!compressed) { if (body.Length != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Payload is " + body.Length + " bytes but declared " + payloadLength + "."); } return DecodeResult.Complete(header, ByteString.Own(body)); } checked { try { byte[] array = new byte[payloadLength]; using (MemoryStream stream = new MemoryStream(body, writable: false)) { using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); int i; int num; for (i = 0; i < payloadLength; i += num) { num = deflateStream.Read(array, i, payloadLength - i); if (num == 0) { break; } } if (i != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflated to " + i + " bytes but declared " + payloadLength + "."); } byte[] buffer = new byte[1]; if (deflateStream.Read(buffer, 0, 1) != 0) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflates beyond its declared " + payloadLength + " bytes."); } } return DecodeResult.Complete(header, ByteString.Own(array)); } catch (Exception ex) when (ex is InvalidDataException || ex is IOException || ex is NotSupportedException) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Compressed payload is not valid deflate: " + ex.Message); } } } private static byte[] Deflate(byte[] data) { using MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) { deflateStream.Write(data, 0, data.Length); } return memoryStream.ToArray(); } private static byte[] Build(FrameHeader h, byte flags, int payloadLength, ChunkInfo? chunk, byte[] body, int offset, int length) { checked { WireWriter wireWriter = new WireWriter(56 + length + 4); wireWriter.WriteU16(42782); wireWriter.WriteU8(1); wireWriter.WriteU8(flags); wireWriter.WriteU16(h.MsgType); wireWriter.WriteU8(h.MsgVersion); wireWriter.WriteU8(0); wireWriter.WriteU32(h.Seq); wireWriter.WriteU32(h.AckSeq); wireWriter.WriteU64(h.SessionId); wireWriter.WriteFixed(h.IdemKey, 16); wireWriter.WriteU32((uint)payloadLength); if (chunk != null) { wireWriter.WriteU32(chunk.ChunkId); wireWriter.WriteU16((ushort)chunk.Index); wireWriter.WriteU16((ushort)chunk.Count); wireWriter.WriteU32((uint)chunk.TotalLength); } wireWriter.WriteRaw(ByteString.CopyFrom(body, offset, length)); byte[] array = wireWriter.ToArray(); wireWriter.WriteU32(Crc32C.Compute(array, 0, array.Length)); return wireWriter.ToArray(); } } } public sealed class FrameHeader { public bool Admin { get; init; } public ushort MsgType { get; init; } public byte MsgVersion { get; init; } = 1; public uint Seq { get; init; } public uint AckSeq { get; init; } public ulong SessionId { get; init; } public ByteString IdemKey { get; init; } = ByteString.Zeros(16); public bool SameAs(FrameHeader other) { if (other != null && Admin == other.Admin && MsgType == other.MsgType && MsgVersion == other.MsgVersion && Seq == other.Seq && AckSeq == other.AckSeq && SessionId == other.SessionId) { return IdemKey.FixedTimeEquals(other.IdemKey); } return false; } } public sealed class FrameLimits { public static FrameLimits ServerToClient { get; } = new FrameLimits(8192, 4194304, 64); public static FrameLimits ClientToServer { get; } = new FrameLimits(8192, 262144, 8); public int MaxFrameBytes { get; } public int MaxPayloadBytes { get; } public int MaxChunks { get; } public long MaxChunkedBodyBytes { get { checked { return unchecked((long)MaxChunks) * unchecked((long)Envelope.ChunkBodyLimit(MaxFrameBytes)); } } } public FrameLimits(int maxFrameBytes, int maxPayloadBytes, int maxChunks) { if (maxFrameBytes < 1024) { throw new ArgumentOutOfRangeException("maxFrameBytes", "The protocol needs frames of at least 1 KiB."); } if (maxPayloadBytes < 1) { throw new ArgumentOutOfRangeException("maxPayloadBytes"); } if (maxChunks < 1 || maxChunks > 65535) { throw new ArgumentOutOfRangeException("maxChunks"); } MaxFrameBytes = maxFrameBytes; MaxPayloadBytes = maxPayloadBytes; MaxChunks = maxChunks; } } public sealed class FrameReceiver { private readonly FrameLimits _limits; public Reassembler Chunks { get; } public FrameReceiver(FrameLimits limits) { _limits = limits ?? throw new ArgumentNullException("limits"); Chunks = new Reassembler(limits, 4, 30000L, 8388608L); } public DecodeResult Receive(byte[]? frame, long nowMs) { if (!FrameCodec.TryDecode(frame, _limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return Chunks.Accept(decoded, nowMs); } return FrameCodec.Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } } public sealed class Reassembler { private sealed class Pending { internal Frame First { get; } internal long StartedMs { get; } internal long Order { get; } internal ByteString?[] Parts { get; } internal int Received { get; set; } internal int Bytes { get; set; } internal Pending(Frame first, long startedMs, long order) { First = first; StartedMs = startedMs; Order = order; Parts = new ByteString[first.Chunk.Count]; } internal bool Matches(Frame f) { ChunkInfo chunk = First.Chunk; ChunkInfo chunk2 = f.Chunk; if (chunk.Count == chunk2.Count && chunk.TotalLength == chunk2.TotalLength && First.Compressed == f.Compressed && First.PayloadLength == f.PayloadLength) { return First.Header.SameAs(f.Header); } return false; } } public const int DefaultMaxConcurrent = 4; public const long DefaultTtlMs = 30000L; public const long DefaultMemoryBudget = 8388608L; private readonly FrameLimits _limits; private readonly int _maxConcurrent; private readonly long _ttlMs; private readonly long _memoryBudget; private readonly Dictionary<uint, Pending> _pending = new Dictionary<uint, Pending>(); private long _order; public int PendingCount => _pending.Count; public long BufferedBytes { get; private set; } public int Evictions { get; private set; } public int Expirations { get; private set; } public Reassembler(FrameLimits limits, int maxConcurrent = 4, long ttlMs = 30000L, long memoryBudget = 8388608L) { _limits = limits ?? throw new ArgumentNullException("limits"); if (maxConcurrent < 1) { throw new ArgumentOutOfRangeException("maxConcurrent"); } if (ttlMs < 1) { throw new ArgumentOutOfRangeException("ttlMs"); } if (memoryBudget < 1) { throw new ArgumentOutOfRangeException("memoryBudget"); } _maxConcurrent = maxConcurrent; _ttlMs = ttlMs; _memoryBudget = memoryBudget; } public DecodeResult Accept(Frame frame, long nowMs) { if (frame == null) { throw new ArgumentNullException("frame"); } ChunkInfo chunkInfo = frame.Chunk ?? throw new ArgumentException("Not a chunk frame.", "frame"); if (chunkInfo.Count > _limits.MaxChunks || frame.PayloadLength > _limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked message " + chunkInfo.ChunkId + " exceeds this direction's limits."); } Expire(nowMs); checked { if (!_pending.TryGetValue(chunkInfo.ChunkId, out Pending value)) { while (_pending.Count >= _maxConcurrent) { Pending p = (from x in _pending.Values orderby x.StartedMs, x.Order select x).First(); Remove(p); Evictions++; } value = new Pending(frame, nowMs, _order++); _pending.Add(chunkInfo.ChunkId, value); } else if (!value.Matches(frame)) { Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " changed the message's header or chunk count mid-stream."); } ByteString byteString = value.Parts[chunkInfo.Index]; if (byteString != null) { if (byteString.FixedTimeEquals(frame.Body)) { return DecodeResult.Pending(); } Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " arrived twice with different bytes."); } if (BufferedBytes + frame.Body.Length > _memoryBudget) { Clear(); long memoryBudget = _memoryBudget; return DecodeResult.Reject(ErrorCode.MemoryBudget, hard: false, "Reassembly memory budget of " + memoryBudget + " bytes exhausted; all partial messages dropped."); } if (value.Bytes + frame.Body.Length > chunkInfo.TotalLength) { Remove(value); return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunks of message " + chunkInfo.ChunkId + " exceed its declared " + chunkInfo.TotalLength + " bytes."); } value.Parts[chunkInfo.Index] = frame.Body; value.Received++; value.Bytes += frame.Body.Length; BufferedBytes += frame.Body.Length; if (value.Received < chunkInfo.Count) { return DecodeResult.Pending(); } Remove(value); if (value.Bytes != chunkInfo.TotalLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Message " + chunkInfo.ChunkId + " reassembled to " + value.Bytes + " bytes but declared " + chunkInfo.TotalLength + "."); } byte[] array = new byte[value.Bytes]; int num = 0; ByteString[] parts = value.Parts; foreach (ByteString byteString2 in parts) { byteString2.CopyTo(array, num); num += byteString2.Length; } return FrameCodec.Open(value.First.Header, array, value.First.Compressed, value.First.PayloadLength); } } public void Expire(long nowMs) { checked { foreach (Pending item in _pending.Values.Where((Pending x) => nowMs - x.StartedMs > _ttlMs).ToList()) { Remove(item); Expirations++; } } } public void Clear() { _pending.Clear(); BufferedBytes = 0L; } private void Remove(Pending p) { checked { if (_pending.Remove(p.First.Chunk.ChunkId)) { BufferedBytes -= p.Bytes; } } } } public sealed class ReplayWindow { public const int Width = 64; private ulong _seen; public uint Highest { get; private set; } public long Rejected { get; private set; } public bool Accept(uint seq) { uint num2; checked { if (seq == 0) { Rejected++; return false; } if (seq > Highest) { uint num = seq - Highest; _seen = ((num >= 64) ? 0 : (_seen << (int)num)); _seen |= 1uL; Highest = seq; return true; } num2 = Highest - seq; if (num2 >= 64) { Rejected++; return false; } } ulong num3 = (ulong)(1L << checked((int)num2)); checked { if ((_seen & num3) != 0L) { Rejected++; return false; } _seen |= num3; return true; } } } public sealed class WireException : Exception { public ErrorCode Code { get; } = ErrorCode.Malformed; public WireException() { } public WireException(string message) : base(message) { } public WireException(string message, Exception innerException) : base(message, innerException) { } public WireException(ErrorCode code, string message) : base(message) { Code = code; } } public sealed class WireReader { private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly byte[] _buffer; private readonly int _end; private int _position; public int Remaining => checked(_end - _position); public WireReader(byte[] buffer) : this(buffer, 0, (buffer != null) ? buffer.Length : 0) { } public WireReader(byte[] buffer, int offset, int count) { _buffer = buffer ?? throw new ArgumentNullException("buffer"); checked { if (offset < 0 || count < 0 || offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } _position = offset; _end = offset + count; } } public byte ReadU8() { Need(1, "u8"); return _buffer[checked(_position++)]; } public bool ReadBool() { byte b = ReadU8(); return b switch { 0 => false, 1 => true, _ => throw new WireException(ErrorCode.Malformed, "A bool field held " + b + "; only 0 and 1 are valid."), }; } public ushort ReadU16() { Need(2, "u16"); checked { int num = _buffer[_position] | (_buffer[_position + 1] << 8); _position += 2; return (ushort)num; } } public uint ReadU32() { Need(4, "u32"); uint num = 0u; for (int i = 0; i < 4; i = checked(i + 1)) { num |= (uint)checked(_buffer[_position + i] << 8 * i); } checked { _position += 4; return num; } } public ulong ReadU64() { Need(8, "u64"); ulong num = 0uL; for (int i = 0; i < 8; i = checked(i + 1)) { num |= (ulong)_buffer[checked(_position + i)] << checked(8 * i); } checked { _position += 8; return num; } } public long ReadI64() { return (long)ReadU64(); } public ByteString ReadFixed(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } Need(length, "byte[" + length + "]"); ByteString result = ByteString.CopyFrom(_buffer, _position, length); checked { _position += length; return result; } } public ByteString ReadRest() { ByteString result = ByteString.CopyFrom(_buffer, _position, Remaining); _position = _end; return result; } public ByteString ReadBlob(int maxBytes) { uint num = ReadU32(); checked { if (num > (uint)maxBytes) { throw new WireException(ErrorCode.SizeLimit, "A blob declared " + num + " bytes; the limit is " + maxBytes + "."); } return ReadFixed((int)num); } } public string ReadString(int maxBytes) { ushort num = ReadU16(); if (n
plugins/attestation/0.61.0/player/ALIVE.Client.Player.dll.attest
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core; using ALIVE.Core.Abstractions; using ALIVE.Core.Assets; using ALIVE.Core.Client; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Diagnostics; using ALIVE.Core.Life; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using ALIVE.Core.Web; using ALIVE.Server.Util; using ALIVE.Server.World; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.Rendering; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Client.Player")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ALIVE.Server.Util { public sealed class PngWriter : IDisposable { private sealed class ChunkStream : Stream { private const int ChunkBytes = 65536; private readonly Stream _output; private readonly byte[] _buffer = new byte[65536]; private int _count; public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } internal ChunkStream(Stream output) { _output = output; } public override void Write(byte[] buffer, int offset, int count) { checked { while (count > 0) { int num = Math.Min(count, 65536 - _count); Array.Copy(buffer, offset, _buffer, _count, num); _count += num; offset += num; count -= num; if (_count == 65536) { Emit(); } } } } public override void WriteByte(byte value) { _buffer[checked(_count++)] = value; if (_count == 65536) { Emit(); } } public override void Flush() { if (_count > 0) { Emit(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } private void Emit() { WriteChunk(_output, "IDAT", _buffer, _count); _count = 0; } } private static readonly byte[] Signature = new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }; private static readonly uint[] CrcTable = MakeCrcTable(); private readonly Stream _output; private readonly int _width; private readonly int _height; private readonly ChunkStream _chunks; private readonly Stream _deflate; private readonly bool _stored; private readonly byte[] _line; private readonly byte[] _previous; private uint _adlerA = 1u; private uint _adlerB; private int _rows; private bool _finished; public bool Stored => _stored; public PngWriter(Stream output, int width, int height, bool compress = true) { if (width < 1 || height < 1 || width > 16384 || height > 16384) { throw new ArgumentOutOfRangeException("width", "A picture is 1 to 16,384 points on a side."); } _output = output ?? throw new ArgumentNullException("output"); _width = width; _height = height; checked { _line = new byte[1 + width * 3]; _previous = new byte[width * 3]; _output.Write(Signature, 0, Signature.Length); byte[] array = new byte[13]; BigEndian(array, 0, (uint)width); BigEndian(array, 4, (uint)height); array[8] = 8; array[9] = 2; array[10] = 0; array[11] = 0; array[12] = 0; WriteChunk(_output, "IHDR", array, array.Length); _chunks = new ChunkStream(_output); _chunks.WriteByte(120); _chunks.WriteByte(1); Stream stream = null; if (compress) { try { stream = new DeflateStream(_chunks, CompressionLevel.Fastest, leaveOpen: true); } catch (Exception ex) when (ex is DllNotFoundException || ex is TypeInitializationException || ex is EntryPointNotFoundException || ex is NotSupportedException || ex is PlatformNotSupportedException) { stream = null; } } _stored = stream == null; _deflate = stream ?? _chunks; } } public void WriteRow(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException("rgb"); } checked { if (rgb.Length < _width * 3) { throw new ArgumentException("A row is three bytes for each point.", "rgb"); } if (_finished || _rows >= _height) { throw new InvalidOperationException("The picture already has all its rows."); } _line[0] = 2; for (int i = 0; i < _width * 3; i++) { _line[i + 1] = unchecked((byte)(rgb[i] - _previous[i])); _previous[i] = rgb[i]; } Adler(_line, _line.Length); if (_stored) { StoredBlock(_line, _rows == _height - 1); } else { _deflate.Write(_line, 0, _line.Length); } _rows++; } } public void Finish() { if (!_finished) { if (_rows != _height) { throw new InvalidOperationException("The picture has " + _rows + " of its " + _height + " rows."); } _finished = true; if (!_stored) { _deflate.Dispose(); } byte[] array = new byte[4]; BigEndian(array, 0, (_adlerB << 16) | _adlerA); _chunks.Write(array, 0, 4); _chunks.Flush(); WriteChunk(_output, "IEND", Array.Empty<byte>(), 0); _output.Flush(); } } public void Dispose() { if (!_stored && !_finished) { _deflate.Dispose(); } } public static uint Crc(byte[] data, int count) { uint num = uint.MaxValue; for (int i = 0; i < count; i = checked(i + 1)) { num = CrcTable[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return num ^ 0xFFFFFFFFu; } private void StoredBlock(byte[] data, bool last) { checked { int num; for (int i = 0; i < data.Length; i += num) { num = Math.Min(65535, data.Length - i); bool flag = last && i + num == data.Length; _chunks.WriteByte(flag ? ((byte)1) : ((byte)0)); _chunks.WriteByte((byte)(num & 0xFF)); _chunks.WriteByte((byte)(num >> 8)); _chunks.WriteByte((byte)(~num & 0xFF)); _chunks.WriteByte((byte)((~num >> 8) & 0xFF)); _chunks.Write(data, i, num); } } } private void Adler(byte[] data, int count) { for (int i = 0; i < count; i = checked(i + 1)) { _adlerA = checked(_adlerA + data[i]) % 65521; _adlerB = checked(_adlerB + _adlerA) % 65521; } } private static void WriteChunk(Stream output, string type, byte[] data, int count) { byte[] array = new byte[8]; checked { BigEndian(array, 0, (uint)count); for (int i = 0; i < 4; i++) { array[4 + i] = (byte)type[i]; } byte[] array2 = new byte[4 + count]; Array.Copy(array, 4, array2, 0, 4); Array.Copy(data, 0, array2, 4, count); byte[] array3 = new byte[4]; BigEndian(array3, 0, Crc(array2, array2.Length)); output.Write(array, 0, 8); output.Write(data, 0, count); output.Write(array3, 0, 4); } } private static void BigEndian(byte[] into, int at, uint value) { into[at] = (byte)(value >> 24); into[checked(at + 1)] = (byte)(value >> 16); into[checked(at + 2)] = (byte)(value >> 8); into[checked(at + 3)] = (byte)value; } private static uint[] MakeCrcTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0xEDB88320u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } } namespace ALIVE.Server.World { public readonly struct MapSample { public int Biome { get; } public float Height { get; } public bool Forest { get; } public MapSample(int biome, float height, bool forest) { Biome = biome; Height = height; Forest = forest; } } public static class WorldMapPainter { public const float SeaLevel = 30f; private static readonly byte[] Outside = new byte[3] { 6, 9, 11 }; public static bool Paint(Stream output, int size, double radius, Func<double, double, MapSample> sample, Action<double>? progress, Func<bool>? stop) { if (output == null) { throw new ArgumentNullException("output"); } if (sample == null) { throw new ArgumentNullException("sample"); } if (size < 2 || size > 8192) { throw new ArgumentOutOfRangeException("size"); } if (radius <= 0.0) { throw new ArgumentOutOfRangeException("radius"); } double num = radius * 2.0 / (double)size; float[] array = new float[size]; float[] array2 = new float[size]; checked { byte[] array3 = new byte[size * 3]; using (PngWriter pngWriter = new PngWriter(output, size, size)) { for (int i = 0; i < size; i++) { if (stop != null && stop()) { return false; } double num2 = radius - ((double)i + 0.5) * num; for (int j = 0; j < size; j++) { double num3 = 0.0 - radius + ((double)j + 0.5) * num; int num4 = j * 3; if (num3 * num3 + num2 * num2 > radius * radius) { array2[j] = -20f; array3[num4] = Outside[0]; array3[num4 + 1] = Outside[1]; array3[num4 + 2] = Outside[2]; continue; } MapSample s = sample(num3, num2); float num5 = (array2[j] = ((float.IsNaN(s.Height) || float.IsInfinity(s.Height)) ? 30f : s.Height)); float num6 = ((j > 0) ? array2[j - 1] : num5); float num7 = ((i > 0) ? array[j] : num5); Colour(s, num5, num5 - num6 + (num5 - num7), out var red, out var green, out var blue); array3[num4] = red; array3[num4 + 1] = green; array3[num4 + 2] = blue; } pngWriter.WriteRow(array3); float[] array4 = array; array = array2; array2 = array4; if ((i & 0x3F) == 0) { progress?.Invoke((double)i / (double)size); } } pngWriter.Finish(); } progress?.Invoke(1.0); return true; } } public static void Colour(MapSample s, float h, float rise, out byte red, out byte green, out byte blue) { float v; float v2; float v3; if (h < 30f) { float t = Math.Min(1f, (30f - h) / 40f); v = Mix(0.34f, 0.07f, t); v2 = Mix(0.58f, 0.17f, t); v3 = Mix(0.7f, 0.29f, t); } else { switch (s.Biome) { case 1: v = 0.57f; v2 = 0.66f; v3 = 0.36f; break; case 2: v = 0.55f; v2 = 0.42f; v3 = 0.33f; break; case 4: v = 0.93f; v2 = 0.94f; v3 = 0.96f; break; case 8: v = 0.36f; v2 = 0.42f; v3 = 0.24f; break; case 16: v = 0.86f; v2 = 0.78f; v3 = 0.47f; break; case 32: v = 0.62f; v2 = 0.2f; v3 = 0.15f; break; case 64: v = 0.86f; v2 = 0.91f; v3 = 0.97f; break; case 512: v = 0.36f; v2 = 0.33f; v3 = 0.38f; break; default: v = 0.6f; v2 = 0.6f; v3 = 0.55f; break; } if (s.Forest && s.Biome != 4 && s.Biome != 64) { v *= 0.82f; v2 *= 0.86f; v3 *= 0.8f; } if (h < 31.2f && s.Biome != 4) { v = Mix(v, 0.8f, 0.5f); v2 = Mix(v2, 0.74f, 0.5f); v3 = Mix(v3, 0.56f, 0.5f); } float num = 1f + Math.Max(-0.38f, Math.Min(0.38f, rise * 0.045f)); v *= num; v2 *= num; v3 *= num; } red = Byte(v); green = Byte(v2); blue = Byte(v3); } private static float Mix(float a, float b, float t) { return a + (b - a) * t; } private static byte Byte(float v) { return checked((byte)Math.Max(0, Math.Min(255, (int)(v * 255f + 0.5f)))); } } } namespace ALIVE.Client { [BepInPlugin("com.imaginaryrealms.alive.client.player", "ALIVE Player", "0.61.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("com.imaginaryrealms.alive.client.admin")] [BepInIncompatibility("net.winterwolf.alive.client.player")] [BepInIncompatibility("net.winterwolf.alive.client.admin")] public sealed class AlivePlayerPlugin : BaseUnityPlugin { private ClientHost? _host; private void Awake() { //IL_017c: Unknown result type (might be due to invalid IL or missing references) SettingsFile.Carry(((BaseUnityPlugin)this).Config, "net.winterwolf.alive.client.player", "com.imaginaryrealms.alive.client.player", ((BaseUnityPlugin)this).Logger); if (SettingsFile.BesideOldCopy("ALIVE Player", ((BaseUnityPlugin)this).Logger)) { return; } AliveInput.Register((BaseUnityPlugin)(object)this, "com.imaginaryrealms.alive.client.player", admin: false); ConfigEntry<bool> val = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "ShowTracker", true, "Show the quest list on screen while you play."); ConfigEntry<float> trackerX = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterX", 0.9f, "Where the tracker's centre sits, as a fraction of the screen's width from the left. Drag the tracker and this updates itself."); ConfigEntry<float> trackerY = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerCenterY", 0.6f, "Where the tracker's centre sits, as a fraction of the screen's height from the bottom. Drag the tracker and this updates itself."); ConfigEntry<float> val2 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "TrackerScale", 1f, "How big the tracker is, between 0.75 and 1.5."); ConfigEntry<bool> val3 = ((BaseUnityPlugin)this).Config.Bind<bool>("Quests", "Sounds", true, "Play a sound when a quest is accepted, finished or lost."); ConfigEntry<float> val4 = ((BaseUnityPlugin)this).Config.Bind<float>("Quests", "SoundVolume", 0.5f, "How loud those sounds are, between 0 and 1."); ConfigEntry<bool> fromBank = ((BaseUnityPlugin)this).Config.Bind<bool>("Shops", "PayFromBank", false, "Pay shop prices in a banked currency (Coins and the like) from your bank rather than with what you carry. Also switched from the shop window; a shop can refuse it."); _host = ClientHost.Start((ClientRole)1, "com.imaginaryrealms.alive.client.player", ((BaseUnityPlugin)this).Info.Location, ((BaseUnityPlugin)this).Logger); if (_host != null) { _host.TrackerEnabled = val.Value; _host.TrackerCenter = new Vector2(trackerX.Value, trackerY.Value); _host.TrackerScale = val2.Value; _host.SoundEnabled = val3.Value; _host.SoundVolume = val4.Value; _host.PayFromBank = fromBank.Value; _host.PayFromBankChanged = delegate(bool on) { fromBank.Value = on; }; _host.TrackerMoved = delegate(Vector2 anchor) { //IL_0006: 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) trackerX.Value = anchor.x; trackerY.Value = anchor.y; }; } } private void OnApplicationQuit() { _host?.Dispose(); _host = null; } } internal sealed class AdminConsole { private const int WindowId = 41247; private readonly AdminClient _admin; private readonly ShopEditorView _shops; private readonly ConsolePopups _popups = new ConsolePopups(41257); private static readonly Vector2 MinSize = new Vector2(640f, 420f); private static readonly float[] Presets = new float[5] { 1f, 1.25f, 1.5f, 1.75f, 2f }; private Rect _screen; private bool _placed; private float _scale = 1f; private int _gripControl; private Vector2 _gripFrom; private Vector2 _sizeFrom; private Texture2D? _background; private GUIStyle? _window; private Vector2 _scroll; private bool _openOnly; private ulong _confirmComplete; private ulong _confirmWipe; private string _giveFlag = string.Empty; private const string FlagBox = "alive_give_flag"; private const string CounterBox = "alive_set_counter"; private (string Control, string Value) _pendingName = (Control: string.Empty, Value: string.Empty); private string _activeNameBox = string.Empty; private string _openNameList = string.Empty; private string _lastTyped = string.Empty; private Vector2 _nameListScroll; private readonly Dictionary<string, NameRows> _nameRows = new Dictionary<string, NameRows>(StringComparer.Ordinal); private string _counterName = string.Empty; private string _counterValue = string.Empty; private uint _logCategories; private LogSearchItem? _detail; private Rect _detailRect; private Vector2 _detailScroll; private Action? _leave; private string _leaveWhat = string.Empty; private bool _leavePublishing; private bool _superAdmin; private string _hammerNote = string.Empty; private string _npcLabel = string.Empty; private string _spawnerLabel = string.Empty; private bool _confirmRemoveCreatures; private string _storyFlag = string.Empty; private bool _confirmClearAll; private string _storySwitch = string.Empty; private string _picturesAsked = string.Empty; private float _openedAt = -1f; private bool _drawnSinceOpened = true; private static GUIStyle? _tipStyle; private float _keptUpAt; private string _flagFind = string.Empty; private static readonly int[] LogSizes = new int[3] { 25, 50, 100 }; private DebugArea _serverAreas = (DebugArea)127; private DebugArea _gameAreas = (DebugArea)127; private bool _serverAreasRead; private string _serverNote = string.Empty; private string _gameNote = string.Empty; private string _gameSaid = string.Empty; internal bool Visible { get; private set; } internal Action<string, string>? PlaceWithTool { get; set; } internal Action? OpenEditor { get; set; } internal Action? StopEditor { get; set; } internal Func<string>? EditorLine { get; set; } internal Action<ulong, string>? MoveWithTool { get; set; } internal Func<string>? GiveHammer { get; set; } internal Action<string>? SpawnWithTool { get; set; } internal Action<string, string>? PlaceSpawnerWithTool { get; set; } internal Action<ulong, string>? MoveSpawnerWithTool { get; set; } internal AdminConsole(AdminClient admin) { //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) _admin = admin; _shops = new ShopEditorView(admin) { Popups = _popups }; _admin.Editor.AfterDelete = delegate { _admin.RefreshNpcs(); }; _shops.GoTo = delegate(EditorPage page) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Go((AdminTab)(page switch { EditorPage.Stories => 5, EditorPage.Npcs => 7, _ => 4, })); }; _shops.GuardWith = Guard; _admin.PicturesWanted = AskedForPictures; } private void AskedForPictures(IReadOnlyList<byte> kinds) { PictureRun pictures = _admin.Pictures; bool all; if (!pictures.Busy) { all = kinds.Count == 0; pictures.Creatures = Has(1) || Has(2); pictures.Items = Has(3); pictures.Pieces = Has(4); pictures.Objects = Has(5); List<string> list = new List<string>(); if (pictures.Creatures) { list.Add("creatures"); } if (pictures.Items) { list.Add("items"); } if (pictures.Pieces) { list.Add("building pieces"); } if (pictures.Objects) { list.Add("objects"); } _picturesAsked = "The browser editor asks for pictures of " + ((list.Count == 0) ? "everything" : string.Join(", ", list)) + ". It takes a few minutes; you can keep playing."; Visible = true; Go((AdminTab)8); } bool Has(byte k) { if (!all) { return kinds.Contains(k); } return true; } } internal void Toggle() { if (Visible) { Hide(); return; } Visible = true; _openedAt = Time.unscaledTime; _drawnSinceOpened = false; if (_admin.Players.Count == 0) { _admin.RefreshPlayers(); } } internal string Where() { //IL_00a3: 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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) string text = Screen.width.ToString(CultureInfo.InvariantCulture) + "×" + Screen.height.ToString(CultureInfo.InvariantCulture); if (!_placed) { Rect? val = ConsolePrefs.Window(); if (val.HasValue) { Rect valueOrDefault = val.GetValueOrDefault(); return "its window as it was left, " + Size(valueOrDefault) + ", on a " + text + " screen"; } return "its window in the middle of a " + text + " screen"; } return "its window " + Size(_screen) + " on a " + text + " screen"; } private static string Size(Rect r) { return checked(((int)((Rect)(ref r)).width).ToString(CultureInfo.InvariantCulture) + "×" + ((int)((Rect)(ref r)).height).ToString(CultureInfo.InvariantCulture) + " at " + ((int)((Rect)(ref r)).x).ToString(CultureInfo.InvariantCulture) + "," + ((int)((Rect)(ref r)).y).ToString(CultureInfo.InvariantCulture)); } internal bool ClosePopup() { if (Visible) { if (!_shops.CloseTreePopup()) { return _popups.CloseTop(); } return true; } return false; } internal void Hide() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (Visible) { if (_placed) { ConsolePrefs.SaveWindow(_screen); } Visible = false; GUIUtility.keyboardControl = 0; } } internal void OnSessionReady(bool superAdmin) { _superAdmin = superAdmin; if (Visible) { _admin.RefreshPlayers(); } if (superAdmin) { _admin.CountWaiting(); } } internal void OnSuperAdminChanged(bool superAdmin) { if (_superAdmin != superAdmin) { _superAdmin = superAdmin; if (superAdmin) { _admin.CountWaiting(); } } } internal void Draw() { //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_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0191: 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_01bf: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Invalid comparison between Unknown and I4 //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Expected O, but got Unknown //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Expected O, but got Unknown //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) if (!Visible) { return; } Place(); if (!_drawnSinceOpened) { _drawnSinceOpened = true; float num = Time.unscaledTime - _openedAt; if (num >= 0.5f) { IAliveLog? log = AliveProps.Log; if (log != null) { log.Info("ALIVE: the admin console was drawn " + num.ToString("0.0", CultureInfo.InvariantCulture) + " s after its key opened it; " + Where() + "."); } } } KeepUp(); float num2 = (ConsolePrefs.GrowWithWindow ? Mathf.Clamp(Mathf.Min(((Rect)(ref _screen)).width / ConsolePrefs.BaseSize.x, ((Rect)(ref _screen)).height / ConsolePrefs.BaseSize.y), 0.6f, 3f) : 1f); _scale = Mathf.Clamp(ConsolePrefs.TextScale * num2, 0.5f, 4f); GUISkin val = RuneSkin.Prepare(); GUISkin skin = GUI.skin; Matrix4x4 matrix = GUI.matrix; if ((Object)(object)val != (Object)null) { GUI.skin = val; } GUI.matrix = Matrix4x4.Scale(new Vector3(_scale, _scale, 1f)); GUI.depth = 0; Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(((Rect)(ref _screen)).x / _scale, ((Rect)(ref _screen)).y / _scale, ((Rect)(ref _screen)).width / _scale, ((Rect)(ref _screen)).height / _scale); Rect val3 = GUI.Window(41247, val2, new WindowFunction(DrawWindow), "ALIVE · ADMIN", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); _popups.Windows(val2); if (_gripControl == 0 || GUIUtility.hotControl != _gripControl) { ((Rect)(ref _screen)).x = ((Rect)(ref val3)).x * _scale; ((Rect)(ref _screen)).y = ((Rect)(ref val3)).y * _scale; } if (_detail != null) { if (((Rect)(ref _detailRect)).width <= 0f) { _detailRect = new Rect(((Rect)(ref val2)).x + ((Rect)(ref val2)).width - 560f, ((Rect)(ref val2)).y + 60f, 540f, 520f); } _detailRect = GUI.Window(41249, _detailRect, new WindowFunction(DrawDetail), "EVENT", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } FollowPublish(); if (_leave != null) { Rect val4 = default(Rect); ((Rect)(ref val4))..ctor(((Rect)(ref val2)).x + (((Rect)(ref val2)).width - 560f) / 2f, ((Rect)(ref val2)).y + 140f, 560f, 230f); GUI.ModalWindow(41248, val4, new WindowFunction(DrawLeave), "UNPUBLISHED CHANGES", ((Object)(object)val != (Object)null) ? RuneSkin.Window : Style()); } GUI.matrix = matrix; GUI.skin = skin; if ((int)_admin.Tab == 5) { _shops.DrawTreeWindow(); } } private void Place() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (!_placed) { _placed = true; Rect? val = ConsolePrefs.Window(); _screen = (Rect)(((??)val) ?? new Rect(0f, 0f, Mathf.Min(ConsolePrefs.BaseSize.x, (float)Screen.width - 40f), Mathf.Min(ConsolePrefs.BaseSize.y, (float)Screen.height - 40f))); if (!val.HasValue) { ((Rect)(ref _screen)).center = new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f); } } ((Rect)(ref _screen)).width = Mathf.Clamp(((Rect)(ref _screen)).width, Mathf.Min(MinSize.x, (float)Screen.width), (float)Screen.width); ((Rect)(ref _screen)).height = Mathf.Clamp(((Rect)(ref _screen)).height, Mathf.Min(MinSize.y, (float)Screen.height), (float)Screen.height); ((Rect)(ref _screen)).x = Mathf.Clamp(((Rect)(ref _screen)).x, 0f, Mathf.Max(0f, (float)Screen.width - ((Rect)(ref _screen)).width)); ((Rect)(ref _screen)).y = Mathf.Clamp(((Rect)(ref _screen)).y, 0f, Mathf.Max(0f, (float)Screen.height - ((Rect)(ref _screen)).height)); } private void ResetWindow() { ConsolePrefs.ForgetWindow(); _placed = false; Place(); } private GUIStyle Style() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_008d: Expected O, but got Unknown //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) if (_window != null && (Object)(object)_background != (Object)null) { return _window; } _background = new Texture2D(1, 1, (TextureFormat)4, false) { hideFlags = (HideFlags)61 }; _background.SetPixel(0, 0, new Color(0.07f, 0.07f, 0.08f, 0.97f)); _background.Apply(); _window = new GUIStyle(GUI.skin.window) { padding = new RectOffset(12, 12, 24, 16) }; _window.normal.background = _background; _window.onNormal.background = _background; _window.normal.textColor = Color.white; _window.onNormal.textColor = Color.white; return _window; } private static void Tip(float width, float height) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_007d: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Expected O, but got Unknown //IL_0054: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) string tooltip = GUI.tooltip; if (!string.IsNullOrEmpty(tooltip) && (int)Event.current.type == 7) { if (_tipStyle == null) { _tipStyle = new GUIStyle(GUI.skin.box) { wordWrap = true, alignment = (TextAnchor)0, padding = new RectOffset(8, 8, 6, 6) }; } float num = Mathf.Min(380f, width - 12f); float num2 = _tipStyle.CalcHeight(new GUIContent(tooltip), num); Vector2 mousePosition = Event.current.mousePosition; float num3 = Mathf.Clamp(mousePosition.x + 14f, 6f, Mathf.Max(6f, width - num - 6f)); float num4 = ((mousePosition.y + 22f + num2 > height - 6f) ? Mathf.Max(6f, mousePosition.y - num2 - 10f) : (mousePosition.y + 22f)); GUI.Box(new Rect(num3, num4, num, num2), tooltip, _tipStyle); } } private void DrawWindow(int id) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } float num = ((Rect)(ref _screen)).width / _scale; float num2 = ((Rect)(ref _screen)).height / _scale; try { _popups.Begin(num, num2); Rect val = default(Rect); ((Rect)(ref val))..ctor(num - 20f, num2 - 20f, 18f, 18f); Grip(val); if (GUI.Button(new Rect(num - 42f, 7f, 30f, 22f), "✕")) { Hide(); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); Rail(); GUILayout.Space(14f); GUILayout.BeginVertical(Array.Empty<GUILayoutOption>()); Page(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); Texture2D grip = RuneSkin.Grip; if ((Object)(object)grip != (Object)null && (Object)(object)RuneSkin.Current != (Object)null) { GUI.DrawTexture(val, (Texture)(object)grip); } else { GUI.Label(val, "◢"); } Tip(num, num2); _popups.End(); } finally { GUI.skin = skin; } GUI.DragWindow(new Rect(0f, 0f, 10000f, 32f)); } private void Grip(Rect rect) { //IL_001b: 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_0052: 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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected I4, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0160: 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_0126: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) int controlID = GUIUtility.GetControlID((FocusType)2); Event current = Event.current; Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(((Rect)(ref _screen)).x + current.mousePosition.x * _scale, ((Rect)(ref _screen)).y + current.mousePosition.y * _scale); EventType typeForControl = current.GetTypeForControl(controlID); switch ((int)typeForControl) { case 0: if (current.button == 0 && ((Rect)(ref rect)).Contains(current.mousePosition)) { GUIUtility.hotControl = controlID; _gripControl = controlID; _gripFrom = val; _sizeFrom = new Vector2(((Rect)(ref _screen)).width, ((Rect)(ref _screen)).height); current.Use(); } break; case 3: if (GUIUtility.hotControl == controlID) { ((Rect)(ref _screen)).width = Mathf.Max(MinSize.x, _sizeFrom.x + (val.x - _gripFrom.x)); ((Rect)(ref _screen)).height = Mathf.Max(MinSize.y, _sizeFrom.y + (val.y - _gripFrom.y)); current.Use(); } break; case 1: if (GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; _gripControl = 0; ConsolePrefs.SaveWindow(_screen); current.Use(); } break; case 2: break; } } private void Rail() { //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_021e: 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) GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Space(4f); NavTo("Players", (AdminTab)0, delegate { _admin.RefreshPlayers(); }); NavTo("Quests", (AdminTab)1, delegate { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); }); NavTo("Activity", (AdminTab)2, delegate { _admin.RefreshLog(_logCategories); }); NavTo("NPCs", (AdminTab)3, delegate { _admin.RefreshNpcs(); _admin.Editor.RefreshLists(); }); NavTo("Creatures", (AdminTab)10, delegate { _admin.RefreshCreatures(); }); GUILayout.Space(10f); GUILayout.Label("CONTENT EDITOR", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Shops", (AdminTab)4, null); NavTo("Quest editor", (AdminTab)5, null); NavTo("NPC creator", (AdminTab)7, null); NavTo("Pictures", (AdminTab)8, null); NavTo("Test tools", (AdminTab)9, delegate { _admin.Editor.RefreshLists(); }); EditorButton(); GUILayout.Space(10f); GUILayout.Label("YOU", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); NavTo("Preferences", (AdminTab)6, null); NavTo("Debug log", (AdminTab)11, delegate { _admin.AskDebug(); }); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.1f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(52f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.1f; } GUILayout.EndHorizontal(); RuneSkin.Line(_superAdmin ? "● SuperAdmin" : "○ Not an admin here", _superAdmin ? RuneSkin.Moss : RuneSkin.Rust); if (_admin.TestKills) { RuneSkin.Line("⚔ Test mode on", RuneSkin.Amber); } GUILayout.Label("Esc closes · drag the corner to resize", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndVertical(); } private static string Percent(float scale) { return checked((int)(scale * 100f + 0.5f)).ToString(CultureInfo.InvariantCulture) + "%"; } private void NavTo(string label, AdminTab tab, Action? opened) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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) bool flag = _admin.Tab == tab; if (!GUILayout.Button(label, RuneSkin.Or(flag ? RuneSkin.NavOn : RuneSkin.Nav, GUI.skin.button), Array.Empty<GUILayoutOption>())) { return; } if (flag) { opened?.Invoke(); return; } Guard("Going to " + label, delegate { //IL_0007: Unknown result type (might be due to invalid IL or missing references) Go(tab); opened?.Invoke(); }); } private void Guard(string what, Action go) { ContentEditor editor = _admin.Editor; if (editor.Form == null || !editor.Dirty) { go(); return; } _leave = go; _leaveWhat = what; _leavePublishing = false; } private void DrawLeave(int id) { //IL_006e: 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) GUISkin current = RuneSkin.Current; GUISkin skin = GUI.skin; if ((Object)(object)current != (Object)null) { GUI.skin = current; } try { JsonForm form = _admin.Editor.Form; string text = ((form == null) ? "this" : ((form.DisplayName.Length > 0) ? form.DisplayName : form.Id)); GUILayout.Space(6f); RuneSkin.Line("Changes have been made to " + text + " that are not published yet.", RuneSkin.Amber); GUILayout.Label(_leaveWhat + " would leave them behind. What would you like to do?", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.Space(10f); if (_leavePublishing) { RuneSkin.Line((_admin.Editor.Status.Length > 0) ? _admin.Editor.Status : "Publishing…", RuneSkin.Steel); return; } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Publish, then go on", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.Publish(_admin.Reason); } if (GUILayout.Button("Save as a draft, then go on", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leavePublishing = true; _admin.Editor.SaveDraft(_admin.Reason); } if (GUILayout.Button("Go on without publishing", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { Action leave = _leave; _leave = null; _admin.Editor.Close(); leave?.Invoke(); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) })) { _leave = null; } GUILayout.EndHorizontal(); } finally { GUI.skin = skin; } } private void FollowPublish() { ContentEditor editor = _admin.Editor; if (_leavePublishing && _leave != null && !editor.Busy) { _leavePublishing = false; if (editor.Dirty) { _leave = null; return; } Action leave = _leave; _leave = null; leave(); } } private void Go(AdminTab tab) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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) if (_admin.Tab != tab) { _admin.Tab = tab; _scroll = Vector2.zero; _shops.LeftPage(); } } private static string PageTitle(AdminTab tab) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown return (int)tab switch { 0 => "Players", 1 => "Quests in progress", 3 => "NPCs in the world", 10 => "Creatures and spawners", 4 => "Shops, trades and money", 5 => "Quests and conversations", 7 => "NPC creator", 8 => "Pictures for the browser editor", 9 => "Test tools", 6 => "Preferences", 11 => "Debug log", _ => "Activity", }; } private void DrawPreferences() { //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Text"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("A−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.TextScale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(56f) }); if (GUILayout.Button("A+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) })) { ConsolePrefs.TextScale += 0.05f; } GUILayout.Space(16f); float[] presets = Presets; foreach (float num in presets) { bool flag = Mathf.Abs(ConsolePrefs.TextScale - num) < 0.01f; if (GUILayout.Toggle(flag, Percent(num), GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(64f) }) && !flag) { ConsolePrefs.TextScale = num; } } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Resizing the window", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); bool flag2 = GUILayout.Toggle(ConsolePrefs.GrowWithWindow, "makes the text bigger or smaller with it", Array.Empty<GUILayoutOption>()); if (flag2 != ConsolePrefs.GrowWithWindow) { ConsolePrefs.GrowWithWindow = flag2; } GUILayout.EndHorizontal(); GUILayout.Label(ConsolePrefs.GrowWithWindow ? "Drag the window's corner: at its usual size the text is the size above; twice as big, twice the size." : "Drag the window's corner for more room; the text stays the size above.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Font", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Averia Serif (Valheim's)", ConsolePrefs.Font == "averia", delegate { ConsolePrefs.Font = "averia"; }); Choice("Averia Serif light", ConsolePrefs.Font == "averia_light", delegate { ConsolePrefs.Font = "averia_light"; }); Choice("Plain", ConsolePrefs.Font == "plain", delegate { ConsolePrefs.Font = "plain"; }); GUILayout.EndHorizontal(); RuneSkin.Header("Look and colours"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Look", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); Choice("Rune-carved", ConsolePrefs.Look == "rune", delegate { ConsolePrefs.Look = "rune"; }); Choice("Plain (Unity's own)", ConsolePrefs.Look == "plain", delegate { ConsolePrefs.Look = "plain"; }); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Accent", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color, Color, Color)[] accents = RuneSkin.Accents; for (int num2 = 0; num2 < accents.Length; num2++) { (string, string, Color, Color, Color) tuple = accents[num2]; var (text, _, _, _, _) = tuple; if (RuneSkin.Swatch(tuple.Item3, 22f, ConsolePrefs.Accent == text)) { ConsolePrefs.Accent = text; } GUILayout.Label(tuple.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(62f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Text colour", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); (string, string, Color)[] textColours = RuneSkin.TextColours; for (int num3 = 0; num3 < textColours.Length; num3++) { (string, string, Color) tuple3 = textColours[num3]; var (text2, _, _) = tuple3; if (RuneSkin.Swatch(tuple3.Item3, 22f, ConsolePrefs.TextColour == text2)) { ConsolePrefs.TextColour = text2; } GUILayout.Label(tuple3.Item2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(82f) }); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Panel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); if (GUILayout.Button("−", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity -= 0.05f; } GUILayout.Label(Percent(ConsolePrefs.Opacity) + " solid", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); if (GUILayout.Button("+", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(30f) })) { ConsolePrefs.Opacity += 0.05f; } GUILayout.Label("(lower lets the world show through)", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (ConsolePrefs.Look == "plain") { GUILayout.Label("The accent, text colour, font and panel apply to the rune-carved look.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Window"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Size", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(checked(((int)((Rect)(ref _screen)).width).ToString(CultureInfo.InvariantCulture) + " × " + ((int)((Rect)(ref _screen)).height).ToString(CultureInfo.InvariantCulture)) + " pixels, drawn at " + Percent(_scale), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Usual size, middle of the screen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Space(10f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Everything back to the defaults", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) })) { ConsolePrefs.Reset(); ResetWindow(); } GUILayout.EndHorizontal(); GUILayout.Label("These are saved on this computer, in the ALIVE Admin config file under [Console]. They change only your console.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private static void Choice(string label, bool chosen, Action choose) { if (GUILayout.Toggle(chosen, label, GUI.skin.button, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }) && !chosen) { choose(); } } private void KeepUp() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_006e: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected I4, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Invalid comparison between Unknown and I4 if (Event.current == null || (int)Event.current.type != 7) { return; } float unscaledTime = Time.unscaledTime; float num = (((int)_admin.Tab == 3 || (int)_admin.Tab == 10) ? 15f : 10f); if (unscaledTime - _keptUpAt < num) { return; } _keptUpAt = unscaledTime; if (GUIUtility.keyboardControl != 0 || _leave != null) { return; } AdminTab tab = _admin.Tab; switch ((int)tab) { default: if ((int)tab == 10) { _admin.Quietly((Action)_admin.RefreshCreatures); } break; case 0: _admin.Quietly((Action)_admin.RefreshPlayers); if (_admin.FlagsPlayer.Length > 0) { _admin.Quietly((Action)delegate { _admin.ShowFlags(_admin.FlagsPlayer); }); } break; case 1: _admin.Quietly((Action)delegate { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } }); break; case 2: _admin.Quietly((Action)delegate { _admin.RefreshLog(_logCategories); }); break; case 3: _admin.Quietly((Action)_admin.RefreshNpcs); break; } } private void EditorButton() { //IL_00c6: 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) if (OpenEditor == null) { return; } GUILayout.Space(6f); bool enabled = GUI.enabled; GUI.enabled = enabled && _superAdmin; if (GUILayout.Button("Open the editor\nin my browser", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), Array.Empty<GUILayoutOption>())) { OpenEditor(); } GUI.enabled = enabled; if (!_superAdmin) { GUILayout.Label("For SuperAdmins only", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); return; } string text = EditorLine?.Invoke() ?? string.Empty; if (text.Length != 0) { RuneSkin.Line(text, text.Contains("not connected") ? RuneSkin.Rust : RuneSkin.Moss); if (StopEditor != null && GUILayout.Button("Stop it", Array.Empty<GUILayoutOption>())) { StopEditor(); } } } private void Page() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected I4, but got Unknown //IL_00c4: 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_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Invalid comparison between Unknown and I4 //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Invalid comparison between Unknown and I4 //IL_01e2: 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_010f: 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_02ed: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label(PageTitle(_admin.Tab), RuneSkin.Or(RuneSkin.Title, GUI.skin.label), Array.Empty<GUILayoutOption>()); _scroll = GUILayout.BeginScrollView(_scroll, Array.Empty<GUILayoutOption>()); AdminTab tab = _admin.Tab; switch ((int)tab) { case 0: DrawPlayers(); break; case 1: DrawQuests(); break; case 3: DrawNpcs(); break; case 10: DrawCreatures(); break; case 4: case 5: case 7: { ShopEditorView shops = _shops; AdminTab tab2 = _admin.Tab; EditorPage page = (((int)tab2 == 5) ? EditorPage.Stories : (((int)tab2 == 7) ? EditorPage.Npcs : EditorPage.Shops)); shops.Page = page; _shops.Draw(); if (_shops.WantsTop) { _shops.WantsTop = false; _scroll = Vector2.zero; } break; } case 6: DrawPreferences(); break; case 8: PicturesSection(); break; case 9: DrawTestTools(); break; case 11: DrawDebug(); break; default: DrawLog(); break; } GUILayout.EndScrollView(); GUILayout.Space(6f); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Note for the audit log", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); _admin.Reason = GUILayout.TextField(_admin.Reason ?? string.Empty, 256, Array.Empty<GUILayoutOption>()); GUILayout.EndHorizontal(); if (_superAdmin) { GUILayout.Label("Optional. Every change is recorded with your Steam id either way.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } else { RuneSkin.Line(AdminClient.NotAnAdmin(_admin.PlatformId), RuneSkin.Rust); } if (_admin.PendingOpId.Length > 0) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); RuneSkin.Line("Waiting for another SuperAdmin: " + _admin.PendingOpId, RuneSkin.Amber); if (GUILayout.Button("Approve", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, true); } if (GUILayout.Button("Refuse", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.Decide(_admin.PendingOpId, false); } GUILayout.EndHorizontal(); } if (_admin.Status.Length > 0) { RuneSkin.Line(_admin.Status, RuneSkin.Tone(_admin.Status)); } } private void DrawPlayers() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Name or Steam id", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); _admin.PlayerQuery = GUILayout.TextField(_admin.PlayerQuery ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); if (GUILayout.Button("Search", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshPlayers(); } GUILayout.EndHorizontal(); foreach (PlayerSearchItem player in _admin.Players) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((player.Online ? "● " : "○ ") + ((player.LastName.Length == 0) ? "(no name yet)" : player.LastName), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(player.PlatformId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(player.SessionCount + " visit(s), last " + Ago(player.LastSeenUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); if (GUILayout.Button("Quests", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshQuests(player.PlatformId, false); } if (GUILayout.Button("Flags…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; _admin.ShowFlags(player.PlatformId); } GUILayout.EndHorizontal(); } if (_admin.Players.Count == 0) { GUILayout.Label("Nobody matched. The list holds players who have joined with ALIVE at least once.", Array.Empty<GUILayoutOption>()); } if (_admin.FlagsPlayer.Length > 0) { DrawFlags(); } } private void DrawFlags() { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_08c1: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); string text = ((_admin.FlagsName.Length > 0) ? _admin.FlagsName : _admin.FlagsPlayer); GUILayout.Space(10f); RuneSkin.Header(text + "'s ALIVE flags" + ((_admin.FlagsTotal >= 0) ? (" · " + _admin.FlagsTotal) : string.Empty)); GUILayout.Label(_admin.FlagsPlayer + ". A flag is a yes-or-no mark ALIVE keeps for each player: quests and conversations give and take them and read them to decide what happens. The browser editor's Story memory page shows where each one is set and read.", val, Array.Empty<GUILayoutOption>()); foreach (string flagLine in _admin.FlagLines) { RuneSkin.Line(flagLine, RuneSkin.Tone(flagLine)); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Find", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(50f) }); _flagFind = GUILayout.TextField(_flagFind ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) }); if (GUILayout.Button("⟳ Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (_admin.FlagsTotal < 0) { GUILayout.Label("Asking the server…", val, Array.Empty<GUILayoutOption>()); } else if (_admin.FlagsTotal == 0) { GUILayout.Label(text + " holds no ALIVE flags.", val, Array.Empty<GUILayoutOption>()); } string find = (_flagFind ?? string.Empty).Trim(); List<PlayerFlagItem> list = (from f in _admin.PlayerFlags where find.Length == 0 || f.Flag.Contains(find, StringComparison.OrdinalIgnoreCase) orderby (!string.Equals(f.Flag, _admin.LitFlag, StringComparison.Ordinal)) ? 1 : 0 select f).ToList(); if (find.Length > 0 && list.Count == 0 && _admin.FlagsTotal > 0) { GUILayout.Label("None of their flags is called that.", val, Array.Empty<GUILayoutOption>()); } foreach (PlayerFlagItem item in list) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text2 = (item.Flag.StartsWith("alive:flag/", StringComparison.Ordinal) ? item.Flag.Substring("alive:flag/".Length) : item.Flag); bool flag = string.Equals(item.Flag, _admin.LitFlag, StringComparison.Ordinal); Color contentColor = GUI.contentColor; if (flag) { GUI.contentColor = RuneSkin.Amber; } GUILayout.Label((flag ? "● " : string.Empty) + text2, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUI.contentColor = contentColor; GUILayout.Label("set " + Ago(item.SetUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Clear", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ClearFlags(item.Flag); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal > _admin.PlayerFlags.Count) { GUILayout.Label("…and " + checked(_admin.FlagsTotal - _admin.PlayerFlags.Count) + " more, oldest first, not shown.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Give a flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _giveFlag = NameBox("alive_give_flag", _giveFlag); GUI.enabled = _giveFlag.Trim().Length > 0 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Give", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.GiveFlag(_giveFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); NameSuggestions("alive_give_flag", _giveFlag, _admin.KnownFlags, "alive:flag/", "flags", delegate(string v) { _giveFlag = v; }); GUILayout.Space(6f); GUILayout.Label("Counters: numbers ALIVE keeps for each player, which quests and conversations add to and compare.", val, Array.Empty<GUILayoutOption>()); foreach (PlayerCounterItem playerCounter in _admin.PlayerCounters) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); string text3 = (playerCounter.Counter.StartsWith("alive:counter/", StringComparison.Ordinal) ? playerCounter.Counter.Substring("alive:counter/".Length) : playerCounter.Counter); GUILayout.Label(text3, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(300f) }); GUILayout.Label(playerCounter.Value.ToString(CultureInfo.InvariantCulture), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); if (GUILayout.Button("Change…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _counterName = text3; _counterValue = playerCounter.Value.ToString(CultureInfo.InvariantCulture); } GUILayout.EndHorizontal(); } if (_admin.FlagsTotal >= 0 && _admin.PlayerCounters.Count == 0) { GUILayout.Label(text + " holds no ALIVE counters.", val, Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Set a counter", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); _counterName = NameBox("alive_set_counter", _counterName); GUILayout.Label("to", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(20f) }); _counterValue = GUILayout.TextField(_counterValue, 12, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }); long result; bool flag2 = long.TryParse(_counterValue.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out result); GUI.enabled = _counterName.Trim().Length > 0 && flag2 && _admin.FlagsTotal >= 0; if (GUILayout.Button("Set", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.SetCounter(_counterName, result); } GUI.enabled = true; GUILayout.EndHorizontal(); if (_counterValue.Trim().Length > 0 && !flag2) { GUILayout.Label("A counter is a whole number, such as 3 or -1. 0 takes it away.", val, Array.Empty<GUILayoutOption>()); } NameSuggestions("alive_set_counter", _counterName, _admin.KnownCounters, "alive:counter/", "counters", delegate(string v) { _counterName = v; }); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _admin.FlagsTotal > 0; if (GUILayout.Button("Clear all…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _confirmClearAll = !_confirmClearAll; } GUI.enabled = true; if (GUILayout.Button("Read again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.ShowFlags(_admin.FlagsPlayer); } if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmClearAll = false; _admin.HideFlags(); } GUILayout.EndHorizontal(); if (_confirmClearAll && _admin.FlagsTotal > 0) { RuneSkin.Line("Clear all " + _admin.FlagsTotal + " flags " + text + " holds? Quests and conversations that read them will treat " + text + " as if they never had them.", RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Clear them all", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmClearAll = false; _admin.ClearFlags(string.Empty); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmClearAll = false; } GUILayout.EndHorizontal(); } } private string NameBox(string control, string value) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Invalid comparison between Unknown and I4 //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 if ((int)Event.current.type == 8 && _pendingName.Control == control) { value = _pendingName.Value; _pendingName = (Control: string.Empty, Value: string.Empty); _activeNameBox = string.Empty; if (GUI.GetNameOfFocusedControl() == control) { GUIUtility.keyboardControl = 0; } } GUI.SetNextControlName(control); string text = GUILayout.TextField(value, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if ((int)Event.current.type == 8 && GUI.GetNameOfFocusedControl() == control && !string.Equals(text, _lastTyped, StringComparison.Ordinal)) { _activeNameBox = control; } if ((int)Event.current.type == 8) { _lastTyped = ((GUI.GetNameOfFocusedControl() == control) ? text : _lastTyped); } bool flag = _openNameList == control; if (GUILayout.Button(flag ? "Hide list" : "List", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(72f) })) { _openNameList = (flag ? string.Empty : control); } return text; } private void NameSuggestions(string control, string value, IReadOnlyList<string> known, string prefix, string what, Action<string> chosen) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0116: 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_0150: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 8) { _nameRows[control] = NameRows.Of(control == _openNameList, control == _activeNameBox, value, known, prefix); } if (!_nameRows.TryGetValue(control, out NameRows value2) || !value2.Shown) { return; } GUIStyle val = RuneSkin.Or(RuneSkin.Row, GUI.skin.button); GUIStyle val2 = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(110f); GUILayout.BeginVertical((GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(value2.Open ? 306f : 280f) }); if (value2.Open && value2.Names.Count == 0) { GUILayout.Label((value2.Known == 0) ? ("The server knows no " + what + " yet: none is set or read by its quests and conversations, and no player holds one.") : ("None of the " + what + " the server knows has that in its name."), val2, Array.Empty<GUILayoutOption>()); } else if (value2.Open) { _nameListScroll = GUILayout.BeginScrollView(_nameListScroll, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(Mathf.Min(220f, 26f * (float)value2.Names.Count + 8f)) }); foreach (string name in value2.Names) { if (GUILayout.Button(name, val, Array.Empty<GUILayoutOption>())) { Choose(control, name, chosen); } } GUILayout.EndScrollView(); } else { foreach (string name2 in value2.Names) { if (GUILayout.Button(name2, val, Array.Empty<GUILayoutOption>())) { Choose(control, name2, chosen); } } if (value2.More > 0) { GUILayout.Label("…and " + value2.More.ToString(CultureInfo.InvariantCulture) + " more: type more, or open the list.", val2, Array.Empty<GUILayoutOption>()); } } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } private void Choose(string control, string name, Action<string> chosen) { chosen(name); _pendingName = (Control: control, Value: name); _openNameList = string.Empty; _activeNameBox = string.Empty; } private void DrawQuests() { //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_05a0: Unknown result type (might be due to invalid IL or missing references) //IL_065f: Unknown result type (might be due to invalid IL or missing references) GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((_admin.QuestPlayer.Length == 0) ? "Every player" : ("Player " + _admin.QuestPlayer), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(260f) }); bool flag = GUILayout.Toggle(_openOnly, "Only unfinished", Array.Empty<GUILayoutOption>()); if (flag != _openOnly) { _openOnly = flag; _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { if (_admin.ShowingWaiting) { _admin.RefreshWaiting(); } else { _admin.RefreshQuests(_admin.QuestPlayer, _openOnly); } } if (_admin.QuestPlayer.Length > 0 && GUILayout.Button("All players", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _admin.RefreshQuests(string.Empty, _openOnly); } string text = ((_admin.WaitingCount > 0) ? ("Waiting for me (" + _admin.WaitingCount.ToString(CultureInfo.InvariantCulture) + ")") : "Waiting for me"); if (GUILayout.Button(text, (GUIStyle)((_admin.WaitingCount > 0) ? ((object)RuneSkin.Or(RuneSkin.Primary, GUI.skin.button)) : ((object)GUI.skin.button)), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) })) { _admin.RefreshWaiting(); } GUILayout.EndHorizontal(); TestKillsRow(); if (_admin.ShowingWaiting) { RuneSkin.Line("Quests with a step waiting for an admin to check it. Mark the step done when the player has done it.", RuneSkin.Amber); } foreach (QuestInstanceRow quest in _admin.Quests) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(quest.QuestId, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(230f) }); GUILayout.Label(StateName(quest.State) + " (try " + quest.Attempt + ")", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Progress(quest), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); bool flag2 = quest.State != 0 && QuestStates.IsOpen((QuestState)quest.State); if (flag2 && GUILayout.Button("Clear progress", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.ResetQuest(quest.InstanceId, false); } if (GUILayout.Button(flag2 ? "Full reset" : "Let them retake", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(flag2 ? 80f : 120f) })) { _admin.ResetQuest(quest.InstanceId, true); } if (flag2 && GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.CancelQuest(quest.InstanceId); } if (GUILayout.Button("Take rewards", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.RevokeQuest(quest.InstanceId); } if (GUILayout.Button("Close to player", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, true, 0uL); } if (GUILayout.Button("Reopen", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.DenyQuest(quest.PlatformId, quest.QuestId, false, 0uL); } if ((quest.State == 2 || quest.State == 3 || quest.State == 7 || quest.State == 9) && GUILayout.Button("Complete…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmComplete = ((_confirmComplete == quest.InstanceId) ? 0 : quest.InstanceId); } if (quest.State == 7 && GUILayout.Button("Resume", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _admin.ResumeQuest(quest.InstanceId); } GUI.enabled = _superAdmin; if (GUILayout.Button("Wipe…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = ((_confirmWipe == quest.InstanceId) ? 0 : quest.InstanceId); } GUI.enabled = true; GUILayout.EndHorizontal(); if (quest.Status.Length > 0) { RuneSkin.Line(" " + quest.Status, RuneSkin.Amber); } if (_confirmWipe == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Wipe " + quest.QuestId + " from " + quest.PlatformId + "'s history, as if they never took it? Every attempt, its steps and the flags it uses go, and rewards it has not handed over are not handed over. What they were given stays theirs. This cannot be undone; the audit log keeps the record.", RuneSkin.Amber); if (GUILayout.Button("Wipe it", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) })) { _confirmWipe = 0uL; _admin.WipeQuest(quest.InstanceId); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmWipe = 0uL; } GUILayout.EndHorizontal(); } if (_confirmComplete == quest.InstanceId) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); RuneSkin.Line("Complete it for " + quest.PlatformId + " as if they had finished it? The rewards are paid; nothing it asked for is taken.", RuneSkin.Amber); if (GUILayout.Button("Complete and pay", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _confirmComplete = 0uL; _admin.CompleteQuest(quest.InstanceId, ""); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) })) { _confirmComplete = 0uL; } GUILayout.EndHorizontal(); } foreach (QuestObjectiveRow objective in quest.Objectives) { if (objective.Manual) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Space(24f); GUILayout.Label("Step \"" + objective.ObjectiveId + "\"" + ((objective.Text.Length > 0) ? (": " + objective.Text) : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(520f) }); if (GUILayout.Button("Mark it done", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.CompleteQuest(quest.InstanceId, objective.ObjectiveId); } GUILayout.EndHorizontal(); } } } if (_admin.Quests.Count == 0) { GUILayout.Label(_admin.ShowingWaiting ? "Nothing is waiting for you to check." : "No quest instances yet.", Array.Empty<GUILayoutOption>()); } } private void TestKillsRow() { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); bool flag = GUILayout.Toggle(_admin.TestKills, "Test mode: what I do counts for my quests at once, even with creatures and items I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); if (flag != _admin.TestKills) { _admin.SetTestKills(flag); } GUILayout.EndHorizontal(); GUILayout.Label(_admin.TestKills ? "On for you until you log off: your kills, what you pick up for gathering steps, and taming count at once. Each is in the activity log (kill.test, quest.gather_test). Players beside you are checked as always." : "Off: you are checked like everyone else. A creature that appears right beside a player must be watched a while before its death counts, and only what was gathered in the world counts for gathering steps.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } private void DrawTestTools() { //IL_0397: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = RuneSkin.Or(RuneSkin.Aside, GUI.skin.label); RuneSkin.Header("Meet an NPC again for the first time"); GUILayout.Label("The NPC forgets you: how often you have spoken, the lines you heard and the answers you chose in their conversation, and the flags that conversation gives. Only you: players keep what they have.", val, Array.Empty<GUILayoutOption>()); IReadOnlyList<ContentListItem> readOnlyList = _admin.Editor.Listed((AliveIdKind)1); foreach (ContentListItem item in readOnlyList) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((item.DisplayName.Length > 0) ? item.DisplayName : item.Id, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); if (GUILayout.Button("Forget me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) })) { _admin.UseStoryTool((byte)1, item.Id); } GUILayout.EndHorizontal(); } if (readOnlyList.Count == 0) { GUILayout.Label("(no NPCs yet, or the list is still loading)", val, Array.Empty<GUILayoutOption>()); } GUILayout.Space(8f); RuneSkin.Header("Your own flags"); GUILayout.Label("Give yourself a flag, or take one away, to try a branch without playing up to it. Every flag, with what sets it and what reads it, is on the browser editor's Story memory page.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Flag", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storyFlag = GUILayout.TextField(_storyFlag, 128, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storyFlag.Trim().Length > 0; if (GUILayout.Button("Give me", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)2, _storyFlag); } if (GUILayout.Button("Take away", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.UseStoryTool((byte)3, _storyFlag); } GUI.enabled = true; GUILayout.EndHorizontal(); if (GUILayout.Button("See all my flags", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { string playerQuery = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerName() : string.Empty); _admin.PlayerQuery = playerQuery; Go((AdminTab)0); _admin.RefreshPlayers(); } GUILayout.Space(8f); RuneSkin.Header("Server switches"); GUILayout.Label("One on/off for every player, read by conversations as \"Server switch is on\". Switching it changes what every player meets at once.", val, Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Switch", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }); _storySwitch = GUILayout.TextField(_storySwitch, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(280f) }); GUI.enabled = _storySwitch.Trim().Length > 0; if (GUILayout.Button("On for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)4, _storySwitch); } if (GUILayout.Button("Off for everyone", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.UseStoryTool((byte)5, _storySwitch); } GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.Space(8f); RuneSkin.Header("Kills"); TestKillsRow(); if (_admin.StoryLines.Count == 0) { return; } GUILayout.Space(8f); foreach (string storyLine in _admin.StoryLines) { RuneSkin.Line(storyLine, RuneSkin.Moss); } } private void DrawNpcs() { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) RuneSkin.Header("Place an NPC"); GUILayout.Label("Place here puts the NPC where you stand, facing you. Place… lets you aim: the NPC follows where you look, the wheel turns it, a click puts it down, right-click stops. The server takes any spot within 30 m of you.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _npcLabel = GUILayout.TextField(_npcLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.FlexibleSpace(); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshNpcs(); } GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } _shops.DrawDeleteBox(); if (_admin.Editor.DeleteId.Length == 0 && _admin.Editor.Status.StartsWith("Deleted", StringComparison.Ordinal)) { RuneSkin.Line(_admin.Editor.Status, RuneSkin.Moss); } string text = _npcLabel ?? string.Empty; foreach (string item in _admin.Placeable) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(NpcName(item), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label(item, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceNpc(item, text); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceWithTool != null) { PlaceWithTool(item, text); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(item); } ContentListItem val = Listed(item); GUI.enabled = val != null && !_admin.Editor.Busy; if (GUILayout.Button("Delete…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && val != null) { _admin.Editor.AskDelete(val.Id, val.Version, NpcName(item)); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.Placeable.Count == 0) { GUILayout.Label("The loaded content has no NPCs to place.", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("In the world"); foreach (NpcPlacementRow placement in _admin.Placements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label((placement.Enabled ? "● " : "○ ") + placement.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) }); GUILayout.Label((placement.Label.Length == 0) ? "-" : placement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(Metres(placement.XCm) + ", " + Metres(placement.YCm) + ", " + Metres(placement.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) }); GUILayout.Label("placed " + Ago(placement.PlacedUnixMs), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }); if (GUILayout.Button("Teleport to NPC", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) })) { _admin.GoToNpc(placement.PlacementId); } if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveWithTool != null) { MoveWithTool(placement.PlacementId, placement.NpcId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveNpc(placement.PlacementId); } if (GUILayout.Button("Edit", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) })) { EditNpc(placement.NpcId); } GUILayout.EndHorizontal(); } if (_admin.Placements.Count == 0) { GUILayout.Label("No NPC has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void DrawCreatures() { //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) GUILayout.Label("Creatures and spawners are made in the browser editor on the server machine and published there. Here you try them and place them.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin && GiveHammer != null; if (GUILayout.Button("Get the Admin Tool", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(170f) })) { _hammerNote = GiveHammer(); } GUI.enabled = true; if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _admin.RefreshCreatures(); } GUILayout.FlexibleSpace(); GUILayout.Label(_admin.CreaturesAlive.ToString(CultureInfo.InvariantCulture) + " of at most " + _admin.CreatureLimit.ToString(CultureInfo.InvariantCulture) + " ALIVE creatures alive · " + _admin.CreaturesMine.ToString(CultureInfo.InvariantCulture) + " spawned by you", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); GUILayout.EndHorizontal(); if (_hammerNote.Length > 0) { RuneSkin.Line(_hammerNote, _hammerNote.StartsWith("The ALIVE Admin Tool is in", StringComparison.Ordinal) ? RuneSkin.Moss : RuneSkin.Steel); } if (!_admin.CllcOnServer && _admin.CreaturesKnown) { GUILayout.Label("Creature Level & Loot Control is not on this server: creatures' settings for it are skipped.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Creatures"); GUILayout.Label("Spawn with the Admin Tool: aim, click for one, Shift+click for five, right-click to stop. A creature you spawn gives no loot, kill credit or world key, unless your test mode is on (Test tools).", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); foreach (CreatureRow creatureRow in _admin.CreatureRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(creatureRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(creatureRow.Base + ((creatureRow.Level > 1) ? (" " + new string('★', Math.Min(9, checked(creatureRow.Level - 1)))) : string.Empty) + (creatureRow.Boss ? " · boss" : string.Empty), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); GUILayout.Label(creatureRow.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && SpawnWithTool != null; if (GUILayout.Button("Spawn with the Admin Tool", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) })) { if (NpcHammer.Held() == null && GiveHammer != null) { _hammerNote = GiveHammer(); } SpawnWithTool(creatureRow.Id); } GUI.enabled = true; GUILayout.EndHorizontal(); } if (_admin.CreatureRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No creatures yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); if (GUILayout.Button("Remove the ones I spawned", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) })) { _admin.ClearCreatures((CreatureClearScope)0, 0uL); } GUI.enabled = _superAdmin; if (!_confirmRemoveCreatures) { if (GUILayout.Button("Remove every ALIVE creature…", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(240f) })) { _confirmRemoveCreatures = true; } } else { if (GUILayout.Button("Yes, remove them all", RuneSkin.Or(RuneSkin.Danger, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) })) { _confirmRemoveCreatures = false; _admin.ClearCreatures((CreatureClearScope)2, 0uL); } if (GUILayout.Button("Cancel", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) })) { _confirmRemoveCreatures = false; } } GUI.enabled = true; GUILayout.EndHorizontal(); RuneSkin.Header("Spawn points and altars"); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label("Spot label", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }); _spawnerLabel = GUILayout.TextField(_spawnerLabel ?? string.Empty, 64, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }); GUILayout.EndHorizontal(); foreach (SpawnerRow spawnerRow in _admin.SpawnerRows) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(spawnerRow.Name, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label(spawnerRow.Altar ? ("altar" + ((spawnerRow.Look.Length > 0) ? (" (" + spawnerRow.Look + ")") : string.Empty)) : "spawn point", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) }); if (GUILayout.Button("Place here", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.PlaceSpawner(spawnerRow.Id, _spawnerLabel ?? string.Empty); } if (GUILayout.Button("Place…", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(80f) }) && PlaceSpawnerWithTool != null) { PlaceSpawnerWithTool(spawnerRow.Id, _spawnerLabel ?? string.Empty); } GUILayout.EndHorizontal(); } if (_admin.SpawnerRows.Count == 0) { GUILayout.Label(_admin.CreaturesKnown ? "No spawners yet: make one in the browser editor and publish it." : "Asking the server…", Array.Empty<GUILayoutOption>()); } RuneSkin.Header("Placed"); foreach (SpawnerPlacementRow spawnerPlacement in _admin.SpawnerPlacements) { GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUILayout.Label(_admin.SpawnerName(spawnerPlacement.SpawnerId), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(180f) }); GUILayout.Label((spawnerPlacement.Label.Length == 0) ? "-" : spawnerPlacement.Label, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(120f) }); GUILayout.Label(Metres(spawnerPlacement.Spot.XCm) + ", " + Metres(spawnerPlacement.Spot.YCm) + ", " + Metres(spawnerPlacement.Spot.ZCm), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) }); GUILayout.Label(spawnerPlacement.Alive.ToString(CultureInfo.InvariantCulture) + " alive", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }); GUI.enabled = _superAdmin && _admin.TeleportTo != null; if (GUILayout.Button("Teleport to", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _admin.TeleportTo((double)spawnerPlacement.Spot.XCm / 100.0, (double)spawnerPlacement.Spot.YCm / 100.0, (double)spawnerPlacement.Spot.ZCm / 100.0, (double)spawnerPlacement.Spot.FacingCentiDeg / 100.0); } GUI.enabled = true; if (GUILayout.Button("Move…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(70f) }) && MoveSpawnerWithTool != null) { MoveSpawnerWithTool(spawnerPlacement.PlacementId, spawnerPlacement.SpawnerId); } if (GUILayout.Button("Remove from world", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) })) { _admin.RemoveSpawner(spawnerPlacement.PlacementId); } if (spawnerPlacement.Alive > 0 && GUILayout.Button("Remove its creatures", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _admin.ClearCreatures((CreatureClearScope)1, spawnerPlacement.PlacementId); } GUILayout.EndHorizontal(); } if (_admin.SpawnerPlacements.Count == 0) { GUILayout.Label("No spawner has been placed yet.", Array.Empty<GUILayoutOption>()); } } private void PicturesSection() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Invalid comparison between Unknown and I4 //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Invalid comparison between Unknown and I4 //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) PictureRun pictures = _admin.Pictures; if (_picturesAsked.Length > 0 && !pictures.Busy) { RuneSkin.Line(_picturesAsked, RuneSkin.Amber); GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); GUI.enabled = _superAdmin; if (GUILayout.Button("Take pictures", RuneSkin.Or(RuneSkin.Primary, GUI.skin.button), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) })) { _picturesAsked = string.Empty; pictures.Start(); } GUI.enabled = true; if (GUILayout.Button("Not now", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(100f) })) { _picturesAsked = string.Empty; } GUILayout.EndHorizontal(); GUILayout.Space(8f); } GUILayout.Label("The browser editor on the server machine shows a picture of each creature, item, building piece and object. The server has no graphics, so your game takes them and sends them. It takes a few minutes; you can keep playing.", RuneSkin.Or(RuneSkin.Aside, GUI.skin.label), Array.Empty<GUILayoutOption>()); GUI.enabled = !pictures.Busy; GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>()); pictures.Creatures = GUILayout.Toggle(pictures.Creatures, "Creatures & characters", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Items = GUILayout.Toggle(pictures.Items, "Items", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Pieces = GUILayout.Toggle(pictures.Pieces, "Building pieces", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.Objects = GUILayout.Toggle(pictures.Objects, "Objects", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.ExpandWidth(false) }); pictures.RetakeAll = GUILayout.Toggle(pictures.RetakeAll, "Take again the ones the server has", (GUILayoutOption[])
plugins/attestation/0.61.0/player/ALIVE.Core.dll.attest
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; 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.Versioning; using System.Security; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using ALIVE.Core.Abstractions; using ALIVE.Core.Client.Editing; using ALIVE.Core.Content; using ALIVE.Core.Content.Conditions; using ALIVE.Core.Content.Creatures; using ALIVE.Core.Content.Currencies; using ALIVE.Core.Content.Dialogue; using ALIVE.Core.Content.Economy; using ALIVE.Core.Content.Effects; using ALIVE.Core.Content.Ids; using ALIVE.Core.Content.Json; using ALIVE.Core.Content.Loading; using ALIVE.Core.Content.Mods; using ALIVE.Core.Content.Npcs; using ALIVE.Core.Content.Packs; using ALIVE.Core.Content.Pricing; using ALIVE.Core.Content.Quests; using ALIVE.Core.Content.Schema; using ALIVE.Core.Content.Shops; using ALIVE.Core.Content.Trades; using ALIVE.Core.Content.Validation; using ALIVE.Core.Diagnostics; using ALIVE.Core.Economy; using ALIVE.Core.Places; using ALIVE.Core.Protocol; using ALIVE.Core.Protocol.Messages; using ALIVE.Core.Storage; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Linq; [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("Valheim ALIVE")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.61.0.0")] [assembly: AssemblyInformationalVersion("0.61.0")] [assembly: AssemblyProduct("Valheim ALIVE")] [assembly: AssemblyTitle("ALIVE.Core")] [assembly: InternalsVisibleTo("ALIVE.Core.Tests")] [assembly: AssemblyVersion("0.61.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } } namespace ALIVE.Core { public static class AliveCoreVersion { public static readonly string Value = ReadFromAssembly(); private static string ReadFromAssembly() { return typeof(AliveCoreVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0"; } } public static class AliveGuid { public const string Server = "com.imaginaryrealms.alive.server"; public const string Player = "com.imaginaryrealms.alive.client.player"; public const string Admin = "com.imaginaryrealms.alive.client.admin"; public static bool IsPlayer(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.player"); } return true; } public static bool IsAdmin(string? id) { if (!Is(id, "com.imaginaryrealms.alive.client.admin")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } public static bool IsAlive(string? id) { if (!IsPlayer(id) && !IsAdmin(id) && !Is(id, "com.imaginaryrealms.alive.server")) { return Is(id, "net.winterwolf.alive.server"); } return true; } public static bool IsOld(string? id) { if (!Is(id, "net.winterwolf.alive.server") && !Is(id, "net.winterwolf.alive.client.player")) { return Is(id, "net.winterwolf.alive.client.admin"); } return true; } private static bool Is(string? id, string guid) { return string.Equals(id, guid, StringComparison.Ordinal); } } public static class AliveOldGuid { public const string Server = "net.winterwolf.alive.server"; public const string Player = "net.winterwolf.alive.client.player"; public const string Admin = "net.winterwolf.alive.client.admin"; } public static class SettingsCarry { public static string? FromOldId(string configFolder, string oldId, string newId) { if (string.IsNullOrEmpty(configFolder) || string.IsNullOrEmpty(oldId) || string.IsNullOrEmpty(newId)) { return null; } string text = Path.Combine(configFolder, newId + ".cfg"); string text2 = Path.Combine(configFolder, oldId + ".cfg"); if (File.Exists(text) || !File.Exists(text2)) { return null; } File.Copy(text2, text, overwrite: false); return "settings carried over from " + oldId + ".cfg to " + newId + ".cfg, as ALIVE's id changed in 0.61.0. The old file is no longer read and may be deleted."; } } public static class OldCopies { public static readonly Version FirstWithNewIds = new Version(0, 61, 0); private static readonly string[] PluginFiles = new string[3] { "ALIVE.Server.dll", "ALIVE.Client.Player.dll", "ALIVE.Client.Admin.dll" }; public static IReadOnlyList<string> Find(string pluginFolder, Func<string, Version?> versionOf) { if (versionOf == null) { throw new ArgumentNullException("versionOf"); } List<string> list = new List<string>(); if (string.IsNullOrEmpty(pluginFolder) || !Directory.Exists(pluginFolder)) { return list; } string[] pluginFiles = PluginFiles; foreach (string searchPattern in pluginFiles) { IEnumerable<string> files; try { files = Directory.GetFiles(pluginFolder, searchPattern, SearchOption.AllDirectories); } catch (Exception ex) when (ex is UnauthorizedAccessException || ex is IOException) { continue; } foreach (string item in files) { Version version = versionOf(item); if (version != null && version < FirstWithNewIds) { list.Add(item); } } } list.Sort(StringComparer.OrdinalIgnoreCase); return list; } public static Version? VersionOfFile(string path) { try { return AssemblyName.GetAssemblyName(path).Version; } catch (Exception ex) when (ex is IOException || ex is BadImageFormatException || ex is UnauthorizedAccessException || ex is ArgumentException || ex is SecurityException) { return null; } } public static string Refusal(string plugin, string version, IReadOnlyList<string> copies) { return plugin + " " + version + " is not starting: an older copy of ALIVE (from before 0.61.0, when its id was net.winterwolf.alive.*) is still in BepInEx/plugins: " + string.Join("; ", copies ?? Array.Empty<string>()) + ". Delete that copy's folder, keep the one your mod manager installed, and start again."; } } public static class AliveNames { public const string Server = "ALIVE Server"; public const string Player = "ALIVE Player"; public const string Admin = "ALIVE Admin"; } public static class AliveWorld { public const string Prefab = "ALIVE_Signpost"; public const string BasePrefab = "piece_banner01"; public const string FallbackPrefab = "sign"; public const string PersonPrefab = "ALIVE_Villager"; public const string PersonBase = "Player"; public const string ModelPrefab = "ALIVE_Model"; public const string ModelBase = "piece_chest_wood"; public const string DvergrShape = "Dverger"; public const string ShapeKey = "alive_shape"; public const string TillPrefab = "ALIVE_Till"; public const string TillBase = "piece_chest_wood"; public const string TillKey = "alive_till"; public const int TillWidth = 8; public const int TillHeight = 4; public const string SubtitleKey = "alive_subtitle"; public const string ModelKey = "alive_model"; public const string HairKey = "alive_hair"; public const string BeardKey = "alive_beard"; public const string SkinKey = "alive_skin"; public const string HairColorKey = "alive_hair_color"; public const string ScaleKey = "alive_scale"; public const string FaceKey = "alive_face"; public const string EquipmentKeyPrefix = "alive_eq_"; public const string EquipmentColorKeyPrefix = "alive_eqc_"; public const string NpcKey = "alive_npc"; public const string NameKey = "alive_name"; public const string PromptKey = "alive_prompt"; public const string HoverKey = "alive_hover"; public const string NoUseKey = "alive_nouse"; public const string LifeKey = "alive_life"; public const string LifeKey2 = "alive_life2"; public const string LifeKey3 = "alive_life3"; public const string LifeKey4 = "alive_life4"; public const string HomeKey = "alive_home"; public const string HomeTurnKey = "alive_home_turn"; public const string LabelShowKey = "alive_label"; public const string LabelTextKey = "alive_label_text"; public const string LabelSubKey = "alive_label_sub"; public const string LabelColorKey = "alive_label_color"; public const string LabelSubColorKey = "alive_label_subcolor"; public const string LabelSizeKey = "alive_label_size"; public const string LabelHeightKey = "alive_label_height"; public const string LabelRangeKey = "alive_label_range"; public const string LabelStyleKey = "alive_label_style"; public const int LabelBold = 1; public const int LabelItalic = 2; public const int LabelOutline = 4; public const string PlacementKey = "alive_placement"; public const string HammerPrefab = "ALIVE_NpcHammer"; public const string HammerBase = "Hammer"; public const string BoardPiecePrefab = "ALIVE_JobBoard"; public const string BoardPieceBase = "sign"; public const string CreatureKey = "alive_creature"; public const string CreatureSpawnKey = "alive_spawn"; public const string CreatureFirstKey = "alive_cr_uid"; public const string CreatureDamageKey = "alive_cr_damage"; public const string CreatureScaleKey = "alive_cr_scale"; public const string CreatureResistKey = "alive_cr_resist"; public const string CreatureFactionKey = "alive_cr_faction"; public const string CreaturePassiveKey = "alive_cr_passive"; public const string CreatureAngryKey = "alive_cr_angry"; public const string CreatureNoDropsKey = "alive_cr_nodrops"; public const string CreatureColorsKey = "alive_cr_colors"; public const string AltarKey = "alive_altar"; public const string SentryKey = "alive_sentry"; public const string FightKey = "alive_fight"; public const string FightWithKey = "alive_fight_with"; public const string DownKey = "alive_down_until"; public const string SentryHealthKey = "alive_sentry_hp"; public const string SentryRestKey = "alive_sentry_rest"; public const string SentryPrefab = "ALIVE_Sentry"; public const string CreatureNoEliteKey = "alive_cr_noelite"; public const string SentryOfKey = "alive_sentry_of"; public const string FightFromKey = "alive_fight_from"; public const string FightKitKey = "alive_fight_kit"; public const string FightDoneKey = "alive_fight_done"; } } namespace ALIVE.Core.Web { public sealed class LocalHttpServer : IDisposable { public const int MaxHeadBytes = 16384; public const int MaxBodyBytes = 4194304; public const int MaxConnections = 8; private const int TimeoutMs = 15000; private readonly Func<LocalRequest, LocalResponse> _handle; private readonly IAliveLog _log; private TcpListener? _listener; private int _open; private volatile bool _stopping; private static readonly string[] LineBreak = new string[1] { "\r\n" }; public int Port { get; private set; } public LocalHttpServer(Func<LocalRequest, LocalResponse> handle, IAliveLog log) { _handle = handle ?? throw new ArgumentNullException("handle"); _log = log ?? throw new ArgumentNullException("log"); } public void Start(int port) { if (_listener != null) { throw new InvalidOperationException("The editor's server is already listening."); } TcpListener tcpListener = new TcpListener(IPAddress.Loopback, port); tcpListener.Start(16); _listener = tcpListener; Port = ((IPEndPoint)tcpListener.LocalEndpoint).Port; Thread thread = new Thread(AcceptLoop); thread.IsBackground = true; thread.Name = "ALIVE web editor"; thread.Start(); } public void Dispose() { _stopping = true; try { _listener?.Stop(); } catch (SocketException) { } _listener = null; } private void AcceptLoop() { while (!_stopping) { TcpClient client; try { TcpListener listener = _listener; if (listener == null) { break; } client = listener.AcceptTcpClient(); } catch (Exception) when (_stopping) { break; } catch (Exception ex2) { _log.Warning("ALIVE web editor: a connection could not be taken: " + ex2.Message); continue; } if (Interlocked.Increment(ref _open) > 8) { Interlocked.Decrement(ref _open); client.Close(); } else { ThreadPool.QueueUserWorkItem(delegate { Serve(client); }); } } } private void Serve(TcpClient client) { try { client.ReceiveTimeout = 15000; client.SendTimeout = 15000; using (client) { using NetworkStream stream = client.GetStream(); string refusal; LocalRequest localRequest = Read(stream, out refusal); LocalResponse response; if (localRequest == null) { response = LocalResponse.Text(400, refusal ?? "That request could not be read."); } else { try { response = _handle(localRequest); } catch (Exception exception) { _log.Failure("ALIVE web editor: answering " + localRequest.Method + " " + localRequest.Path + " failed.", exception); response = LocalResponse.Text(500, "Something went wrong on the server; its log says what."); } } Write(stream, response); } } catch (IOException) { } catch (SocketException) { } catch (ObjectDisposedException) { } finally { Interlocked.Decrement(ref _open); } } public static LocalRequest? Read(Stream stream, out string? refusal) { refusal = null; List<byte> list = new List<byte>(1024); checked { while (!EndsTheHead(list)) { int num = stream.ReadByte(); if (num < 0) { refusal = "The request ended early."; return null; } list.Add((byte)num); if (list.Count > 16384) { refusal = "The request's headers are too long."; return null; } } string[] array = Encoding.ASCII.GetString(list.ToArray(), 0, list.Count - 4).Split(LineBreak, StringSplitOptions.None); string[] array2 = array[0].Split(new char[1] { ' ' }); if (array2.Length != 3 || !array2[2].StartsWith("HTTP/1.", StringComparison.Ordinal)) { refusal = "That is not an HTTP request."; return null; } Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); for (int i = 1; i < array.Length; i++) { int num2 = array[i].IndexOf(':'); if (num2 > 0) { string key = array[i].Substring(0, num2).Trim(); string text = array[i].Substring(num2 + 1).Trim(); dictionary[key] = (dictionary.TryGetValue(key, out var value) ? (value + ", " + text) : text); } } int result = 0; if (dictionary.TryGetValue("Content-Length", out var value2) && (!int.TryParse(value2, NumberStyles.None, CultureInfo.InvariantCulture, out result) || result > 4194304)) { refusal = "The request's body is too large."; return null; } if (dictionary.ContainsKey("Transfer-Encoding")) { refusal = "Chunked requests are not taken; send a Content-Length."; return null; } byte[] array3 = new byte[result]; int num3; for (int j = 0; j < result; j += num3) { num3 = stream.Read(array3, j, result - j); if (num3 <= 0) { refusal = "The request's body ended early."; return null; } } string text2 = array2[1]; int num4 = text2.IndexOf('?'); string stringToUnescape = ((num4 < 0) ? text2 : text2.Substring(0, num4)); return new LocalRequest(array2[0].ToUpperInvariant(), Uri.UnescapeDataString(stringToUnescape), Query((num4 < 0) ? string.Empty : text2.Substring(num4 + 1)), dictionary, Encoding.UTF8.GetString(array3)); } } private static bool EndsTheHead(List<byte> head) { int count = head.Count; checked { if (count >= 4 && head[count - 4] == 13 && head[count - 3] == 10 && head[count - 2] == 13) { return head[count - 1] == 10; } return false; } } private static Dictionary<string, string> Query(string query) { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.Ordinal); string[] array = query.Split(new char[1] { '&' }); foreach (string text in array) { if (text.Length != 0) { int num = text.IndexOf('='); string key = Uri.UnescapeDataString(((num < 0) ? text : text.Substring(0, num)).Replace('+', ' ')); string value = ((num < 0) ? string.Empty : Uri.UnescapeDataString(text.Substring(checked(num + 1)).Replace('+', ' '))); dictionary[key] = value; } } return dictionary; } private static void Write(Stream stream, LocalResponse response) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("HTTP/1.1 ").Append(response.Status.ToString(CultureInfo.InvariantCulture)).Append(' ') .Append(Reason(response.Status)) .Append("\r\n"); stringBuilder.Append("Content-Type: ").Append(response.ContentType).Append("\r\n"); stringBuilder.Append("Content-Length: ").Append(response.Bytes.Length.ToString(CultureInfo.InvariantCulture)).Append("\r\n"); stringBuilder.Append("Connection: close\r\n"); if (!response.Headers.ContainsKey("Cache-Control")) { stringBuilder.Append("Cache-Control: no-store\r\n"); } stringBuilder.Append("X-Content-Type-Options: nosniff\r\n"); stringBuilder.Append("X-Frame-Options: DENY\r\n"); stringBuilder.Append("Referrer-Policy: no-referrer\r\n"); stringBuilder.Append("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; form-action 'self'\r\n"); foreach (KeyValuePair<string, string> header in response.Headers) { stringBuilder.Append(header.Key).Append(": ").Append(header.Value) .Append("\r\n"); } stringBuilder.Append("\r\n"); byte[] bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString()); stream.Write(bytes, 0, bytes.Length); stream.Write(response.Bytes, 0, response.Bytes.Length); stream.Flush(); } private static string Reason(int status) { return status switch { 200 => "OK", 303 => "See Other", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 409 => "Conflict", 413 => "Payload Too Large", 415 => "Unsupported Media Type", 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Error", }; } } public sealed class LocalRequest { public string Method { get; } public string Path { get; } public IReadOnlyDictionary<string, string> Query { get; } public IReadOnlyDictionary<string, string> Headers { get; } public string Body { get; } public LocalRequest(string method, string path, IReadOnlyDictionary<string, string> query, IReadOnlyDictionary<string, string> headers, string body) { Method = method; Path = path; Query = query; Headers = headers; Body = body; } public string Header(string name) { if (!Headers.TryGetValue(name, out string value)) { return string.Empty; } return value; } public string Cookie(string name) { string[] array = Header("Cookie").Split(new char[1] { ';' }); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && string.Equals(text.Substring(0, num).Trim(), name, StringComparison.Ordinal)) { return text.Substring(checked(num + 1)).Trim(); } } return string.Empty; } } public sealed class LocalResponse { public int Status { get; } public string ContentType { get; } public byte[] Bytes { get; } public Dictionary<string, string> Headers { get; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public LocalResponse(int status, string contentType, byte[] body) { Status = status; ContentType = contentType; Bytes = body ?? Array.Empty<byte>(); } public static LocalResponse Text(int status, string text) { return new LocalResponse(status, "text/plain; charset=utf-8", Encoding.UTF8.GetBytes(text ?? string.Empty)); } public static LocalResponse Json(int status, string json) { return new LocalResponse(status, "application/json; charset=utf-8", Encoding.UTF8.GetBytes(json ?? "{}")); } public static LocalResponse Html(int status, string html) { return new LocalResponse(status, "text/html; charset=utf-8", Encoding.UTF8.GetBytes(html ?? string.Empty)); } } public static class LoopbackGate { public enum Verdict { WrongHost, OtherOrigin, ChangeFromElsewhere, Opening, Locked, Through } public const string KeyCookie = "alive_key"; public const string OpeningPage = "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"; public static Verdict Check(LocalRequest request, int port, string key) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrEmpty(key)) { return Verdict.Locked; } string text = port.ToString(CultureInfo.InvariantCulture); string a = request.Header("Host"); if (!string.Equals(a, "127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) && !string.Equals(a, "localhost:" + text, StringComparison.OrdinalIgnoreCase)) { return Verdict.WrongHost; } string text2 = request.Header("Origin"); bool flag = string.Equals(text2, "http://127.0.0.1:" + text, StringComparison.OrdinalIgnoreCase) || string.Equals(text2, "http://localhost:" + text, StringComparison.OrdinalIgnoreCase); if (text2.Length > 0 && !flag) { return Verdict.OtherOrigin; } if (!IsRead(request) && !flag) { return Verdict.ChangeFromElsewhere; } if (request.Path == "/" && request.Query.TryGetValue("key", out string value)) { if (!Same(value, key)) { return Verdict.Locked; } return Verdict.Opening; } if (!Same(request.Cookie("alive_key"), key)) { return Verdict.Locked; } return Verdict.Through; } public static bool IsRead(LocalRequest request) { if (request != null) { if (!(request.Method == "GET")) { return request.Method == "HEAD"; } return true; } return false; } public static LocalResponse Opened(string key) { LocalResponse localResponse = LocalResponse.Html(200, "<!doctype html><meta charset=\"utf-8\"><title>ALIVE editor</title><meta http-equiv=\"refresh\" content=\"0; url=/\"><script>location.replace(\"/\");</script><body style=\"font-family:sans-serif;background:#16130f;color:#e8dcc4;padding:40px\"><p>Opening the editor. If nothing happens, <a href=\"/\" style=\"color:#d9b45a\">open it here</a>.</p></body>"); localResponse.Headers["Set-Cookie"] = "alive_key=" + key + "; Path=/; HttpOnly; SameSite=Strict"; return localResponse; } public static string Link(int port, string key) { return "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture) + "/?key=" + key; } public static bool Same(string? a, string b) { if (a == null || b == null || a.Length != b.Length) { return false; } int num = 0; for (int i = 0; i < a.Length; i = checked(i + 1)) { num |= a[i] ^ b[i]; } return num == 0; } } } namespace ALIVE.Core.Storage { public enum ActivityCategory { Session, Shop, Quest, Dialogue, Economy, Admin, Anticheat, Npc } public sealed class ActivityEntry { public const int MaxDetailChars = 512; public const int MaxSubjectChars = 128; public const int MaxEventChars = 64; public long AtUnixMs { get; init; } public string PlatformId { get; init; } = string.Empty; public ActivityCategory Category { get; init; } public string Event { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string SubjectSub { get; init; } = string.Empty; public string Detail { get; init; } = string.Empty; public int Outcome { get; init; } public int? PosX { get; init; } public int? PosZ { get; init; } public string Correlation { get; init; } = string.Empty; public int Severity { get; init; } } public sealed class ActivityRecord { public long ActivityId { get; } public ActivityEntry Entry { get; } public ActivityRecord(long activityId, ActivityEntry entry) { ActivityId = activityId; Entry = entry ?? throw new ArgumentNullException("entry"); } } public enum TextMatch { None, Exact, Prefix, Contains } public sealed class ActivityQuery { public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public string PlatformId { get; init; } = string.Empty; public uint Categories { get; init; } public string Text { get; init; } = string.Empty; public TextMatch Match { get; init; } public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public enum PendingOpState { Pending, Approved, Rejected, Expired, Applied } public sealed class NewPendingOp { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class PendingOpRecord { public string OpId { get; init; } = string.Empty; public string Action { get; init; } = string.Empty; public string Requester { get; init; } = string.Empty; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string PayloadJson { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public PendingOpState State { get; init; } public string Approver { get; init; } = string.Empty; public string DecideNote { get; init; } = string.Empty; public long CreatedMs { get; init; } public long ExpiresMs { get; init; } public long? DecidedMs { get; init; } } public enum DecideOutcome { Ok, NotFound, AlreadyDecided, Expired, SelfApproval } public sealed class DecideResult { public DecideOutcome Outcome { get; } public PendingOpRecord? Op { get; } public DecideResult(DecideOutcome outcome, PendingOpRecord? op) { Outcome = outcome; Op = op; } } public sealed class QuestDenialRecord { public string PlatformId { get; } public string QuestId { get; } public long? UntilMs { get; } public string Reason { get; } public string Actor { get; } public long CreatedMs { get; } public QuestDenialRecord(string platformId, string questId, long? untilMs, string reason, string actor, long createdMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); QuestId = questId ?? throw new ArgumentNullException("questId"); UntilMs = untilMs; Reason = reason ?? string.Empty; Actor = actor ?? string.Empty; CreatedMs = createdMs; } public bool AppliesAt(long nowMs) { if (UntilMs.HasValue) { return UntilMs.Value > nowMs; } return true; } } public enum AuditTier { System, Super, Admin, Player } public sealed class AuditEntry { public const int MaxSnapshotChars = 4096; public DateTime AtUtc { get; init; } public string Actor { get; init; } = string.Empty; public AuditTier Tier { get; init; } public string Action { get; init; } = string.Empty; public string Permission { get; init; } = string.Empty; public bool Granted { get; init; } = true; public string SubjectKind { get; init; } = string.Empty; public string SubjectId { get; init; } = string.Empty; public string Before { get; init; } = string.Empty; public string After { get; init; } = string.Empty; public string Reason { get; init; } = string.Empty; public string CorrelationId { get; init; } = string.Empty; } public sealed class AuditRecord { public long AuditId { get; } public AuditEntry Entry { get; } public string RowHash { get; } public AuditRecord(long auditId, AuditEntry entry, string rowHash) { AuditId = auditId; Entry = entry ?? throw new ArgumentNullException("entry"); RowHash = rowHash ?? throw new ArgumentNullException("rowHash"); } } public sealed class AuditVerification { public bool Intact => !FirstBrokenId.HasValue; public long Rows { get; } public long? FirstBrokenId { get; } public string Detail { get; } public AuditVerification(long rows, long? firstBrokenId, string detail) { Rows = rows; FirstBrokenId = firstBrokenId; Detail = detail; } } public static class AuditHash { public static byte[] Genesis => new byte[32]; public static byte[] Compute(byte[] previous, long auditId, AuditEntry e) { if (previous == null || previous.Length != 32) { throw new ArgumentException("The previous hash must be 32 bytes.", "previous"); } if (e == null) { throw new ArgumentNullException("e"); } string[] array = new string[13] { auditId.ToString(CultureInfo.InvariantCulture), e.AtUtc.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), e.Actor, TierName(e.Tier), e.Action, e.Permission, e.Granted ? "1" : "0", e.SubjectKind, e.SubjectId, e.Before, e.After, e.Reason, e.CorrelationId }; using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(previous, 0, 32, null, 0); string[] array2 = array; foreach (string s in array2) { byte[] bytes = Encoding.UTF8.GetBytes(s); byte[] bytes2 = BitConverter.GetBytes(checked((uint)bytes.Length)); if (!BitConverter.IsLittleEndian) { Array.Reverse((Array)bytes2); } sHA.TransformBlock(bytes2, 0, 4, null, 0); sHA.TransformBlock(bytes, 0, bytes.Length, null, 0); } sHA.TransformFinalBlock(Array.Empty<byte>(), 0, 0); return sHA.Hash; } public static string TierName(AuditTier tier) { return tier switch { AuditTier.Super => "SUPER", AuditTier.Admin => "ADMIN", AuditTier.Player => "PLAYER", _ => "SYSTEM", }; } public static bool TryParseTier(string name, out AuditTier tier) { switch (name) { case "SUPER": tier = AuditTier.Super; return true; case "ADMIN": tier = AuditTier.Admin; return true; case "SYSTEM": tier = AuditTier.System; return true; case "PLAYER": tier = AuditTier.Player; return true; default: tier = AuditTier.System; return false; } } } public sealed class SpawnerPlacementRecord { public long PlacementId { get; init; } public string SpawnerId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } public long LastSpawnMs { get; init; } public string SpotKey { get; init; } = string.Empty; } public static class CreatureSpawnKinds { public const string Hand = "hand"; public const string Spawner = "spawner"; public const string Altar = "altar"; public const string Encounter = "encounter"; } public static class CreatureStates { public const string Alive = "alive"; public const string Dead = "dead"; public const string Removed = "removed"; public const string Gone = "gone"; } public sealed class AliveCreatureRecord { public string Uid { get; init; } = string.Empty; public string CreatureId { get; init; } = string.Empty; public string SpawnKind { get; init; } = string.Empty; public long PlacementId { get; init; } public string QuestId { get; init; } = string.Empty; public string Step { get; init; } = string.Empty; public string OwnerPlatformId { get; init; } = string.Empty; public string State { get; init; } = "alive"; public long SpawnedMs { get; init; } public long LastNearMs { get; init; } public long ExpiresMs { get; init; } public double X { get; init; } public double Y { get; init; } public double Z { get; init; } } public enum GrantState { Pending = 1, Offered, Delivered, Mailbox, Stalled, Expired } public static class GrantReasons { public const byte QuestReward = 1; public const byte AdminGift = 2; public const byte Purchase = 3; public const byte Barter = 4; public const byte Withdrawal = 5; public const byte Returned = 6; public const byte Sale = 7; public const byte Effect = 8; } public sealed class GrantItem { public string Prefab { get; init; } = string.Empty; public int Count { get; init; } = 1; public int Quality { get; init; } = 1; public int Variant { get; init; } } public sealed class NewGrant { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public long CreatedMs { get; init; } public long ExpiresMs { get; init; } } public sealed class GrantRecord { public string GrantId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public byte Reason { get; init; } public string SourceKind { get; init; } = string.Empty; public string SourceId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public IReadOnlyList<GrantItem> Items { get; init; } = Array.Empty<GrantItem>(); public GrantState State { get; init; } public int Attempts { get; init; } public long CreatedMs { get; init; } public long UpdatedMs { get; init; } public long ExpiresMs { get; init; } public string Detail { get; init; } = string.Empty; } public interface IAliveStore : IDisposable { int SchemaVersion { get; } string EngineDescription { get; } void RecordContentLoad(ContentLoadRecord record); IReadOnlyList<ContentLoadRecord> RecentContentLoads(int max); AuditRecord AppendAudit(AuditEntry entry); AuditVerification VerifyAudit(); IReadOnlyList<AuditRecord> RecentAudit(int max); PlayerRecord RecordSessionStart(string platformId, string characterName, long nowMs); void RecordSessionEnd(string platformId, long nowMs); PlayerRecord? FindPlayer(string platformId); IReadOnlyList<PlayerRecord> SearchPlayers(PlayerQuery query); long AppendActivity(ActivityEntry entry); IReadOnlyList<ActivityRecord> SearchActivity(ActivityQuery query); PostResult Post(IReadOnlyList<LedgerPosting> legs, IReadOnlyDictionary<string, LedgerBounds> bounds, IReadOnlyList<ActivityEntry> activity, long nowMs); long Balance(string platformId, string currencyId); IReadOnlyList<WalletRecord> Wallets(string platformId); (int Players, long Total) CurrencyHeld(string currencyId); IReadOnlyList<LedgerRecord> SearchLedger(LedgerQuery query); IReadOnlyList<LedgerRecord> LedgerGroup(string groupId); bool WalletReconciles(string platformId, string currencyId); ReconcileReport Reconcile(long nowMs); QuestInstanceRecord? CreateQuestInstance(NewQuestInstance instance); bool SaveJobPosting(JobPosting posting); JobPosting? LatestJobPosting(long placedId); bool MarkJobHanded(long instanceId, long morning); int JobsHandedSince(string platformId, long fromMorning); int JobsHandedOn(string platformId, long morning); IReadOnlyList<KeyValuePair<string, string>> JobTakers(long placedId, long posting); void RetireJobPostings(long placedId); void StartJobTravel(long instanceId); void SaveJobTravel(long instanceId, double countedMetres); void FreezeJobTravel(long instanceId, double countedMetres, long doneMs); JobTravelRow? JobTravel(long instanceId); IReadOnlyList<JobTravelRow> OpenJobTravel(); bool AddJobDone(string platformId, string boardKey, long nowMs); int JobsDone(string platformId, string boardKey); bool FillJobDoneOnce(IReadOnlyDictionary<long, string> boardKeyByPlacedId, long nowMs); QuestInstanceRecord? QuestInstance(long instanceId); QuestInstanceRecord? OpenQuestInstance(string platformId, string questId); IReadOnlyList<QuestInstanceRecord> SearchQuestInstances(QuestInstanceQuery query); QuestWipe WipeQuest(string platformId, string questId, string note, long nowMs); QuestInstanceRecord ApplyQuestTransition(QuestTransition transition); IReadOnlyList<QuestEventRecord> QuestEvents(long instanceId, int max); bool SetQuestClock(long instanceId, QuestClock clock); bool ClaimObjectiveEffects(string platformId, string questId, string objectiveId, long nowMs, long windowMs); NpcPlacementRecord AddPlacement(NewNpcPlacement placement); IReadOnlyList<NpcPlacementRecord> Placements(bool includeRemoved = false); NpcPlacementRecord? Placement(long placementId); void SetPlacementObject(long placementId, string zdoId, long nowMs); bool MovePlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemovePlacement(long placementId, long nowMs); SpawnerPlacementRecord AddSpawnerPlacement(string spawnerId, string label, double x, double y, double z, double rotY, string placedBy, long nowMs); IReadOnlyList<SpawnerPlacementRecord> SpawnerPlacements(); SpawnerPlacementRecord? SpawnerPlacement(long placementId); bool MoveSpawnerPlacement(long placementId, double x, double y, double z, double rotY, long nowMs); bool RemoveSpawnerPlacement(long placementId); int RemoveSpawnerPlacements(string spawnerId); void SetSpawnerPlacementObject(long placementId, string zdoId, long nowMs); void SetSpawnerPlacementSpawned(long placementId, long nowMs); bool SetSpawnerPlacementSpot(long placementId, string spotKey, long nowMs); void AddAliveCreature(AliveCreatureRecord creature); IReadOnlyList<AliveCreatureRecord> AliveCreatures(); AliveCreatureRecord? AliveCreature(string uid); void SeeAliveCreature(string uid, double x, double y, double z, long lastNearMs); bool RenameAliveCreature(string uid, string newUid); bool EndAliveCreature(string uid, string state, long nowMs); int PurgeEndedCreatures(long endedBeforeMs); GrantRecord AddGrant(NewGrant grant); GrantRecord? Grant(string grantId); IReadOnlyList<GrantRecord> Grants(string platformId, IReadOnlyList<GrantState> states, int limit = 200); int CountGrantsFrom(string sourceKind, string sourceIdPrefix); bool MoveGrant(string grantId, GrantState fromState, GrantState toState, long nowMs, bool countAttempt, string detail); ShopStockRecord? ShopStock(string shopId, string entryId); bool SetShopStock(ShopStockRecord stock, long? expectedRestockedMs); long ShopCredit(string platformId, string shopId); int ShopTradeCount(string platformId, ShopTradeKind kind, string refId, long sinceMs); long LastShopTradeMs(string platformId, ShopTradeKind kind, string refId); bool ApplyPlayerState(PlayerStateChange change); string? RewardRolls(string groupId); bool HasFlag(string platformId, string flagId); void AddCounters(string platformId, IReadOnlyDictionary<string, long> deltas, long atMs); IReadOnlyList<string> Flags(string platformId); IReadOnlyList<HeldFlag> FlagsHeld(string platformId); IReadOnlyList<string> ClearFlags(string platformId, IReadOnlyList<string>? flags); bool GiveFlag(string platformId, string flagId, long atMs); long SetCounter(string platformId, string counterId, long value); IReadOnlyList<KeyValuePair<string, long>> CountersOf(string platformId, string prefix, int most); IReadOnlyList<HeldName> HeldFlags(); IReadOnlyList<HeldName> HeldCounters(string prefix); int CountFlagHolders(string flagId); int CountCounterHolders(string counterId); IReadOnlyList<string> ClearFlagEverywhere(string flagId); IReadOnlyList<string> ClearCounterEverywhere(string counterId); bool DeleteServerSwitch(string switchId); int ForgetPlayerState(string platformId, IReadOnlyList<string> counters, IReadOnlyList<string> counterPrefixes, IReadOnlyList<string> flags); bool ServerSwitchOn(string switchId); IReadOnlyList<ServerSwitchRecord> ServerSwitches(); void SetServerSwitch(string switchId, bool isOn, string actor, long nowMs); IReadOnlyList<string> EditorFolders(); bool AddEditorFolder(string folder, string madeBy, long atMs); bool RemoveEditorFolder(string folder); void RenameEditorFolder(string oldFolder, string newFolder); string? PlayerVar(string platformId, string varId); void SetPlayerVar(string platformId, string varId, string value, long atMs); int CountVarHolders(string varId); IReadOnlyList<string> ClearVarEverywhere(string varId); long Counter(string platformId, string counterId); int Relationship(string platformId, string npcId); void SetRelationship(string platformId, string id, int value, long nowMs); IReadOnlyList<RelationshipRow> RelationshipsWith(string id); int CountRelationshipsWith(string id); int ForgetRelationshipsWith(string id); bool HasUnlock(string platformId, byte kind, string reference); void SetRewardChoice(long instanceId, string platformId, int choice, long atMs); int? RewardChoice(long instanceId); int ShopTradeCountSinceGameDay(string platformId, ShopTradeKind kind, string refId, long fromGameDay); ShopCommitOutcome CommitShopTrade(ShopCommit commit); IReadOnlyDictionary<string, int> SoldByItem(string platformId, SellWindow window); IReadOnlyDictionary<string, int> SoldByItemAt(string platformId, string shopId, SellWindow window); long SoldValue(string platformId, SellWindow window); long MerchantPaid(string shopId, SellWindow window); void SetShopTradeGrant(string tradeId, string grantId); IReadOnlyList<ShopTradeRecord> UngrantedShopTrades(int limit); PendingOpRecord CreatePendingOp(NewPendingOp op); PendingOpRecord? PendingOp(string opId); DecideResult DecidePendingOp(string opId, string approver, bool approve, string note, long nowMs); void MarkPendingOpApplied(string opId, long nowMs); int ExpirePendingOps(long nowMs); void SetQuestDenial(string platformId, string questId, long? untilMs, string reason, string actor, long nowMs); bool ClearQuestDenial(string platformId, string questId); QuestDenialRecord? QuestDenial(string platformId, string questId); IReadOnlyList<QuestDenialRecord> QuestDenials(string platformId); IReadOnlyList<WorldRow> WorldPlaces(); long SaveWorldPlace(long id, string key, string body, string by, long nowMs); bool RemoveWorldPlace(long id); IReadOnlyList<WorldRow> WorldLocks(); long SaveWorldLock(long id, string uid, string body, string by, long nowMs); bool RemoveWorldLock(long id); IReadOnlyList<WorldRow> WorldObjects(); long SaveWorldObject(long id, string uid, string body, string by, long nowMs); bool RemoveWorldObject(long id); IReadOnlyList<WorldRow> WorldSpots(); long SaveWorldSpot(long id, string key, string body, string by, long nowMs); bool RemoveWorldSpot(long id); void RenameWorldThings(bool objects, IReadOnlyList<KeyValuePair<long, string>> names); bool LockOpened(long lockId, string platformId); void MarkLockOpened(long lockId, string platformId, long nowMs); long PlaceSeen(long placeId, string platformId); void MarkPlaceSeen(long placeId, string platformId, long nowMs); } public sealed class ContentLoadRecord { public DateTime AtUtc { get; } public IReadOnlyList<string> Packs { get; } public IReadOnlyList<string> FailedPacks { get; } public int Published { get; } public int Quarantined { get; } public int Errors { get; } public int Warnings { get; } public string ContentHash { get; } public ContentLoadRecord(DateTime atUtc, IReadOnlyList<string> packs, IReadOnlyList<string> failedPacks, int published, int quarantined, int errors, int warnings, string contentHash) { AtUtc = atUtc; Packs = packs ?? throw new ArgumentNullException("packs"); FailedPacks = failedPacks ?? throw new ArgumentNullException("failedPacks"); Published = published; Quarantined = quarantined; Errors = errors; Warnings = warnings; ContentHash = contentHash ?? throw new ArgumentNullException("contentHash"); } } public enum LedgerReason { ShopBuy = 1, ShopSell, Barter, QuestReward, AdminGrant, Decay, Refund, Reconcile, StartingBalance, Deposit, Withdrawal, Penalty, Effect } public enum LedgerSourceKind { None, Shop, Quest, TradeRecipe, Admin, System, Bank } public sealed class LedgerPosting { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long DeltaMinor { get; init; } public LedgerReason Reason { get; init; } public LedgerSourceKind SourceKind { get; init; } public string SourceId { get; init; } = string.Empty; public string SourceSub { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Note { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; } public sealed class LedgerRecord { public long TxnId { get; } public LedgerPosting Posting { get; } public long BalanceAfterMinor { get; } public long AtUnixMs { get; } public LedgerRecord(long txnId, LedgerPosting posting, long balanceAfterMinor, long atUnixMs) { TxnId = txnId; Posting = posting ?? throw new ArgumentNullException("posting"); BalanceAfterMinor = balanceAfterMinor; AtUnixMs = atUnixMs; } } public sealed class WalletRecord { public string PlatformId { get; } public string CurrencyId { get; } public long BalanceMinor { get; } public long LifetimeInMinor { get; } public long LifetimeOutMinor { get; } public long UpdatedMs { get; } public WalletRecord(string platformId, string currencyId, long balanceMinor, long lifetimeInMinor, long lifetimeOutMinor, long updatedMs) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); BalanceMinor = balanceMinor; LifetimeInMinor = lifetimeInMinor; LifetimeOutMinor = lifetimeOutMinor; UpdatedMs = updatedMs; } } public sealed class LedgerBounds { public long MinMinor { get; } public long MaxMinor { get; } public LedgerBounds(long minMinor, long maxMinor) { if (maxMinor < minMinor) { throw new ArgumentOutOfRangeException("maxMinor", maxMinor, "The ceiling is below the floor."); } MinMinor = minMinor; MaxMinor = maxMinor; } } public enum PostOutcome { Posted, AlreadyPosted, BelowFloor, AboveCeiling, UnknownPlayer, UnknownCurrency } public sealed class PostResult { public PostOutcome Outcome { get; } public bool Accepted { get { if (Outcome != PostOutcome.Posted) { return Outcome == PostOutcome.AlreadyPosted; } return true; } } public IReadOnlyList<LedgerRecord> Legs { get; } public string Detail { get; } public PostResult(PostOutcome outcome, IReadOnlyList<LedgerRecord> legs, string detail) { Outcome = outcome; Legs = legs ?? throw new ArgumentNullException("legs"); Detail = detail ?? string.Empty; } } public sealed class LedgerQuery { public string PlatformId { get; init; } = string.Empty; public string CurrencyId { get; init; } = string.Empty; public long FromMs { get; init; } public long ToMs { get; init; } = long.MaxValue; public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public sealed class WalletDiscrepancy { public string PlatformId { get; } public string CurrencyId { get; } public long WalletMinor { get; } public long LedgerMinor { get; } public WalletDiscrepancy(string platformId, string currencyId, long walletMinor, long ledgerMinor) { PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CurrencyId = currencyId ?? throw new ArgumentNullException("currencyId"); WalletMinor = walletMinor; LedgerMinor = ledgerMinor; } } public sealed class ReconcileReport { public int WalletsChecked { get; } public IReadOnlyList<WalletDiscrepancy> Repaired { get; } public bool Balanced => Repaired.Count == 0; public ReconcileReport(int walletsChecked, IReadOnlyList<WalletDiscrepancy> repaired) { WalletsChecked = walletsChecked; Repaired = repaired ?? throw new ArgumentNullException("repaired"); } } public sealed class NewNpcPlacement { public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } } public sealed class NpcPlacementRecord { public long PlacementId { get; init; } public string NpcId { get; init; } = string.Empty; public string Label { get; init; } = string.Empty; public double X { get; init; } public double Y { get; init; } public double Z { get; init; } public double RotY { get; init; } public string ZdoId { get; init; } = string.Empty; public bool Enabled { get; init; } = true; public string PlacedBy { get; init; } = string.Empty; public long PlacedMs { get; init; } public long UpdatedMs { get; init; } } public sealed class PlayerRecord { public long PlayerId { get; } public string PlatformId { get; } public string CharacterName { get; } public long FirstSeenMs { get; } public long LastSeenMs { get; } public long SessionCount { get; } public PlayerRecord(long playerId, string platformId, string characterName, long firstSeenMs, long lastSeenMs, long sessionCount) { PlayerId = playerId; PlatformId = platformId ?? throw new ArgumentNullException("platformId"); CharacterName = characterName ?? throw new ArgumentNullException("characterName"); FirstSeenMs = firstSeenMs; LastSeenMs = lastSeenMs; SessionCount = sessionCount; } } public enum PlayerQueryKind { PlatformId = 1, NamePrefix } public sealed class PlayerQuery { public PlayerQueryKind Kind { get; init; } = PlayerQueryKind.NamePrefix; public string Text { get; init; } = string.Empty; public string AlternateText { get; init; } = string.Empty; public string? AfterName { get; init; } public string AfterPlatformId { get; init; } = string.Empty; public int Limit { get; init; } = 50; } public static class UnlockKinds { public const byte Quest = 1; public const byte ShopEntry = 2; } public sealed class RelationshipRow { public string PlatformId { get; init; } = string.Empty; public int Value { get; init; } public long ChangedMs { get; init; } } public sealed class PlayerStateChange { public string GroupId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public IReadOnlyList<string> Flags { get; init; } = Array.Empty<string>(); public IReadOnlyList<string> ClearFlags { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, long> Counters { get; init; } = new Dictionary<string, long>(); public IReadOnlyDictionary<string, long> Relationships { get; init; } = new Dictionary<string, long>(); public IReadOnlyList<KeyValuePair<byte, string>> Unlocks { get; init; } = Array.Empty<KeyValuePair<byte, string>>(); public string Rolls { get; init; } = string.Empty; public long AtMs { get; init; } } public static class GrantPrefixes { public const string Skill = "@skill:"; public const string PovTree = "@pov:tree:"; public const string PovProfession = "@pov:prof:"; public static bool IsSkill(string? prefab) { return prefab?.StartsWith("@skill:", StringComparison.Ordinal) ?? false; } public static bool IsPov(string? prefab) { if (prefab != null) { if (!prefab.StartsWith("@pov:tree:", StringComparison.Ordinal)) { return prefab.StartsWith("@pov:prof:", StringComparison.Ordinal); } return true; } return false; } public static bool IsNotItem(string? prefab) { if (!IsSkill(prefab)) { return IsPov(prefab); } return true; } } public enum QuestState { NotOffered, Offered, Active, ReadyToTurnIn, Completed, Failed, Abandoned, Paused, Cooldown, Stale } public enum QuestEventKind { Offered, Accepted, Progress, ObjectiveDone, Ready, Completed, Failed, Abandoned, Paused, Resumed, Stale, Migrated, AdminAdjusted } public enum MigrationPolicy { Snapshot, FollowLive } public sealed class ObjectiveProgress { public string ObjectiveId { get; init; } = string.Empty; public long Current { get; init; } public long Required { get; init; } public long? CompletedMs { get; init; } public bool Optional { get; init; } public int OrderIndex { get; init; } public bool Revealed { get; init; } = true; public bool IsDone => CompletedMs.HasValue; } public static class QuestClockDomains { public const string None = ""; public const string Online = "online"; public const string Real = "real"; public const string World = "world"; } public static class QuestHolds { public const string None = ""; public const string Deadline = "deadline"; public const string Window = "window"; public const string Manual = "manual"; } public sealed class QuestClock { public static QuestClock Empty { get; } = new QuestClock(); public string Domain { get; init; } = ""; public long? DeadlineMs { get; init; } public long? LeftMs { get; init; } public long? WorldDeadlineS { get; init; } public string OnDeadline { get; init; } = string.Empty; public long GraceMs { get; init; } public long BudgetMs { get; init; } public string Hold { get; init; } = ""; public bool HasDeadline => Domain.Length > 0; public bool Running { get { if (!DeadlineMs.HasValue) { return WorldDeadlineS.HasValue; } return true; } } public QuestClock With(long? deadlineMs, long? leftMs, long? worldDeadlineS, string hold) { return new QuestClock { Domain = Domain, DeadlineMs = deadlineMs, LeftMs = leftMs, WorldDeadlineS = worldDeadlineS, OnDeadline = OnDeadline, GraceMs = GraceMs, BudgetMs = BudgetMs, Hold = (hold ?? "") }; } } public sealed class NewQuestInstance { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } = QuestState.Offered; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public QuestClock? Clock { get; init; } public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } } public sealed class JobTake { public string Board { get; init; } = string.Empty; public long PlacedId { get; init; } public long Posting { get; init; } public string BoardNpc { get; init; } = string.Empty; public string HandIn { get; init; } = string.Empty; public long? HandedMorning { get; init; } public string Rolled { get; init; } = string.Empty; } public sealed class JobPosting { public const long NeverDue = long.MinValue; public long PlacedId { get; init; } public long Number { get; init; } public long Due { get; init; } public long PostedMs { get; init; } public IReadOnlyList<string> Notices { get; init; } = Array.Empty<string>(); public IReadOnlyDictionary<string, string> Rolls { get; init; } = new Dictionary<string, string>(StringComparer.Ordinal); } public sealed class JobTravelRow { public long InstanceId { get; init; } public double CountedMetres { get; init; } public long? DoneMs { get; init; } } public sealed class QuestInstanceRecord { public long InstanceId { get; init; } public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public QuestState State { get; init; } public int Attempt { get; init; } = 1; public int DefinitionVersion { get; init; } public MigrationPolicy Policy { get; init; } public string Snapshot { get; init; } = string.Empty; public long? OfferedMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? LastProgressMs { get; init; } public long? CooldownUntilMs { get; init; } public bool Tracked { get; init; } = true; public string RewardGroupId { get; init; } = string.Empty; public string StaleReason { get; init; } = string.Empty; public QuestClock Clock { get; init; } = QuestClock.Empty; public IReadOnlyList<ObjectiveProgress> Objectives { get; init; } = Array.Empty<ObjectiveProgress>(); public JobTake? Job { get; init; } public bool IsOpen => QuestStates.IsOpen(State); } public sealed class QuestEventRecord { public long EventId { get; } public long InstanceId { get; } public QuestEventKind Kind { get; } public string Detail { get; } public string Actor { get; } public string Correlation { get; } public long AtUnixMs { get; } public QuestEventRecord(long eventId, long instanceId, QuestEventKind kind, string detail, string actor, string correlation, long atUnixMs) { EventId = eventId; InstanceId = instanceId; Kind = kind; Detail = detail ?? string.Empty; Actor = actor ?? string.Empty; Correlation = correlation ?? string.Empty; AtUnixMs = atUnixMs; } } public sealed class QuestTransition { public long InstanceId { get; init; } public QuestState State { get; init; } public QuestEventKind Kind { get; init; } public string Detail { get; init; } = string.Empty; public string Actor { get; init; } = string.Empty; public string Correlation { get; init; } = string.Empty; public long AtUnixMs { get; init; } public long? AcceptedMs { get; init; } public long? DeadlineMs { get; init; } public long? CompletedMs { get; init; } public long? CooldownUntilMs { get; init; } public string? RewardGroupId { get; init; } public string? StaleReason { get; init; } public bool ClearTimestamps { get; init; } public IReadOnlyDictionary<string, long>? Progress { get; init; } public IReadOnlyCollection<string>? Reveal { get; init; } public QuestClock? Clock { get; init; } public bool ClearCooldown { get; init; } } public sealed class QuestInstanceQuery { public string PlatformId { get; init; } = string.Empty; public string QuestId { get; init; } = string.Empty; public IReadOnlyList<QuestState> States { get; init; } = Array.Empty<QuestState>(); public long? BeforeId { get; init; } public int Limit { get; init; } = 100; } public static class QuestStates { public static bool IsOpen(QuestState state) { if (state != QuestState.Offered && state != QuestState.Active && state != QuestState.ReadyToTurnIn && state != QuestState.Paused) { return state == QuestState.Stale; } return true; } public static bool IsTerminal(QuestState state) { if (state != QuestState.Completed && state != QuestState.Failed && state != QuestState.Abandoned) { return state == QuestState.Cooldown; } return true; } public static string Name(QuestState state) { return state switch { QuestState.Offered => "offered", QuestState.Active => "active", QuestState.ReadyToTurnIn => "ready_to_turn_in", QuestState.Completed => "completed", QuestState.Failed => "failed", QuestState.Abandoned => "abandoned", QuestState.Paused => "paused", QuestState.Cooldown => "cooldown", QuestState.Stale => "stale", _ => throw new ArgumentOutOfRangeException("state", state, "NOT_OFFERED is the absence of a row and is never stored."), }; } public static QuestState Parse(string name) { return name switch { "offered" => QuestState.Offered, "active" => QuestState.Active, "ready_to_turn_in" => QuestState.ReadyToTurnIn, "completed" => QuestState.Completed, "failed" => QuestState.Failed, "abandoned" => QuestState.Abandoned, "paused" => QuestState.Paused, "cooldown" => QuestState.Cooldown, "stale" => QuestState.Stale, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest state."), }; } public static string EventName(QuestEventKind kind) { return kind switch { QuestEventKind.Offered => "offered", QuestEventKind.Accepted => "accepted", QuestEventKind.Progress => "progress", QuestEventKind.ObjectiveDone => "objective_done", QuestEventKind.Ready => "ready", QuestEventKind.Completed => "completed", QuestEventKind.Failed => "failed", QuestEventKind.Abandoned => "abandoned", QuestEventKind.Paused => "paused", QuestEventKind.Resumed => "resumed", QuestEventKind.Stale => "stale", QuestEventKind.Migrated => "migrated", QuestEventKind.AdminAdjusted => "admin_adjusted", _ => throw new ArgumentOutOfRangeException("kind", kind, "Unknown quest event kind."), }; } public static QuestEventKind ParseEvent(string name) { return name switch { "offered" => QuestEventKind.Offered, "accepted" => QuestEventKind.Accepted, "progress" => QuestEventKind.Progress, "objective_done" => QuestEventKind.ObjectiveDone, "ready" => QuestEventKind.Ready, "completed" => QuestEventKind.Completed, "failed" => QuestEventKind.Failed, "abandoned" => QuestEventKind.Abandoned, "paused" => QuestEventKind.Paused, "resumed" => QuestEventKind.Resumed, "stale" => QuestEventKind.Stale, "migrated" => QuestEventKind.Migrated, "admin_adjusted" => QuestEventKind.AdminAdjusted, _ => throw new ArgumentOutOfRangeException("name", name, "Unknown quest event kind."), }; } } public enum ShopTradeKind { Buy = 1, Barter, Sell } public sealed class ShopStockRecord { public string ShopId { get; init; } = string.Empty; public string EntryId { get; init; } = string.Empty; public int Qty { get; init; } public long RestockedMs { get; init; } } public sealed class ShopTradePart { public byte Kind { get; init; } public string Id { get; init; } = string.Empty; public long Amount { get; init; } } public sealed class ShopTradeRecord { public const string NoGrant = "-"; public string TradeId { get; init; } = string.Empty; public string PlatformId { get; init; } = string.Empty; public string ShopId { get; init; } = string.Empty; public string NpcId { get; init; } = string.Empty; public ShopTradeKind Kind { get; init; } public string RefId { get; init; } = string.Empty; public int Qty { get; init; } public IReadOnlyList<ShopTradePart> Paid { get; init; } = Array.Empty<ShopTradePart>(); public IReadOnlyList<ShopTradePart> Got { get; init; } = Array.Empty<ShopTradePart>(); public long CreditBefore { get; init; } public long CreditAfter { get; init; } public string GrantId { get; init; } = string.Empty; public long GameDay { get; init; } = -1L; public long ValueVu { get; init; } public long AtMs { get; init; } } public enum ShopCommitOutcome { Committed = 1, OutOfStock, CreditChanged } public sealed class ShopCommit { public ShopTradeRecord Trade { get; init; } = new ShopTradeRecord(); public int StockTake { get; init; } public string StockEntryId { get; init; } = string.Empty; public long CreditExpected { get; init; } public IReadOnlyList<ActivityEntry> Activity { get; init; } = Array.Empty<ActivityEntry>(); } public sealed class SellWindow { public long SinceMs { get; init; } public long FromGameDay { get; init; } = -1L; } public sealed class ServerSwitchRecord { public string SwitchId { get; init; } = string.Empty; public bool On { get; init; } public long ChangedMs { get; init; } public string ChangedBy { get; init; } = string.Empty; } public sealed class HeldName { public string Name { get; init; } = string.Empty; public int Holders { get; init; } } public sealed class HeldFlag { public string FlagId { get; init; } = string.Empty; public long SetMs { get; init; } } public sealed class QuestWipe { public IReadOnlyList<long> Instances { get; init; } = Array.Empty<long>(); public int Events { get; init; } public int GrantsClosed { get; init; } } public sealed class WorldRow { public long Id { get; init; } public string Key { get; init; } = string.Empty; public string Body { get; init; } = string.Empty; public string UpdatedBy { get; init; } = string.Empty; public long UpdatedMs { get; init; } } } namespace ALIVE.Core.Protocol { public static class AliveProtocol { public const ushort ProtoVersion = 1; public const byte EnvelopeVersion = 1; public const ushort Magic = 42782; public const int MaxFrameBytes = 8192; public const int MaxPayloadBytes = 4194304; public const int MaxPayloadBytesC2S = 262144; public const int MaxChunks = 64; public const int MaxChunksC2S = 8; public const int CompressMinBytes = 512; public const int MaxStringBytes = 4096; public const int MaxCollectionSize = 1024; public const string RpcChannelServer = "ALIVE.s2c"; public const string RpcChannelPlayer = "ALIVE.c2s.player"; public const string RpcChannelAdmin = "ALIVE.c2s.admin"; } public static class AttestationDigest { public const byte SpecNonceThenFile = 1; public static ByteString Response(ByteString serverNonce, byte[] fileBytes) { if (serverNonce == null) { throw new ArgumentNullException("serverNonce"); } if (fileBytes == null) { throw new ArgumentNullException("fileBytes"); } using SHA256 sHA = SHA256.Create(); sHA.TransformBlock(serverNonce.Raw, 0, serverNonce.Length, null, 0); sHA.TransformFinalBlock(fileBytes, 0, fileBytes.Length); return ByteString.Own(sHA.Hash); } public static ByteString Combined(IReadOnlyList<ByteString> responses) { if (responses == null) { throw new ArgumentNullException("responses"); } WireWriter wireWriter = new WireWriter(); foreach (ByteString response in responses) { wireWriter.WriteRaw(response); } return Sha256(wireWriter.ToArray()); } public static ByteString PluginSet(IReadOnlyList<PluginReport> plugins) { if (plugins == null) { throw new ArgumentNullException("plugins"); } WireWriter wireWriter = new WireWriter(); foreach (PluginReport plugin in plugins) { wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.PluginId))); wireWriter.WriteU8(0); wireWriter.WriteRaw(ByteString.Own(Encoding.UTF8.GetBytes(plugin.Version))); wireWriter.WriteU8(0); wireWriter.WriteRaw(plugin.FileHash); } return Sha256(wireWriter.ToArray()); } private static ByteString Sha256(byte[] data) { using SHA256 sHA = SHA256.Create(); return ByteString.Own(sHA.ComputeHash(data)); } } public sealed class ByteString : IEquatable<ByteString> { private readonly byte[] _bytes; public static ByteString Empty { get; } = new ByteString(Array.Empty<byte>()); public int Length => _bytes.Length; public byte this[int index] => _bytes[index]; public bool IsAllZero { get { byte[] bytes = _bytes; for (int i = 0; i < bytes.Length; i++) { if (bytes[i] != 0) { return false; } } return true; } } internal byte[] Raw => _bytes; private ByteString(byte[] owned) { _bytes = owned; } public static ByteString CopyFrom(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (bytes.Length != 0) { return new ByteString((byte[])bytes.Clone()); } return Empty; } public static ByteString CopyFrom(byte[] bytes, int offset, int count) { if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || count < 0 || offset > checked(bytes.Length - count)) { throw new ArgumentOutOfRangeException("count"); } if (count == 0) { return Empty; } byte[] array = new byte[count]; Buffer.BlockCopy(bytes, offset, array, 0, count); return new ByteString(array); } public static ByteString Zeros(int length) { if (length != 0) { return new ByteString(new byte[length]); } return Empty; } internal static ByteString Own(byte[] bytes) { if (bytes.Length != 0) { return new ByteString(bytes); } return Empty; } public byte[] ToArray() { return (byte[])_bytes.Clone(); } public bool FixedTimeEquals(ByteString? other) { if (other == null || other._bytes.Length != _bytes.Length) { return false; } int num = 0; for (int i = 0; i < _bytes.Length; i = checked(i + 1)) { num |= _bytes[i] ^ other._bytes[i]; } return num == 0; } internal void CopyTo(byte[] destination, int offset) { Buffer.BlockCopy(_bytes, 0, destination, offset, _bytes.Length); } public bool Equals(ByteString? other) { return FixedTimeEquals(other); } public override bool Equals(object? obj) { if (obj is ByteString other) { return FixedTimeEquals(other); } return false; } public override int GetHashCode() { int num = -2128831035; byte[] bytes = _bytes; foreach (byte b in bytes) { num = (num ^ b) * 16777619; } return num; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(checked(_bytes.Length * 2)); byte[] bytes = _bytes; foreach (byte b in bytes) { stringBuilder.Append(b.ToString("x2", CultureInfo.InvariantCulture)); } return stringBuilder.ToString(); } } public static class Crc32C { private const uint Polynomial = 2197175160u; private static readonly uint[] Table = BuildTable(); public static uint Compute(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } checked { if (offset < 0 || count < 0 || offset > data.Length - count) { throw new ArgumentOutOfRangeException("count"); } uint num = uint.MaxValue; int num2 = offset + count; for (int i = offset; i < num2; i++) { num = Table[(num ^ data[i]) & 0xFF] ^ (num >> 8); } return ~num; } } private static uint[] BuildTable() { uint[] array = new uint[256]; checked { for (uint num = 0u; num < 256; num++) { uint num2 = num; for (int i = 0; i < 8; i++) { num2 = (((num2 & 1) != 0) ? (0x82F63B78u ^ (num2 >> 1)) : (num2 >> 1)); } array[num] = num2; } return array; } } } public enum DecodeOutcome { Complete, Pending, Dropped, Rejected } public sealed class DecodeResult { public DecodeOutcome Outcome { get; } public ErrorCode Error { get; } public bool HardSignal { get; } public string Detail { get; } public FrameHeader? Header { get; } public ByteString? Payload { get; } private DecodeResult(DecodeOutcome outcome, ErrorCode error, bool hardSignal, string detail, FrameHeader? header, ByteString? payload) { Outcome = outcome; Error = error; HardSignal = hardSignal; Detail = detail; Header = header; Payload = payload; } internal static DecodeResult Complete(FrameHeader header, ByteString payload) { return new DecodeResult(DecodeOutcome.Complete, ErrorCode.None, hardSignal: false, string.Empty, header, payload); } internal static DecodeResult Pending() { return new DecodeResult(DecodeOutcome.Pending, ErrorCode.None, hardSignal: false, string.Empty, null, null); } internal static DecodeResult Dropped(string detail) { return new DecodeResult(DecodeOutcome.Dropped, ErrorCode.None, hardSignal: false, detail, null, null); } internal static DecodeResult Reject(ErrorCode error, bool hard, string detail) { return new DecodeResult(DecodeOutcome.Rejected, error, hard, detail, null, null); } } public static class Envelope { public const int HeaderBytes = 44; public const int ChunkHeaderBytes = 12; public const int CrcBytes = 4; public const int IdemKeyBytes = 16; public const byte FlagCompressed = 1; public const byte FlagChunk = 2; public const byte FlagAdmin = 4; public const byte ReservedFlags = 248; public static int SingleBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 4); } public static int ChunkBodyLimit(int maxFrameBytes) { return checked(maxFrameBytes - 44 - 12 - 4); } } public enum ErrorCode { None = 0, Malformed = 1000, UnsupportedEnvVersion = 1001, ReservedBitsSet = 1002, TrailingBytes = 1003, WrongDirection = 1004, UnknownMsgType = 1005, SizeLimit = 1006, SenderIdMismatch = 1007, BadCrc = 1008, UnsupportedMsgVersion = 1009, NoSession = 2001, NotReady = 2002, SessionExpired = 2003, SessionMismatch = 2004, ProtoVersionMismatch = 2101, AttestationFailed = 2102, DualClientDetected = 2103, PluginPolicyDenied = 2104, AttestTimeout = 2105, SyncTimeout = 2106, ClientRequired = 2107, Banned = 2108, ServerFullAlive = 2109, ClientVersionMismatch = 2110, FieldInvalid = 3001, NotFound = 3002, QtyOutOfRange = 3003, ItemNotAllowed = 3004, StringTooLong = 3011, ContentSchemaInvalid = 3006, ContentBoundsExceeded = 3007, CollectionTooLarge = 3012, CharsetViolation = 3013, IdempotencyConflict = 3009, IdempotencyMissing = 3010, NotAuthorized = 4001, NotOwner = 4002, NotOffered = 4003, OutOfRange = 4005, OptionNotOffered = 4009, DualControlRequired = 4011, SuperAdminRequired = 4012, SelfApprovalForbidden = 4013, ShopClosed = 5001, StaleVersion = 5002, PriceChanged = 5003, OutOfStock = 5004, InsufficientFunds = 5005, ObjectivesIncomplete = 5006, NotActive = 5010, AlreadyCompleted = 5011, InstanceNotFound = 5016, NothingToRevoke = 5017, ApprovalExpired = 5020, LimitReached = 5021, RateLimited = 6001, BurstLimited = 6002, MemoryBudget = 6004, Internal = 7001 } public static class FieldRules { public static bool IsVersion(string? value) { if (value == null || value.Length == 0 || value.Length > 32) { return false; } int i = 0; int num = 0; checked { while (true) { int num2 = i; for (; i < value.Length && value[i] >= '0' && value[i] <= '9'; i++) { } int num3 = i - num2; if (num3 < 1 || num3 > 5) { return false; } num++; if (i == value.Length) { return num <= 4; } if (value[i] != '.' || num >= 4) { break; } i++; } if (value[i] != '-') { return false; } int num4 = value.Length - i - 1; if (num4 < 1 || num4 > 16) { return false; } for (int j = i + 1; j < value.Length; j++) { char c = value[j]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.') { return false; } } return true; } } public static bool IsPluginId(string? value) { return IsToken(value, 128, allowUpper: true, leadingUnderscore: true); } public static bool IsIdentifier(string? value) { return IsToken(value, 64, allowUpper: false); } public static bool IsBuildId(string? value) { if (value != null) { if (value.Length != 0) { return IsToken(value, 40, allowUpper: true); } return true; } return false; } private static bool IsToken(string? value, int max, bool allowUpper, bool leadingUnderscore = false) { if (value == null || value.Length == 0 || value.Length > max) { return false; } for (int i = 0; i < value.Length; i = checked(i + 1)) { char c = value[i]; if ((c < 'a' || c > 'z') && (c < '0' || c > '9') && (!allowUpper || c < 'A' || c > 'Z') && (i <= 0 || (c != '.' && c != '_' && c != '-')) && (!(i == 0 && leadingUnderscore) || c != '_')) { return false; } } return true; } } public sealed class Frame { public FrameHeader Header { get; } public bool Compressed { get; } public int PayloadLength { get; } public ChunkInfo? Chunk { get; } public ByteString Body { get; } internal Frame(FrameHeader header, bool compressed, int payloadLength, ChunkInfo? chunk, ByteString body) { Header = header; Compressed = compressed; PayloadLength = payloadLength; Chunk = chunk; Body = body; } } public sealed class ChunkInfo { public uint ChunkId { get; } public int Index { get; } public int Count { get; } public int TotalLength { get; } internal ChunkInfo(uint chunkId, int index, int count, int totalLength) { ChunkId = chunkId; Index = index; Count = count; TotalLength = totalLength; } } public static class FrameCodec { public static IReadOnlyList<byte[]> Encode(FrameHeader header, ByteString payload, FrameLimits limits, uint chunkId) { if (header == null) { throw new ArgumentNullException("header"); } if (payload == null) { throw new ArgumentNullException("payload"); } if (limits == null) { throw new ArgumentNullException("limits"); } if (header.IdemKey == null || header.IdemKey.Length != 16) { throw new ArgumentException("The idempotency key must be 16 bytes.", "header"); } if (payload.Length > limits.MaxPayloadBytes) { throw new ArgumentOutOfRangeException("payload", "Payload of " + payload.Length + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } bool flag = false; byte[] array = payload.Raw; if (payload.Length >= 512) { byte[] array2 = Deflate(array); if (array2.Length < array.Length) { array = array2; flag = true; } } byte b = checked((byte)((flag ? 1 : 0) | (header.Admin ? 4 : 0))); if (array.Length <= Envelope.SingleBodyLimit(limits.MaxFrameBytes)) { return new byte[1][] { Build(header, b, payload.Length, null, array, 0, array.Length) }; } int num = Envelope.ChunkBodyLimit(limits.MaxFrameBytes); int num2 = checked(array.Length + num - 1) / num; if (num2 > limits.MaxChunks) { throw new ArgumentOutOfRangeException("payload", "Payload needs " + num2 + " chunks; the limit is " + limits.MaxChunks + "."); } byte[][] array3 = new byte[num2][]; checked { for (int i = 0; i < num2; i++) { int num3 = i * num; int length = Math.Min(num, array.Length - num3); array3[i] = Build(header, (byte)(b | 2), payload.Length, new ChunkInfo(chunkId, i, num2, array.Length), array, num3, length); } return array3; } } public static bool TryDecode(byte[]? frame, FrameLimits limits, [NotNullWhen(true)] out Frame? decoded, [NotNullWhen(false)] out DecodeResult? failure) { decoded = null; failure = Check(frame, limits); if (failure != null) { return false; } Frame decoded2; DecodeResult decodeResult = Parse(frame, limits, out decoded2); if (decodeResult != null || decoded2 == null) { failure = decodeResult ?? DecodeResult.Reject(ErrorCode.Malformed, hard: true, "The envelope could not be read."); return false; } decoded = decoded2; failure = null; return true; } private static DecodeResult? Check(byte[]? frame, FrameLimits limits) { if (limits == null) { throw new ArgumentNullException("limits"); } if (frame == null || frame.Length < 2) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame is too short to hold an envelope."); } if ((frame[0] | (frame[1] << 8)) != 42782) { return DecodeResult.Dropped("Not an ALIVE frame (magic mismatch)."); } if (frame.Length < 48) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Frame of " + frame.Length + " bytes is shorter than an envelope."); } if (frame.Length > limits.MaxFrameBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Frame of " + frame.Length + " bytes exceeds the limit of " + limits.MaxFrameBytes + "."); } int num = checked(frame.Length - 4); WireReader wireReader = new WireReader(frame, num, 4); if (wireReader.ReadU32() != Crc32C.Compute(frame, 0, num)) { return DecodeResult.Reject(ErrorCode.BadCrc, hard: false, "CRC mismatch: the frame was corrupted or truncated."); } return null; } private static DecodeResult? Parse(byte[] frame, FrameLimits limits, out Frame? decoded) { decoded = null; checked { int num = frame.Length - 4; try { WireReader wireReader = new WireReader(frame, 2, num - 2); byte b = wireReader.ReadU8(); if (b != 1) { return DecodeResult.Reject(ErrorCode.UnsupportedEnvVersion, hard: false, "Envelope version " + b + " is not supported."); } byte b2 = wireReader.ReadU8(); if ((b2 & 0xF8) != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "Reserved flag bits were set."); } ushort msgType = wireReader.ReadU16(); byte msgVersion = wireReader.ReadU8(); if (wireReader.ReadU8() != 0) { return DecodeResult.Reject(ErrorCode.ReservedBitsSet, hard: true, "The reserved header byte was not zero."); } uint seq = wireReader.ReadU32(); uint ackSeq = wireReader.ReadU32(); ulong sessionId = wireReader.ReadU64(); ByteString idemKey = wireReader.ReadFixed(16); uint num2 = wireReader.ReadU32(); if (num2 > (uint)limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Declared payload of " + num2 + " bytes exceeds the limit of " + limits.MaxPayloadBytes + "."); } ChunkInfo chunk = null; if ((b2 & 2) != 0) { uint chunkId = wireReader.ReadU32(); ushort num3 = wireReader.ReadU16(); ushort num4 = wireReader.ReadU16(); uint num5 = wireReader.ReadU32(); if (num4 == 0 || num4 > limits.MaxChunks) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunk count " + num4 + " is outside 1-" + limits.MaxChunks + "."); } if (num3 >= num4) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk index " + num3 + " is not below the count " + num4 + "."); } if (num5 == 0 || num5 > limits.MaxChunkedBodyBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked body of " + num5 + " bytes is outside the limit."); } if (wireReader.Remaining == 0) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk frame carried no bytes."); } chunk = new ChunkInfo(chunkId, num3, num4, (int)num5); } FrameHeader header = new FrameHeader { Admin = ((b2 & 4) != 0), MsgType = msgType, MsgVersion = msgVersion, Seq = seq, AckSeq = ackSeq, SessionId = sessionId, IdemKey = idemKey }; decoded = new Frame(header, (b2 & 1) != 0, (int)num2, chunk, wireReader.ReadRest()); return null; } catch (WireException ex) { return DecodeResult.Reject(ex.Code, hard: true, ex.Message); } } } public static DecodeResult DecodeSingle(byte[]? frame, FrameLimits limits) { if (!TryDecode(frame, limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "A chunk arrived where a single frame was required."); } return Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } internal static DecodeResult Open(FrameHeader header, byte[] body, bool compressed, int payloadLength) { if (!compressed) { if (body.Length != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Payload is " + body.Length + " bytes but declared " + payloadLength + "."); } return DecodeResult.Complete(header, ByteString.Own(body)); } checked { try { byte[] array = new byte[payloadLength]; using (MemoryStream stream = new MemoryStream(body, writable: false)) { using DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress); int i; int num; for (i = 0; i < payloadLength; i += num) { num = deflateStream.Read(array, i, payloadLength - i); if (num == 0) { break; } } if (i != payloadLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflated to " + i + " bytes but declared " + payloadLength + "."); } byte[] buffer = new byte[1]; if (deflateStream.Read(buffer, 0, 1) != 0) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Compressed payload inflates beyond its declared " + payloadLength + " bytes."); } } return DecodeResult.Complete(header, ByteString.Own(array)); } catch (Exception ex) when (ex is InvalidDataException || ex is IOException || ex is NotSupportedException) { return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Compressed payload is not valid deflate: " + ex.Message); } } } private static byte[] Deflate(byte[] data) { using MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal, leaveOpen: true)) { deflateStream.Write(data, 0, data.Length); } return memoryStream.ToArray(); } private static byte[] Build(FrameHeader h, byte flags, int payloadLength, ChunkInfo? chunk, byte[] body, int offset, int length) { checked { WireWriter wireWriter = new WireWriter(56 + length + 4); wireWriter.WriteU16(42782); wireWriter.WriteU8(1); wireWriter.WriteU8(flags); wireWriter.WriteU16(h.MsgType); wireWriter.WriteU8(h.MsgVersion); wireWriter.WriteU8(0); wireWriter.WriteU32(h.Seq); wireWriter.WriteU32(h.AckSeq); wireWriter.WriteU64(h.SessionId); wireWriter.WriteFixed(h.IdemKey, 16); wireWriter.WriteU32((uint)payloadLength); if (chunk != null) { wireWriter.WriteU32(chunk.ChunkId); wireWriter.WriteU16((ushort)chunk.Index); wireWriter.WriteU16((ushort)chunk.Count); wireWriter.WriteU32((uint)chunk.TotalLength); } wireWriter.WriteRaw(ByteString.CopyFrom(body, offset, length)); byte[] array = wireWriter.ToArray(); wireWriter.WriteU32(Crc32C.Compute(array, 0, array.Length)); return wireWriter.ToArray(); } } } public sealed class FrameHeader { public bool Admin { get; init; } public ushort MsgType { get; init; } public byte MsgVersion { get; init; } = 1; public uint Seq { get; init; } public uint AckSeq { get; init; } public ulong SessionId { get; init; } public ByteString IdemKey { get; init; } = ByteString.Zeros(16); public bool SameAs(FrameHeader other) { if (other != null && Admin == other.Admin && MsgType == other.MsgType && MsgVersion == other.MsgVersion && Seq == other.Seq && AckSeq == other.AckSeq && SessionId == other.SessionId) { return IdemKey.FixedTimeEquals(other.IdemKey); } return false; } } public sealed class FrameLimits { public static FrameLimits ServerToClient { get; } = new FrameLimits(8192, 4194304, 64); public static FrameLimits ClientToServer { get; } = new FrameLimits(8192, 262144, 8); public int MaxFrameBytes { get; } public int MaxPayloadBytes { get; } public int MaxChunks { get; } public long MaxChunkedBodyBytes { get { checked { return unchecked((long)MaxChunks) * unchecked((long)Envelope.ChunkBodyLimit(MaxFrameBytes)); } } } public FrameLimits(int maxFrameBytes, int maxPayloadBytes, int maxChunks) { if (maxFrameBytes < 1024) { throw new ArgumentOutOfRangeException("maxFrameBytes", "The protocol needs frames of at least 1 KiB."); } if (maxPayloadBytes < 1) { throw new ArgumentOutOfRangeException("maxPayloadBytes"); } if (maxChunks < 1 || maxChunks > 65535) { throw new ArgumentOutOfRangeException("maxChunks"); } MaxFrameBytes = maxFrameBytes; MaxPayloadBytes = maxPayloadBytes; MaxChunks = maxChunks; } } public sealed class FrameReceiver { private readonly FrameLimits _limits; public Reassembler Chunks { get; } public FrameReceiver(FrameLimits limits) { _limits = limits ?? throw new ArgumentNullException("limits"); Chunks = new Reassembler(limits, 4, 30000L, 8388608L); } public DecodeResult Receive(byte[]? frame, long nowMs) { if (!FrameCodec.TryDecode(frame, _limits, out Frame decoded, out DecodeResult failure)) { return failure; } if (decoded.Chunk != null) { return Chunks.Accept(decoded, nowMs); } return FrameCodec.Open(decoded.Header, decoded.Body.Raw, decoded.Compressed, decoded.PayloadLength); } } public sealed class Reassembler { private sealed class Pending { internal Frame First { get; } internal long StartedMs { get; } internal long Order { get; } internal ByteString?[] Parts { get; } internal int Received { get; set; } internal int Bytes { get; set; } internal Pending(Frame first, long startedMs, long order) { First = first; StartedMs = startedMs; Order = order; Parts = new ByteString[first.Chunk.Count]; } internal bool Matches(Frame f) { ChunkInfo chunk = First.Chunk; ChunkInfo chunk2 = f.Chunk; if (chunk.Count == chunk2.Count && chunk.TotalLength == chunk2.TotalLength && First.Compressed == f.Compressed && First.PayloadLength == f.PayloadLength) { return First.Header.SameAs(f.Header); } return false; } } public const int DefaultMaxConcurrent = 4; public const long DefaultTtlMs = 30000L; public const long DefaultMemoryBudget = 8388608L; private readonly FrameLimits _limits; private readonly int _maxConcurrent; private readonly long _ttlMs; private readonly long _memoryBudget; private readonly Dictionary<uint, Pending> _pending = new Dictionary<uint, Pending>(); private long _order; public int PendingCount => _pending.Count; public long BufferedBytes { get; private set; } public int Evictions { get; private set; } public int Expirations { get; private set; } public Reassembler(FrameLimits limits, int maxConcurrent = 4, long ttlMs = 30000L, long memoryBudget = 8388608L) { _limits = limits ?? throw new ArgumentNullException("limits"); if (maxConcurrent < 1) { throw new ArgumentOutOfRangeException("maxConcurrent"); } if (ttlMs < 1) { throw new ArgumentOutOfRangeException("ttlMs"); } if (memoryBudget < 1) { throw new ArgumentOutOfRangeException("memoryBudget"); } _maxConcurrent = maxConcurrent; _ttlMs = ttlMs; _memoryBudget = memoryBudget; } public DecodeResult Accept(Frame frame, long nowMs) { if (frame == null) { throw new ArgumentNullException("frame"); } ChunkInfo chunkInfo = frame.Chunk ?? throw new ArgumentException("Not a chunk frame.", "frame"); if (chunkInfo.Count > _limits.MaxChunks || frame.PayloadLength > _limits.MaxPayloadBytes) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunked message " + chunkInfo.ChunkId + " exceeds this direction's limits."); } Expire(nowMs); checked { if (!_pending.TryGetValue(chunkInfo.ChunkId, out Pending value)) { while (_pending.Count >= _maxConcurrent) { Pending p = (from x in _pending.Values orderby x.StartedMs, x.Order select x).First(); Remove(p); Evictions++; } value = new Pending(frame, nowMs, _order++); _pending.Add(chunkInfo.ChunkId, value); } else if (!value.Matches(frame)) { Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " changed the message's header or chunk count mid-stream."); } ByteString byteString = value.Parts[chunkInfo.Index]; if (byteString != null) { if (byteString.FixedTimeEquals(frame.Body)) { return DecodeResult.Pending(); } Remove(value); return DecodeResult.Reject(ErrorCode.Malformed, hard: true, "Chunk " + chunkInfo.Index + " of message " + chunkInfo.ChunkId + " arrived twice with different bytes."); } if (BufferedBytes + frame.Body.Length > _memoryBudget) { Clear(); long memoryBudget = _memoryBudget; return DecodeResult.Reject(ErrorCode.MemoryBudget, hard: false, "Reassembly memory budget of " + memoryBudget + " bytes exhausted; all partial messages dropped."); } if (value.Bytes + frame.Body.Length > chunkInfo.TotalLength) { Remove(value); return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Chunks of message " + chunkInfo.ChunkId + " exceed its declared " + chunkInfo.TotalLength + " bytes."); } value.Parts[chunkInfo.Index] = frame.Body; value.Received++; value.Bytes += frame.Body.Length; BufferedBytes += frame.Body.Length; if (value.Received < chunkInfo.Count) { return DecodeResult.Pending(); } Remove(value); if (value.Bytes != chunkInfo.TotalLength) { return DecodeResult.Reject(ErrorCode.SizeLimit, hard: true, "Message " + chunkInfo.ChunkId + " reassembled to " + value.Bytes + " bytes but declared " + chunkInfo.TotalLength + "."); } byte[] array = new byte[value.Bytes]; int num = 0; ByteString[] parts = value.Parts; foreach (ByteString byteString2 in parts) { byteString2.CopyTo(array, num); num += byteString2.Length; } return FrameCodec.Open(value.First.Header, array, value.First.Compressed, value.First.PayloadLength); } } public void Expire(long nowMs) { checked { foreach (Pending item in _pending.Values.Where((Pending x) => nowMs - x.StartedMs > _ttlMs).ToList()) { Remove(item); Expirations++; } } } public void Clear() { _pending.Clear(); BufferedBytes = 0L; } private void Remove(Pending p) { checked { if (_pending.Remove(p.First.Chunk.ChunkId)) { BufferedBytes -= p.Bytes; } } } } public sealed class ReplayWindow { public const int Width = 64; private ulong _seen; public uint Highest { get; private set; } public long Rejected { get; private set; } public bool Accept(uint seq) { uint num2; checked { if (seq == 0) { Rejected++; return false; } if (seq > Highest) { uint num = seq - Highest; _seen = ((num >= 64) ? 0 : (_seen << (int)num)); _seen |= 1uL; Highest = seq; return true; } num2 = Highest - seq; if (num2 >= 64) { Rejected++; return false; } } ulong num3 = (ulong)(1L << checked((int)num2)); checked { if ((_seen & num3) != 0L) { Rejected++; return false; } _seen |= num3; return true; } } } public sealed class WireException : Exception { public ErrorCode Code { get; } = ErrorCode.Malformed; public WireException() { } public WireException(string message) : base(message) { } public WireException(string message, Exception innerException) : base(message, innerException) { } public WireException(ErrorCode code, string message) : base(message) { Code = code; } } public sealed class WireReader { private static readonly UTF8Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); private readonly byte[] _buffer; private readonly int _end; private int _position; public int Remaining => checked(_end - _position); public WireReader(byte[] buffer) : this(buffer, 0, (buffer != null) ? buffer.Length : 0) { } public WireReader(byte[] buffer, int offset, int count) { _buffer = buffer ?? throw new ArgumentNullException("buffer"); checked { if (offset < 0 || count < 0 || offset > buffer.Length - count) { throw new ArgumentOutOfRangeException("count"); } _position = offset; _end = offset + count; } } public byte ReadU8() { Need(1, "u8"); return _buffer[checked(_position++)]; } public bool ReadBool() { byte b = ReadU8(); return b switch { 0 => false, 1 => true, _ => throw new WireException(ErrorCode.Malformed, "A bool field held " + b + "; only 0 and 1 are valid."), }; } public ushort ReadU16() { Need(2, "u16"); checked { int num = _buffer[_position] | (_buffer[_position + 1] << 8); _position += 2; return (ushort)num; } } public uint ReadU32() { Need(4, "u32"); uint num = 0u; for (int i = 0; i < 4; i = checked(i + 1)) { num |= (uint)checked(_buffer[_position + i] << 8 * i); } checked { _position += 4; return num; } } public ulong ReadU64() { Need(8, "u64"); ulong num = 0uL; for (int i = 0; i < 8; i = checked(i + 1)) { num |= (ulong)_buffer[checked(_position + i)] << checked(8 * i); } checked { _position += 8; return num; } } public long ReadI64() { return (long)ReadU64(); } public ByteString ReadFixed(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } Need(length, "byte[" + length + "]"); ByteString result = ByteString.CopyFrom(_buffer, _position, length); checked { _position += length; return result; } } public ByteString ReadRest() { ByteString result = ByteString.CopyFrom(_buffer, _position, Remaining); _position = _end; return result; } public ByteString ReadBlob(int maxBytes) { uint num = ReadU32(); checked { if (num > (uint)maxBytes) { throw new WireException(ErrorCode.SizeLimit, "A blob declared " + num + " bytes; the limit is " + maxBytes + "."); } return ReadFixed((int)num); } } public string ReadString(int maxBytes) { ushort num = ReadU16(); if (n
plugins/Microsoft.Data.Sqlite.dll
Decompiled 3 hours 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.ObjectModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.Data.Sqlite.Properties; using Microsoft.Data.Sqlite.Utilities; using SQLitePCL; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Microsoft.Data.Sqlite.e_sqlcipher.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.Data.Sqlite.sqlite3.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.Data.Sqlite.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: InternalsVisibleTo("Microsoft.Data.Sqlite.winsqlite3.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyMetadata("CommitHash", "4315fa43c9573671f8f5be21497d59f9c99cd829")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("Microsoft.Data.Sqlite is a lightweight ADO.NET provider for SQLite. This package does not include a copy of the native SQLite library.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Data.Sqlite.SqliteCommand\r\nMicrosoft.Data.Sqlite.SqliteConnection\r\nMicrosoft.Data.Sqlite.SqliteConnectionStringBuilder\r\nMicrosoft.Data.Sqlite.SqliteDataReader\r\nMicrosoft.Data.Sqlite.SqliteException\r\nMicrosoft.Data.Sqlite.SqliteFactory\r\nMicrosoft.Data.Sqlite.SqliteParameter\r\nMicrosoft.Data.Sqlite.SqliteTransaction")] [assembly: AssemblyFileVersion("8.0.1024.46708")] [assembly: AssemblyInformationalVersion("8.0.10")] [assembly: AssemblyProduct("Microsoft Entity Framework Core")] [assembly: AssemblyTitle("Microsoft.Data.Sqlite")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/efcore")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("8.0.10.0")] [module: RefSafetyRules(11)] [module: NullablePublicOnly(true)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [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 NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = 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 System { internal static class TypeExtensions { public static Type UnwrapEnumType(this Type type) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(type); } public static Type UnwrapNullableType(this Type type) { return Nullable.GetUnderlyingType(type) ?? type; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } } namespace SQLitePCL { internal static class SQLitePCLExtensions { private static readonly Dictionary<string, bool> _knownLibraries = new Dictionary<string, bool> { { "e_sqlcipher", true }, { "e_sqlite3", false }, { "sqlcipher", true }, { "winsqlite3", false } }; public static bool? EncryptionSupported() { string libraryName; return EncryptionSupported(out libraryName); } public static bool? EncryptionSupported(out string libraryName) { libraryName = raw.GetNativeLibraryName(); if (!_knownLibraries.TryGetValue(libraryName, out var value)) { return null; } return value; } } } namespace Microsoft.Data.Sqlite { internal static class SqliteConnectionExtensions { public static int ExecuteNonQuery(this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) { using SqliteCommand sqliteCommand = connection.CreateCommand(); sqliteCommand.CommandText = commandText; sqliteCommand.Parameters.AddRange(parameters); return sqliteCommand.ExecuteNonQuery(); } public static T ExecuteScalar<T>(this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) { return (T)connection.ExecuteScalar(commandText, parameters); } private static object ExecuteScalar(this SqliteConnection connection, string commandText, params SqliteParameter[] parameters) { using SqliteCommand sqliteCommand = connection.CreateCommand(); sqliteCommand.CommandText = commandText; sqliteCommand.Parameters.AddRange(parameters); return sqliteCommand.ExecuteScalar(); } } public class SqliteBlob : Stream { private sqlite3_blob _blob; private readonly SqliteConnection _connection; private long _position; public override bool CanRead => true; public override bool CanWrite { get; } public override bool CanSeek => true; public override long Length { get; } public override long Position { get { return _position; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, null); } _position = value; } } public SqliteBlob(SqliteConnection connection, string tableName, string columnName, long rowid, bool readOnly = false) : this(connection, "main", tableName, columnName, rowid, readOnly) { } public SqliteBlob(SqliteConnection connection, string databaseName, string tableName, string columnName, long rowid, bool readOnly = false) { if (connection == null || connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.SqlBlobRequiresOpenConnection); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (columnName == null) { throw new ArgumentNullException("columnName"); } _connection = connection; CanWrite = !readOnly; SqliteException.ThrowExceptionForRC(raw.sqlite3_blob_open(_connection.Handle, databaseName, tableName, columnName, rowid, (!readOnly) ? 1 : 0, ref _blob), _connection.Handle); Length = raw.sqlite3_blob_bytes(_blob); } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", offset, null); } if (count < 0) { throw new ArgumentOutOfRangeException("count", count, null); } if (offset + count > buffer.Length) { throw new ArgumentException(Resources.InvalidOffsetAndCount); } return Read(buffer.AsSpan(offset, count)); } public new virtual int Read(Span<byte> buffer) { if (_blob == null) { throw new ObjectDisposedException(null); } long num = _position; if (num > Length) { num = Length; } int num2 = buffer.Length; if (num + num2 > Length) { num2 = (int)(Length - num); } SqliteException.ThrowExceptionForRC(raw.sqlite3_blob_read(_blob, buffer.Slice(0, num2), (int)num), _connection.Handle); _position += num2; return num2; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", offset, null); } if (count < 0) { throw new ArgumentOutOfRangeException("count", count, null); } if (offset + count > buffer.Length) { throw new ArgumentException(Resources.InvalidOffsetAndCount); } if (_blob == null) { throw new ObjectDisposedException(null); } Write(buffer.AsSpan(offset, count)); } public new virtual void Write(ReadOnlySpan<byte> buffer) { if (!CanWrite) { throw new NotSupportedException(Resources.WriteNotSupported); } long num = _position; if (num > Length) { num = Length; } int length = buffer.Length; if (num + length > Length) { throw new NotSupportedException(Resources.ResizeNotSupported); } SqliteException.ThrowExceptionForRC(raw.sqlite3_blob_write(_blob, buffer.Slice(0, length), (int)num), _connection.Handle); _position += length; } public override long Seek(long offset, SeekOrigin origin) { long num = origin switch { SeekOrigin.Begin => offset, SeekOrigin.Current => _position + offset, SeekOrigin.End => Length + offset, _ => throw new ArgumentException(Resources.InvalidEnumValue(typeof(SeekOrigin), origin), "origin"), }; if (num < 0) { throw new IOException(Resources.SeekBeforeBegin); } return _position = num; } protected override void Dispose(bool disposing) { if (_blob != null) { ((SafeHandle)(object)_blob).Dispose(); _blob = null; } } public override void Flush() { } public override void SetLength(long value) { throw new NotSupportedException(Resources.ResizeNotSupported); } } public enum SqliteCacheMode { Default, Private, Shared } public class SqliteCommand : DbCommand { private SqliteParameterCollection _parameters; private readonly List<(sqlite3_stmt Statement, int ParamCount)> _preparedStatements = new List<(sqlite3_stmt, int)>(1); private SqliteConnection _connection; private string _commandText = string.Empty; private bool _prepared; private int? _commandTimeout; public override CommandType CommandType { get { return CommandType.Text; } set { if (value != CommandType.Text) { throw new ArgumentException(Resources.InvalidCommandType(value)); } } } public override string CommandText { get { return _commandText; } [param: AllowNull] set { if (DataReader != null) { throw new InvalidOperationException(Resources.SetRequiresNoOpenReader("CommandText")); } if (value != _commandText) { DisposePreparedStatements(); _commandText = value ?? string.Empty; } } } public new virtual SqliteConnection? Connection { get { return _connection; } set { if (DataReader != null) { throw new InvalidOperationException(Resources.SetRequiresNoOpenReader("Connection")); } if (value != _connection) { DisposePreparedStatements(); _connection?.RemoveCommand(this); _connection = value; value?.AddCommand(this); } } } protected override DbConnection? DbConnection { get { return Connection; } set { Connection = (SqliteConnection)value; } } public new virtual SqliteTransaction? Transaction { get; set; } protected override DbTransaction? DbTransaction { get { return Transaction; } set { Transaction = (SqliteTransaction)value; } } public new virtual SqliteParameterCollection Parameters => _parameters ?? (_parameters = new SqliteParameterCollection()); protected override DbParameterCollection DbParameterCollection => Parameters; public override int CommandTimeout { get { return _commandTimeout ?? _connection?.DefaultTimeout ?? 30; } set { _commandTimeout = value; } } public override bool DesignTimeVisible { get; set; } public override UpdateRowSource UpdatedRowSource { get; set; } protected internal virtual SqliteDataReader? DataReader { get; set; } public SqliteCommand() { } public SqliteCommand(string? commandText) { CommandText = commandText; } public SqliteCommand(string? commandText, SqliteConnection? connection) : this(commandText) { Connection = connection; } public SqliteCommand(string? commandText, SqliteConnection? connection, SqliteTransaction? transaction) : this(commandText, connection) { Transaction = transaction; } protected override void Dispose(bool disposing) { DisposePreparedStatements(disposing); if (disposing) { _connection?.RemoveCommand(this); } base.Dispose(disposing); } public new virtual SqliteParameter CreateParameter() { return new SqliteParameter(); } protected override DbParameter CreateDbParameter() { return CreateParameter(); } public override void Prepare() { SqliteConnection connection = _connection; if (connection == null || connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("Prepare")); } if (_prepared) { return; } using IEnumerator<(sqlite3_stmt, int)> enumerator = PrepareAndEnumerateStatements().GetEnumerator(); while (enumerator.MoveNext()) { } } public new virtual SqliteDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } public new virtual SqliteDataReader ExecuteReader(CommandBehavior behavior) { if (DataReader != null) { throw new InvalidOperationException(Resources.DataReaderOpen); } SqliteConnection connection = _connection; if (connection == null || connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("ExecuteReader")); } if (Transaction != _connection.Transaction) { throw new InvalidOperationException((Transaction == null) ? Resources.TransactionRequired : Resources.TransactionConnectionMismatch); } SqliteTransaction? transaction = _connection.Transaction; if (transaction != null && transaction.ExternalRollback) { throw new InvalidOperationException(Resources.TransactionCompleted); } bool closeConnection = behavior.HasFlag(CommandBehavior.CloseConnection); SqliteDataReader sqliteDataReader = new SqliteDataReader(this, GetStatements(), closeConnection); sqliteDataReader.NextResult(); return DataReader = sqliteDataReader; } private IEnumerable<sqlite3_stmt> GetStatements() { IEnumerable<(sqlite3_stmt Statement, int ParamCount)> enumerable; if (_prepared) { IEnumerable<(sqlite3_stmt, int)> preparedStatements = _preparedStatements; enumerable = preparedStatements; } else { enumerable = PrepareAndEnumerateStatements(); } foreach (var item3 in enumerable) { sqlite3_stmt item = item3.Statement; int item2 = item3.ParamCount; int num = _parameters?.Bind(item) ?? 0; if (item2 != num) { List<string> list = new List<string>(); for (int i = 1; i <= item2; i++) { utf8z val = raw.sqlite3_bind_parameter_name(item, i); string name = ((utf8z)(ref val)).utf8_to_string(); if (_parameters != null && !_parameters.Cast<SqliteParameter>().Any((SqliteParameter p) => p.ParameterName == name)) { list.Add(name); } } if (raw.sqlite3_libversion_number() < 3028000 || raw.sqlite3_stmt_isexplain(item) == 0) { throw new InvalidOperationException(Resources.MissingParameters(string.Join(", ", list))); } } yield return item; } } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } public new virtual Task<SqliteDataReader> ExecuteReaderAsync() { return ExecuteReaderAsync(CommandBehavior.Default, CancellationToken.None); } public new virtual Task<SqliteDataReader> ExecuteReaderAsync(CancellationToken cancellationToken) { return ExecuteReaderAsync(CommandBehavior.Default, cancellationToken); } public new virtual Task<SqliteDataReader> ExecuteReaderAsync(CommandBehavior behavior) { return ExecuteReaderAsync(behavior, CancellationToken.None); } public new virtual Task<SqliteDataReader> ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(ExecuteReader(behavior)); } protected override async Task<DbDataReader> ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken) { return await ExecuteReaderAsync(behavior, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public override int ExecuteNonQuery() { SqliteConnection connection = _connection; if (connection == null || connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("ExecuteNonQuery")); } SqliteDataReader sqliteDataReader = ExecuteReader(); sqliteDataReader.Dispose(); return sqliteDataReader.RecordsAffected; } public override object? ExecuteScalar() { SqliteConnection connection = _connection; if (connection == null || connection.State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("ExecuteScalar")); } using SqliteDataReader sqliteDataReader = ExecuteReader(); return sqliteDataReader.Read() ? sqliteDataReader.GetValue(0) : null; } public override void Cancel() { } private IEnumerable<(sqlite3_stmt Statement, int ParamCount)> PrepareAndEnumerateStatements() { DisposePreparedStatements(disposing: false); int byteCount = Encoding.UTF8.GetByteCount(_commandText); byte[] sql = new byte[byteCount + 1]; Encoding.UTF8.GetBytes(_commandText, 0, _commandText.Length, sql, 0); TimeSpan totalElapsedTime = TimeSpan.Zero; int start = 0; sqlite3_stmt val = default(sqlite3_stmt); ReadOnlySpan<byte> readOnlySpan = default(ReadOnlySpan<byte>); do { SharedStopwatch sharedStopwatch = SharedStopwatch.StartNew(); int rc; while (IsBusy(rc = raw.sqlite3_prepare_v2(_connection.Handle, (ReadOnlySpan<byte>)sql.AsSpan(start), ref val, ref readOnlySpan)) && (CommandTimeout == 0 || !((totalElapsedTime + sharedStopwatch.Elapsed).TotalMilliseconds >= (double)((long)CommandTimeout * 1000L)))) { Thread.Sleep(150); } totalElapsedTime += sharedStopwatch.Elapsed; start = sql.Length - readOnlySpan.Length; SqliteException.ThrowExceptionForRC(rc, _connection.Handle); if (((SafeHandle)(object)val).IsInvalid) { if (start >= byteCount) { break; } } else { int item = raw.sqlite3_bind_parameter_count(val); (sqlite3_stmt, int) tuple = (val, item); _preparedStatements.Add(tuple); yield return tuple; } } while (start < byteCount); _prepared = true; } private void DisposePreparedStatements(bool disposing = true) { if (disposing && DataReader != null) { DataReader.Dispose(); DataReader = null; } if (_preparedStatements != null) { foreach (var preparedStatement in _preparedStatements) { ((SafeHandle)(object)preparedStatement.Statement).Dispose(); } _preparedStatements.Clear(); } _prepared = false; } private static bool IsBusy(int rc) { if ((uint)(rc - 5) <= 1u || rc == 262) { return true; } return false; } } public class SqliteConnection : DbConnection { private sealed class AggregateDefinition<TAccumulate, TResult> { public string Name { get; } public TAccumulate Seed { get; } public Func<TAccumulate, SqliteValueReader, TAccumulate> Func { get; } public Func<TAccumulate, TResult> ResultSelector { get; } public AggregateDefinition(string name, TAccumulate seed, Func<TAccumulate, SqliteValueReader, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { Name = name; Seed = seed; Func = func; ResultSelector = resultSelector; } } private sealed class AggregateContext<T> { public T Accumulate { get; set; } public Exception Exception { get; set; } public AggregateContext(T seed) { Accumulate = seed; } } private sealed class FunctionsKeyComparer : IEqualityComparer<(string name, int arity)> { public static readonly FunctionsKeyComparer Instance = new FunctionsKeyComparer(); public bool Equals((string name, int arity) x, (string name, int arity) y) { if (StringComparer.OrdinalIgnoreCase.Equals(x.name, y.name)) { return x.arity == y.arity; } return false; } public int GetHashCode((string name, int arity) obj) { int hashCode = StringComparer.OrdinalIgnoreCase.GetHashCode(obj.name); int hashCode2 = obj.arity.GetHashCode(); return (((hashCode << 5) | (hashCode >>> 27)) + hashCode) ^ hashCode2; } } [Serializable] [CompilerGenerated] private sealed class <>c__159<TAccumulate, TResult> { public static readonly <>c__159<TAccumulate, TResult> <>9 = new <>c__159<TAccumulate, TResult>(); public static delegate_function_aggregate_step <>9__159_0; public static delegate_function_aggregate_final <>9__159_1; internal void <CreateAggregateCore>b__159_0(sqlite3_context ctx, object user_data, sqlite3_value[] args) { AggregateDefinition<TAccumulate, TResult> aggregateDefinition = (AggregateDefinition<TAccumulate, TResult>)user_data; if (ctx.state == null) { ctx.state = new AggregateContext<TAccumulate>(aggregateDefinition.Seed); } AggregateContext<TAccumulate> aggregateContext = (AggregateContext<TAccumulate>)ctx.state; if (aggregateContext.Exception != null) { return; } SqliteParameterReader arg = new SqliteParameterReader(aggregateDefinition.Name, args); try { aggregateContext.Accumulate = aggregateDefinition.Func(aggregateContext.Accumulate, arg); } catch (Exception exception) { aggregateContext.Exception = exception; } } internal void <CreateAggregateCore>b__159_1(sqlite3_context ctx, object user_data) { AggregateDefinition<TAccumulate, TResult> aggregateDefinition = (AggregateDefinition<TAccumulate, TResult>)user_data; if (ctx.state == null) { ctx.state = new AggregateContext<TAccumulate>(aggregateDefinition.Seed); } AggregateContext<TAccumulate> aggregateContext = (AggregateContext<TAccumulate>)ctx.state; if (aggregateContext.Exception == null) { try { TResult val = aggregateDefinition.ResultSelector(aggregateContext.Accumulate); new SqliteResultBinder(ctx, val).Bind(); } catch (Exception exception) { aggregateContext.Exception = exception; } } if (aggregateContext.Exception != null) { raw.sqlite3_result_error(ctx, aggregateContext.Exception.Message); if (aggregateContext.Exception is SqliteException ex) { raw.sqlite3_result_error_code(ctx, ex.SqliteErrorCode); } } } } internal const string MainDatabaseName = "main"; private const int SQLITE_WIN32_DATA_DIRECTORY_TYPE = 1; private const int SQLITE_WIN32_TEMP_DIRECTORY_TYPE = 2; private readonly List<WeakReference<SqliteCommand>> _commands = new List<WeakReference<SqliteCommand>>(); private Dictionary<string, (object state, strdelegate_collation collation)> _collations; private Dictionary<(string name, int arity), (int flags, object state, delegate_function_scalar func)> _functions; private Dictionary<(string name, int arity), (int flags, object state, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final)> _aggregates; private HashSet<(string file, string proc)> _extensions; private string _connectionString; private ConnectionState _state; private SqliteConnectionInternal _innerConnection; private bool _extensionsEnabled; private int? _defaultTimeout; private static readonly StateChangeEventArgs _fromClosedToOpenEventArgs; private static readonly StateChangeEventArgs _fromOpenToClosedEventArgs; public virtual sqlite3? Handle => _innerConnection?.Handle; public override string ConnectionString { get { return _connectionString; } [MemberNotNull(new string[] { "_connectionString", "PoolGroup" })] [param: AllowNull] set { if (State != ConnectionState.Closed) { throw new InvalidOperationException(Resources.ConnectionStringRequiresClosedConnection); } _connectionString = value ?? string.Empty; PoolGroup = SqliteConnectionFactory.Instance.GetPoolGroup(_connectionString); } } internal SqliteConnectionPoolGroup PoolGroup { get; set; } internal SqliteConnectionStringBuilder ConnectionOptions => PoolGroup.ConnectionOptions; public override string Database => "main"; public override string DataSource { get { //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) string text = null; if (State == ConnectionState.Open) { utf8z val = raw.sqlite3_db_filename(Handle, "main"); text = ((utf8z)(ref val)).utf8_to_string(); } return text ?? ConnectionOptions.DataSource; } } public virtual int DefaultTimeout { get { return _defaultTimeout ?? ConnectionOptions.DefaultTimeout; } set { _defaultTimeout = value; } } public override string ServerVersion { get { //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) utf8z val = raw.sqlite3_libversion(); return ((utf8z)(ref val)).utf8_to_string(); } } public override ConnectionState State => _state; protected override DbProviderFactory DbProviderFactory => SqliteFactory.Instance; protected internal virtual SqliteTransaction? Transaction { get; set; } public virtual void CreateAggregate<TAccumulate>(string name, Func<TAccumulate?, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 0, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a)), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, TAccumulate>(string name, Func<TAccumulate?, T1, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 1, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, TAccumulate>(string name, Func<TAccumulate?, T1, T2, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 2, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 3, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 4, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 5, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 6, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 7, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 8, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 9, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 10, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 11, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 12, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 13, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 14, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate>(string name, Func<TAccumulate?, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 15, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<TAccumulate>(string name, Func<TAccumulate?, object?[], TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, -1, default(TAccumulate), IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, GetValues(r))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 0, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a)), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 1, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 2, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 3, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 4, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 5, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 6, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 7, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 8, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 9, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 10, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 11, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 12, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 13, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 14, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, 15, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<TAccumulate>(string name, TAccumulate seed, Func<TAccumulate, object?[], TAccumulate>? func, bool isDeterministic = false) { CreateAggregateCore(name, -1, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, GetValues(r))), (TAccumulate a) => a, isDeterministic); } public virtual void CreateAggregate<TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 0, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a)), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 1, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 2, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 3, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 4, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 5, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 6, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 7, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 8, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 9, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 10, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 11, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 12, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 13, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 14, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13))), resultSelector, isDeterministic); } public virtual void CreateAggregate<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, 15, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14))), resultSelector, isDeterministic); } public virtual void CreateAggregate<TAccumulate, TResult>(string name, TAccumulate seed, Func<TAccumulate, object?[], TAccumulate>? func, Func<TAccumulate, TResult>? resultSelector, bool isDeterministic = false) { CreateAggregateCore<TAccumulate, TResult>(name, -1, seed, IfNotNull(func, (TAccumulate a, SqliteValueReader r) => func(a, GetValues(r))), resultSelector, isDeterministic); } public virtual void CreateFunction<TResult>(string name, Func<TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 0, null, IfNotNull(function, (object s, SqliteValueReader r) => function()), isDeterministic); } public virtual void CreateFunction<T1, TResult>(string name, Func<T1, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 1, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0))), isDeterministic); } public virtual void CreateFunction<T1, T2, TResult>(string name, Func<T1, T2, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 2, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, TResult>(string name, Func<T1, T2, T3, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 3, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, TResult>(string name, Func<T1, T2, T3, T4, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 4, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, TResult>(string name, Func<T1, T2, T3, T4, T5, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 5, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 6, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 7, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 8, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 9, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 10, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 11, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 12, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 13, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 14, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 15, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14))), isDeterministic); } public virtual void CreateFunction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>(string name, Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 16, null, IfNotNull(function, (object s, SqliteValueReader r) => function(r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14), r.GetFieldValue<T16>(15))), isDeterministic); } public virtual void CreateFunction<TResult>(string name, Func<object?[], TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, -1, null, IfNotNull(function, (object s, SqliteValueReader r) => function(GetValues(r))), isDeterministic); } public virtual void CreateFunction<TState, TResult>(string name, TState state, Func<TState, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 0, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s)), isDeterministic); } public virtual void CreateFunction<TState, T1, TResult>(string name, TState state, Func<TState, T1, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 1, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, TResult>(string name, TState state, Func<TState, T1, T2, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 2, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, TResult>(string name, TState state, Func<TState, T1, T2, T3, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 3, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 4, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 5, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 6, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 7, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 8, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 9, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 10, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 11, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 12, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 13, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 14, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13))), isDeterministic); } public virtual void CreateFunction<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>(string name, TState state, Func<TState, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, 15, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, r.GetFieldValue<T1>(0), r.GetFieldValue<T2>(1), r.GetFieldValue<T3>(2), r.GetFieldValue<T4>(3), r.GetFieldValue<T5>(4), r.GetFieldValue<T6>(5), r.GetFieldValue<T7>(6), r.GetFieldValue<T8>(7), r.GetFieldValue<T9>(8), r.GetFieldValue<T10>(9), r.GetFieldValue<T11>(10), r.GetFieldValue<T12>(11), r.GetFieldValue<T13>(12), r.GetFieldValue<T14>(13), r.GetFieldValue<T15>(14))), isDeterministic); } public virtual void CreateFunction<TState, TResult>(string name, TState state, Func<TState, object?[], TResult>? function, bool isDeterministic = false) { CreateFunctionCore(name, -1, state, IfNotNull(function, (TState s, SqliteValueReader r) => function(s, GetValues(r))), isDeterministic); } static SqliteConnection() { _fromClosedToOpenEventArgs = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open); _fromOpenToClosedEventArgs = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed); Type.GetType("SQLitePCL.Batteries_V2, SQLitePCLRaw.batteries_v2")?.GetRuntimeMethod("Init", Type.EmptyTypes)?.Invoke(null, null); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } Type type = null; Type type2 = null; try { type = Type.GetType("Windows.Storage.ApplicationData, Windows, ContentType=WindowsRuntime") ?? Type.GetType("Windows.Storage.ApplicationData, Microsoft.Windows.SDK.NET"); type2 = Type.GetType("Windows.Storage.StorageFolder, Windows, ContentType=WindowsRuntime") ?? Type.GetType("Windows.Storage.StorageFolder, Microsoft.Windows.SDK.NET"); } catch (Exception) { } object obj = null; try { obj = type?.GetRuntimeProperty("Current")?.GetValue(null); } catch (TargetInvocationException) { } if (obj != null) { object obj2 = type?.GetRuntimeProperty("LocalFolder")?.GetValue(obj); string text = (string)type2?.GetRuntimeProperty("Path")?.GetValue(obj2); if (text != null) { raw.sqlite3_win32_set_directory(1, text); } object obj3 = type?.GetRuntimeProperty("TemporaryFolder")?.GetValue(obj); string text2 = (string)type2?.GetRuntimeProperty("Path")?.GetValue(obj3); if (text2 != null) { raw.sqlite3_win32_set_directory(2, text2); } } } public SqliteConnection() : this(null) { } public SqliteConnection(string? connectionString) { ConnectionString = connectionString; } public static void ClearAllPools() { SqliteConnectionFactory.Instance.ClearPools(); } public static void ClearPool(SqliteConnection connection) { connection.PoolGroup.Clear(); } public override void Open() { if (State == ConnectionState.Open) { return; } _innerConnection = SqliteConnectionFactory.Instance.GetConnection(this); _state = ConnectionState.Open; try { if (ConnectionOptions.ForeignKeys.HasValue) { this.ExecuteNonQuery("PRAGMA foreign_keys = " + (ConnectionOptions.ForeignKeys.Value ? "1" : "0") + ";"); } if (ConnectionOptions.RecursiveTriggers) { this.ExecuteNonQuery("PRAGMA recursive_triggers = 1;"); } if (_collations != null) { foreach (KeyValuePair<string, (object, strdelegate_collation)> collation in _collations) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_collation(Handle, collation.Key, collation.Value.Item1, collation.Value.Item2), Handle); } } if (_functions != null) { foreach (KeyValuePair<(string, int), (int, object, delegate_function_scalar)> function in _functions) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, function.Key.Item1, function.Key.Item2, function.Value.Item2, function.Value.Item3), Handle); } } if (_aggregates != null) { foreach (KeyValuePair<(string, int), (int, object, delegate_function_aggregate_step, delegate_function_aggregate_final)> aggregate in _aggregates) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, aggregate.Key.Item1, aggregate.Key.Item2, aggregate.Value.Item2, aggregate.Value.Item3, aggregate.Value.Item4), Handle); } } if (_extensions != null && _extensions.Count != 0) { int num = default(int); SqliteException.ThrowExceptionForRC(raw.sqlite3_db_config(Handle, 1005, 1, ref num), Handle); foreach (var extension in _extensions) { LoadExtensionCore(extension.file, extension.proc); } } if (_extensionsEnabled) { SqliteException.ThrowExceptionForRC(raw.sqlite3_enable_load_extension(Handle, _extensionsEnabled ? 1 : 0), Handle); } } catch { _innerConnection.Close(); _innerConnection = null; _state = ConnectionState.Closed; throw; } OnStateChange(_fromClosedToOpenEventArgs); } public override void Close() { if (State != ConnectionState.Open) { return; } Transaction?.Dispose(); for (int num = _commands.Count - 1; num >= 0; num--) { if (_commands[num].TryGetTarget(out var target)) { target.Dispose(); } else { _commands.RemoveAt(num); } } _innerConnection.Close(); _innerConnection = null; _state = ConnectionState.Closed; OnStateChange(_fromOpenToClosedEventArgs); } internal void Deactivate() { if (_collations != null) { foreach (string key in _collations.Keys) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_collation(Handle, key, (object)null, (strdelegate_collation)null), Handle); } } if (_functions != null) { foreach (var (text, num) in _functions.Keys) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, text, num, (object)null, (delegate_function_scalar)null), Handle); } } if (_aggregates != null) { foreach (var (text2, num2) in _aggregates.Keys) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, text2, num2, (object)null, (delegate_function_aggregate_step)null, (delegate_function_aggregate_final)null), Handle); } } if (_extensionsEnabled) { SqliteException.ThrowExceptionForRC(raw.sqlite3_enable_load_extension(Handle, 0), Handle); } } protected override void Dispose(bool disposing) { if (disposing) { Close(); } base.Dispose(disposing); } public new virtual SqliteCommand CreateCommand() { return new SqliteCommand { Connection = this, CommandTimeout = DefaultTimeout, Transaction = Transaction }; } protected override DbCommand CreateDbCommand() { return CreateCommand(); } internal void AddCommand(SqliteCommand command) { _commands.Add(new WeakReference<SqliteCommand>(command)); } internal void RemoveCommand(SqliteCommand command) { for (int num = _commands.Count - 1; num >= 0; num--) { if (_commands[num].TryGetTarget(out var target) && target == command) { _commands.RemoveAt(num); } } } public virtual void CreateCollation(string name, Comparison<string>? comparison) { CreateCollation(name, null, (comparison != null) ? ((Func<object, string, string, int>)((object _, string s1, string s2) => comparison(s1, s2))) : null); } public virtual void CreateCollation<T>(string name, T state, Func<T, string, string, int>? comparison) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } strdelegate_collation val = ((comparison == null) ? ((strdelegate_collation)null) : ((strdelegate_collation)((object v, string s1, string s2) => comparison((T)v, s1, s2)))); if (State == ConnectionState.Open) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_collation(Handle, name, (object)state, val), Handle); } if (_collations == null) { _collations = new Dictionary<string, (object, strdelegate_collation)>(StringComparer.OrdinalIgnoreCase); } _collations[name] = (state, val); } public new virtual SqliteTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } public virtual SqliteTransaction BeginTransaction(bool deferred) { return BeginTransaction(IsolationLevel.Unspecified, deferred); } protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { return BeginTransaction(isolationLevel); } public new virtual SqliteTransaction BeginTransaction(IsolationLevel isolationLevel) { return BeginTransaction(isolationLevel, isolationLevel == IsolationLevel.ReadUncommitted); } public virtual SqliteTransaction BeginTransaction(IsolationLevel isolationLevel, bool deferred) { if (State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("BeginTransaction")); } if (Transaction != null) { throw new InvalidOperationException(Resources.ParallelTransactionsNotSupported); } return Transaction = new SqliteTransaction(this, isolationLevel, deferred); } public override void ChangeDatabase(string databaseName) { throw new NotSupportedException(); } public virtual void EnableExtensions(bool enable = true) { if (State == ConnectionState.Open) { SqliteException.ThrowExceptionForRC(raw.sqlite3_enable_load_extension(Handle, enable ? 1 : 0), Handle); } _extensionsEnabled = enable; } public virtual void LoadExtension(string file, string? proc = null) { if (State == ConnectionState.Open) { if (!_extensionsEnabled) { int num = default(int); SqliteException.ThrowExceptionForRC(raw.sqlite3_db_config(Handle, 1005, 1, ref num), Handle); } LoadExtensionCore(file, proc); } if (_extensions == null) { _extensions = new HashSet<(string, string)>(); } _extensions.Add((file, proc)); } private void LoadExtensionCore(string file, string proc) { //IL_0007: 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) utf8z val = default(utf8z); int num = raw.sqlite3_load_extension(Handle, utf8z.FromString(file), utf8z.FromString(proc), ref val); if (num != 0) { throw new SqliteException(Resources.SqliteNativeError(num, ((utf8z)(ref val)).utf8_to_string()), num, num); } } public virtual void BackupDatabase(SqliteConnection destination) { BackupDatabase(destination, "main", "main"); } public virtual void BackupDatabase(SqliteConnection destination, string destinationName, string sourceName) { if (State != ConnectionState.Open) { throw new InvalidOperationException(Resources.CallRequiresOpenConnection("BackupDatabase")); } if (destination == null) { throw new ArgumentNullException("destination"); } bool flag = false; if (destination.State != ConnectionState.Open) { destination.Open(); flag = true; } try { sqlite3_backup val = raw.sqlite3_backup_init(destination.Handle, destinationName, Handle, sourceName); try { if (((SafeHandle)(object)val).IsInvalid) { SqliteException.ThrowExceptionForRC(raw.sqlite3_errcode(destination.Handle), destination.Handle); } SqliteException.ThrowExceptionForRC(raw.sqlite3_backup_step(val, -1), destination.Handle); } finally { ((IDisposable)val)?.Dispose(); } } finally { if (flag) { destination.Close(); } } } public override DataTable GetSchema() { return GetSchema(DbMetaDataCollectionNames.MetaDataCollections); } public override DataTable GetSchema(string collectionName) { return GetSchema(collectionName, Array.Empty<string>()); } public override DataTable GetSchema(string collectionName, string?[] restrictionValues) { if (restrictionValues != null && restrictionValues.Length != 0) { throw new ArgumentException(Resources.TooManyRestrictions(collectionName)); } if (string.Equals(collectionName, DbMetaDataCollectionNames.MetaDataCollections, StringComparison.OrdinalIgnoreCase)) { DataTable dataTable = new DataTable(DbMetaDataCollectionNames.MetaDataCollections); dataTable.Columns.Add(DbMetaDataColumnNames.CollectionName); dataTable.Columns.Add(DbMetaDataColumnNames.NumberOfRestrictions, typeof(int)); dataTable.Columns.Add(DbMetaDataColumnNames.NumberOfIdentifierParts, typeof(int)); dataTable.Rows.Add(DbMetaDataCollectionNames.MetaDataCollections, 0, 0); dataTable.Rows.Add(DbMetaDataCollectionNames.ReservedWords, 0, 0); return dataTable; } if (string.Equals(collectionName, DbMetaDataCollectionNames.ReservedWords, StringComparison.OrdinalIgnoreCase)) { DataTable dataTable2 = new DataTable(DbMetaDataCollectionNames.ReservedWords) { Columns = { DbMetaDataColumnNames.ReservedWord } }; int num = raw.sqlite3_keyword_count(); string text = default(string); for (int i = 0; i < num; i++) { SqliteException.ThrowExceptionForRC(raw.sqlite3_keyword_name(i, ref text), null); dataTable2.Rows.Add(text); } return dataTable2; } throw new ArgumentException(Resources.UnknownCollection(collectionName)); } private void CreateFunctionCore<TState, TResult>(string name, int arity, TState state, Func<TState, SqliteValueReader, TResult> function, bool isDeterministic) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown if (name == null) { throw new ArgumentNullException("name"); } delegate_function_scalar val = null; if (function != null) { val = (delegate_function_scalar)delegate(sqlite3_context ctx, object user_data, sqlite3_value[] args) { SqliteParameterReader arg = new SqliteParameterReader(name, args); try { TResult val2 = function((TState)user_data, arg); new SqliteResultBinder(ctx, val2).Bind(); } catch (Exception ex) { raw.sqlite3_result_error(ctx, ex.Message); if (ex is SqliteException ex2) { raw.sqlite3_result_error_code(ctx, ex2.SqliteErrorCode); } } }; } int num = (isDeterministic ? 2048 : 0); if (State == ConnectionState.Open) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, name, arity, num, (object)state, val), Handle); } if (_functions == null) { _functions = new Dictionary<(string, int), (int, object, delegate_function_scalar)>(FunctionsKeyComparer.Instance); } _functions[(name, arity)] = (num, state, val); } private void CreateAggregateCore<TAccumulate, TResult>(string name, int arity, TAccumulate seed, Func<TAccumulate, SqliteValueReader, TAccumulate> func, Func<TAccumulate, TResult> resultSelector, bool isDeterministic) { //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_0033: Expected O, but got Unknown //IL_004e: 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_0059: Expected O, but got Unknown if (name == null) { throw new ArgumentNullException("name"); } delegate_function_aggregate_step val = null; if (func != null) { object obj = <>c__159<TAccumulate, TResult>.<>9__159_0; if (obj == null) { delegate_function_aggregate_step val2 = delegate(sqlite3_context ctx, object user_data, sqlite3_value[] args) { AggregateDefinition<TAccumulate, TResult> aggregateDefinition2 = (AggregateDefinition<TAccumulate, TResult>)user_data; if (ctx.state == null) { ctx.state = new AggregateContext<TAccumulate>(aggregateDefinition2.Seed); } AggregateContext<TAccumulate> aggregateContext = (AggregateContext<TAccumulate>)ctx.state; if (aggregateContext.Exception != null) { return; } SqliteParameterReader arg = new SqliteParameterReader(aggregateDefinition2.Name, args); try { aggregateContext.Accumulate = aggregateDefinition2.Func(aggregateContext.Accumulate, arg); } catch (Exception exception) { aggregateContext.Exception = exception; } }; <>c__159<TAccumulate, TResult>.<>9__159_0 = val2; obj = (object)val2; } val = (delegate_function_aggregate_step)obj; } delegate_function_aggregate_final val3 = null; if (resultSelector != null) { object obj2 = <>c__159<TAccumulate, TResult>.<>9__159_1; if (obj2 == null) { delegate_function_aggregate_final val4 = delegate(sqlite3_context ctx, object user_data) { AggregateDefinition<TAccumulate, TResult> aggregateDefinition2 = (AggregateDefinition<TAccumulate, TResult>)user_data; if (ctx.state == null) { ctx.state = new AggregateContext<TAccumulate>(aggregateDefinition2.Seed); } AggregateContext<TAccumulate> aggregateContext = (AggregateContext<TAccumulate>)ctx.state; if (aggregateContext.Exception == null) { try { TResult val5 = aggregateDefinition2.ResultSelector(aggregateContext.Accumulate); new SqliteResultBinder(ctx, val5).Bind(); } catch (Exception exception) { aggregateContext.Exception = exception; } } if (aggregateContext.Exception != null) { raw.sqlite3_result_error(ctx, aggregateContext.Exception.Message); if (aggregateContext.Exception is SqliteException ex) { raw.sqlite3_result_error_code(ctx, ex.SqliteErrorCode); } } }; <>c__159<TAccumulate, TResult>.<>9__159_1 = val4; obj2 = (object)val4; } val3 = (delegate_function_aggregate_final)obj2; } int num = (isDeterministic ? 2048 : 0); AggregateDefinition<TAccumulate, TResult> aggregateDefinition = new AggregateDefinition<TAccumulate, TResult>(name, seed, func, resultSelector); if (State == ConnectionState.Open) { SqliteException.ThrowExceptionForRC(raw.sqlite3_create_function(Handle, name, arity, num, (object)aggregateDefinition, val, val3), Handle); } if (_aggregates == null) { _aggregates = new Dictionary<(string, int), (int, object, delegate_function_aggregate_step, delegate_function_aggregate_final)>(FunctionsKeyComparer.Instance); } _aggregates[(name, arity)] = (num, aggregateDefinition, val, val3); } private static Func<TState, SqliteValueReader, TResult> IfNotNull<TState, TResult>(object x, Func<TState, SqliteValueReader, TResult> value) { if (x == null) { return null; } return value; } private static object[] GetValues(SqliteValueReader reader) { object[] array = new object[reader.FieldCount]; reader.GetValues(array); return array; } } internal class SqliteConnectionFactory { public static readonly SqliteConnectionFactory Instance = new SqliteConnectionFactory(); private readonly Timer _pruneTimer; private readonly List<SqliteConnectionPoolGroup> _idlePoolGroups = new List<SqliteConnectionPoolGroup>(); private readonly List<SqliteConnectionPool> _poolsToRelease = new List<SqliteConnectionPool>(); private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); private Dictionary<string, SqliteConnectionPoolGroup> _poolGroups = new Dictionary<string, SqliteConnectionPoolGroup>(); protected SqliteConnectionFactory() { AppDomain.CurrentDomain.DomainUnload += delegate { ClearPools(); }; AppDomain.CurrentDomain.ProcessExit += delegate { ClearPools(); }; _pruneTimer = new Timer(PruneCallback, null, TimeSpan.FromMinutes(4.0), TimeSpan.FromSeconds(30.0)); } public SqliteConnectionInternal GetConnection(SqliteConnection outerConnection) { SqliteConnectionPoolGroup sqliteConnectionPoolGroup = outerConnection.PoolGroup; if (sqliteConnectionPoolGroup != null && sqliteConnectionPoolGroup.IsDisabled && !sqliteConnectionPoolGroup.IsNonPooled) { sqliteConnectionPoolGroup = (outerConnection.PoolGroup = GetPoolGroup(sqliteConnectionPoolGroup.ConnectionString)); } SqliteConnectionPool pool = sqliteConnectionPoolGroup.GetPool(); SqliteConnectionInternal obj = ((pool == null) ? new SqliteConnectionInternal(outerConnection.ConnectionOptions) : pool.GetConnection()); obj.Activate(outerConnection); return obj; } public SqliteConnectionPoolGroup GetPoolGroup(string connectionString) { _lock.EnterUpgradeableReadLock(); try { if (!_poolGroups.TryGetValue(connectionString, out var value) || (value.IsDisabled && !value.IsNonPooled)) { SqliteConnectionStringBuilder sqliteConnectionStringBuilder = new SqliteConnectionStringBuilder(connectionString); _lock.EnterWriteLock(); try { if (!_poolGroups.TryGetValue(connectionString, out value)) { bool isNonPooled = sqliteConnectionStringBuilder.DataSource == ":memory:" || sqliteConnectionStringBuilder.Mode == SqliteOpenMode.Memory || sqliteConnectionStringBuilder.DataSource.Length == 0 || !sqliteConnectionStringBuilder.Pooling; value = new SqliteConnectionPoolGroup(sqliteConnectionStringBuilder, connectionString, isNonPooled); _poolGroups.Add(connectionString, value); } } finally { _lock.ExitWriteLock(); } } return value; } finally { _lock.ExitUpgradeableReadLock(); } } public void ReleasePool(SqliteConnectionPool pool, bool clearing) { pool.Shutdown(); lock (_poolsToRelease) { if (clearing) { pool.Clear(); } _poolsToRelease.Add(pool); } } public void ClearPools() { _lock.EnterWriteLock(); try { foreach (KeyValuePair<string, SqliteConnectionPoolGroup> poolGroup in _poolGroups) { poolGroup.Value.Clear(); } } finally { _lock.ExitWriteLock(); } } private void PruneCallback(object _) { lock (_poolsToRelease) { for (int num = _poolsToRelease.Count - 1; num >= 0; num--) { SqliteConnectionPool sqliteConnectionPool = _poolsToRelease[num]; sqliteConnectionPool.Clear(); if (sqliteConnectionPool.Count == 0) { _poolsToRelease.Remove(sqliteConnectionPool); } } } _lock.EnterWriteLock(); try { for (int num2 = _idlePoolGroups.Count - 1; num2 >= 0; num2--) { SqliteConnectionPoolGroup sqliteConnectionPoolGroup = _idlePoolGroups[num2]; if (!sqliteConnectionPoolGroup.Clear()) { _idlePoolGroups.Remove(sqliteConnectionPoolGroup); } } Dictionary<string, SqliteConnectionPoolGroup> dictionary = new Dictionary<string, SqliteConnectionPoolGroup>(); foreach (KeyValuePair<string, SqliteConnectionPoolGroup> poolGroup in _poolGroups) { SqliteConnectionPoolGroup value = poolGroup.Value; if (value.Prune()) { _idlePoolGroups.Add(value); } else { dictionary.Add(poolGroup.Key, value); } } _poolGroups = dictionary; } finally { _lock.ExitWriteLock(); } } } internal class SqliteConnectionInternal { private const string DataDirectoryMacro = "|DataDirectory|"; private readonly sqlite3 _db; private readonly WeakReference<SqliteConnection> _outerConnection = new WeakReference<SqliteConnection>(null); private SqliteConnectionPool _pool; private volatile bool _active; private volatile bool _canBePooled = true; public bool Leaked { get { SqliteConnection target; if (_active) { return !_outerConnection.TryGetTarget(out target); } return false; } } public bool CanBePooled { get { SqliteConnection target; if (_canBePooled) { return !_outerConnection.TryGetTarget(out target); } return false; } } public sqlite3? Handle => _db; public SqliteConnectionInternal(SqliteConnectionStringBuilder connectionOptions, SqliteConnectionPool? pool = null) { string text = connectionOptions.DataSource; int num = 0; if (text.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) { num |= 0x40; } switch (connectionOptions.Mode) { case SqliteOpenMode.ReadOnly: num |= 1; break; case SqliteOpenMode.ReadWrite: num |= 2; break; case SqliteOpenMode.Memory: num |= 0x86; if ((num & 0x40) == 0) { num |= 0x40; text = "file:" + text; } break; default: num |= 6; break; } switch (connectionOptions.Cache) { case SqliteCacheMode.Shared: num |= 0x20000; break; case SqliteCacheMode.Private: num |= 0x40000; break; } string text2 = AppDomain.CurrentDomain.GetData("DataDirectory") as string; if (!string.IsNullOrEmpty(text2) && (num & 0x40) == 0 && !text.Equals(":memory:", StringComparison.OrdinalIgnoreCase)) { if (text.StartsWith("|DataDirectory|", StringComparison.InvariantCultureIgnoreCase)) { text = Path.Combine(text2, text.Substring("|DataDirectory|".Length)); } else if (!Path.IsPathRooted(text)) { text = Path.Combine(text2, text); } } SqliteException.ThrowExceptionForRC(raw.sqlite3_open_v2(text, ref _db, num, (string)null), _db); if (connectionOptions.Password.Length != 0) { if (SQLitePCLExtensions.EncryptionSupported(out string libraryName) == false) { throw new InvalidOperationException(Resources.EncryptionNotSupported(libraryName)); } string text3 = ExecuteScalar("SELECT quote($password);", connectionOptions.Password, connectionOptions.DefaultTimeout); ExecuteNonQuery("PRAGMA key = " + text3 + ";", connectionOptions.DefaultTimeout); if (SQLitePCLExtensions.EncryptionSupported() != false) { ExecuteNonQuery("SELECT COUNT(*) FROM sqlite_master;", connectionOptions.DefaultTimeout); } } if (connectionOptions.ForeignKeys.HasValue) { ExecuteNonQuery("PRAGMA foreign_keys = " + (connectionOptions.ForeignKeys.Value ? "1" : "0") + ";", connectionOptions.DefaultTimeout); } if (connectionOptions.RecursiveTriggers) { ExecuteNonQuery("PRAGMA recursive_triggers = 1;", connectionOptions.DefaultTimeout); } _pool = pool; } public void DoNotPool() { _canBePooled = false; } public void Activate(SqliteConnection outerConnection) { _active = true; _outerConnection.SetTarget(outerConnection); } public void Close() { if (_pool != null) { _pool.Return(this); } else { Dispose(); } } public void Deactivate() { if (_outerConnection.TryGetTarget(out var target)) { target.Deactivate(); } _outerConnection.SetTarget(null); _active = false; } public void Dispose() { ((SafeHandle)(object)_db).Dispose(); _pool = null; } private void ExecuteNonQuery(string sql, int timeout) { RetryWhileBusy(() => raw.sqlite3_exec(_db, sql), timeout); } private string ExecuteScalar(string sql, string p1, int timeout) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) Stopwatch timer = Stopwatch.StartNew(); sqlite3_stmt stmt = null; RetryWhileBusy(() => raw.sqlite3_prepare_v2(_db, sql, ref stmt), timeout, timer); try { raw.sqlite3_bind_text(stmt, 1, p1); RetryWhileBusy(() => raw.sqlite3_step(stmt), delegate { raw.sqlite3_reset(stmt); }, timeout, timer); utf8z val = raw.sqlite3_column_text(stmt, 0); return ((utf8z)(ref val)).utf8_to_string(); } finally { ((SafeHandle)(object)stmt).Dispose(); } } private void RetryWhileBusy(Func<int> action, int timeout, Stopwatch timer = null) { RetryWhileBusy(action, del
plugins/SQLitePCLRaw.batteries_v2.dll
Decompiled 3 hours agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("SourceGear")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2014-2024 SourceGear, LLC")] [assembly: AssemblyDescription("SQLitePCLRaw is a Portable Class Library (PCL) for low-level (raw) access to SQLite")] [assembly: AssemblyFileVersion("2.1.13.3146")] [assembly: AssemblyInformationalVersion("2.1.13")] [assembly: AssemblyTitle("SQLitePCLRaw.batteries_v2")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ericsink/SQLitePCL.raw")] [assembly: AssemblyVersion("2.1.13.3146")] namespace SQLitePCL; public static class Batteries { public static void Init() { Batteries_V2.Init(); } } public static class Batteries_V2 { public static void Init() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Expected O, but got Unknown raw.SetProvider((ISQLite3Provider)new SQLite3Provider_e_sqlite3()); } }
plugins/SQLitePCLRaw.core.dll
Decompiled 3 hours agousing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; 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("SourceGear")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2014-2024 SourceGear, LLC")] [assembly: AssemblyDescription("SQLitePCLRaw is a Portable Class Library (PCL) for low-level (raw) access to SQLite")] [assembly: AssemblyFileVersion("2.1.13.3146")] [assembly: AssemblyInformationalVersion("2.1.13")] [assembly: AssemblyTitle("SQLitePCLRaw.core")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ericsink/SQLitePCL.raw")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.13.3146")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Embedded] internal sealed class IsByRefLikeAttribute : Attribute { } } namespace SQLitePCL { public delegate int strdelegate_collation(object user_data, string s1, string s2); public delegate void strdelegate_update(object user_data, int type, string database, string table, long rowid); public delegate void strdelegate_log(object user_data, int errorCode, string msg); public delegate int strdelegate_authorizer(object user_data, int action_code, string param0, string param1, string dbName, string inner_most_trigger_or_view); public delegate void strdelegate_trace(object user_data, string s); public delegate void strdelegate_profile(object user_data, string statement, long ns); public delegate int strdelegate_exec(object user_data, string[] values, string[] names); public static class raw { private static ISQLite3Provider _imp; private static bool _frozen; public const int SQLITE_UTF8 = 1; public const int SQLITE_UTF16LE = 2; public const int SQLITE_UTF16BE = 3; public const int SQLITE_UTF16 = 4; public const int SQLITE_ANY = 5; public const int SQLITE_UTF16_ALIGNED = 8; public const int SQLITE_DETERMINISTIC = 2048; public const int SQLITE_LIMIT_LENGTH = 0; public const int SQLITE_LIMIT_SQL_LENGTH = 1; public const int SQLITE_LIMIT_COLUMN = 2; public const int SQLITE_LIMIT_EXPR_DEPTH = 3; public const int SQLITE_LIMIT_COMPOUND_SELECT = 4; public const int SQLITE_LIMIT_VDBE_OP = 5; public const int SQLITE_LIMIT_FUNCTION_ARG = 6; public const int SQLITE_LIMIT_ATTACHED = 7; public const int SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8; public const int SQLITE_LIMIT_VARIABLE_NUMBER = 9; public const int SQLITE_LIMIT_TRIGGER_DEPTH = 10; public const int SQLITE_LIMIT_WORKER_THREADS = 11; public const int SQLITE_CONFIG_SINGLETHREAD = 1; public const int SQLITE_CONFIG_MULTITHREAD = 2; public const int SQLITE_CONFIG_SERIALIZED = 3; public const int SQLITE_CONFIG_MALLOC = 4; public const int SQLITE_CONFIG_GETMALLOC = 5; public const int SQLITE_CONFIG_SCRATCH = 6; public const int SQLITE_CONFIG_PAGECACHE = 7; public const int SQLITE_CONFIG_HEAP = 8; public const int SQLITE_CONFIG_MEMSTATUS = 9; public const int SQLITE_CONFIG_MUTEX = 10; public const int SQLITE_CONFIG_GETMUTEX = 11; public const int SQLITE_CONFIG_LOOKASIDE = 13; public const int SQLITE_CONFIG_PCACHE = 14; public const int SQLITE_CONFIG_GETPCACHE = 15; public const int SQLITE_CONFIG_LOG = 16; public const int SQLITE_CONFIG_URI = 17; public const int SQLITE_CONFIG_PCACHE2 = 18; public const int SQLITE_CONFIG_GETPCACHE2 = 19; public const int SQLITE_CONFIG_COVERING_INDEX_SCAN = 20; public const int SQLITE_CONFIG_SQLLOG = 21; public const int SQLITE_DBCONFIG_MAINDBNAME = 1000; public const int SQLITE_DBCONFIG_LOOKASIDE = 1001; public const int SQLITE_DBCONFIG_ENABLE_FKEY = 1002; public const int SQLITE_DBCONFIG_ENABLE_TRIGGER = 1003; public const int SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER = 1004; public const int SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION = 1005; public const int SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE = 1006; public const int SQLITE_DBCONFIG_ENABLE_QPSG = 1007; public const int SQLITE_DBCONFIG_TRIGGER_EQP = 1008; public const int SQLITE_DBCONFIG_RESET_DATABASE = 1009; public const int SQLITE_DBCONFIG_DEFENSIVE = 1010; public const int SQLITE_DBCONFIG_WRITABLE_SCHEMA = 1011; public const int SQLITE_DBCONFIG_LEGACY_ALTER_TABLE = 1012; public const int SQLITE_DBCONFIG_DQS_DML = 1013; public const int SQLITE_DBCONFIG_DQS_DDL = 1014; public const int SQLITE_DBCONFIG_ENABLE_VIEW = 1015; public const int SQLITE_DBCONFIG_LEGACY_FILE_FORMAT = 1016; public const int SQLITE_DBCONFIG_TRUSTED_SCHEMA = 1017; public const int SQLITE_DBCONFIG_MAX = 1017; public const int SQLITE_OPEN_READONLY = 1; public const int SQLITE_OPEN_READWRITE = 2; public const int SQLITE_OPEN_CREATE = 4; public const int SQLITE_OPEN_DELETEONCLOSE = 8; public const int SQLITE_OPEN_EXCLUSIVE = 16; public const int SQLITE_OPEN_AUTOPROXY = 32; public const int SQLITE_OPEN_URI = 64; public const int SQLITE_OPEN_MEMORY = 128; public const int SQLITE_OPEN_MAIN_DB = 256; public const int SQLITE_OPEN_TEMP_DB = 512; public const int SQLITE_OPEN_TRANSIENT_DB = 1024; public const int SQLITE_OPEN_MAIN_JOURNAL = 2048; public const int SQLITE_OPEN_TEMP_JOURNAL = 4096; public const int SQLITE_OPEN_SUBJOURNAL = 8192; public const int SQLITE_OPEN_MASTER_JOURNAL = 16384; public const int SQLITE_OPEN_NOMUTEX = 32768; public const int SQLITE_OPEN_FULLMUTEX = 65536; public const int SQLITE_OPEN_SHAREDCACHE = 131072; public const int SQLITE_OPEN_PRIVATECACHE = 262144; public const int SQLITE_OPEN_WAL = 524288; public const int SQLITE_PREPARE_PERSISTENT = 1; public const int SQLITE_PREPARE_NORMALIZE = 2; public const int SQLITE_PREPARE_NO_VTAB = 4; public const int SQLITE_INTEGER = 1; public const int SQLITE_FLOAT = 2; public const int SQLITE_TEXT = 3; public const int SQLITE_BLOB = 4; public const int SQLITE_NULL = 5; public const int SQLITE_OK = 0; public const int SQLITE_ERROR = 1; public const int SQLITE_INTERNAL = 2; public const int SQLITE_PERM = 3; public const int SQLITE_ABORT = 4; public const int SQLITE_BUSY = 5; public const int SQLITE_LOCKED = 6; public const int SQLITE_NOMEM = 7; public const int SQLITE_READONLY = 8; public const int SQLITE_INTERRUPT = 9; public const int SQLITE_IOERR = 10; public const int SQLITE_CORRUPT = 11; public const int SQLITE_NOTFOUND = 12; public const int SQLITE_FULL = 13; public const int SQLITE_CANTOPEN = 14; public const int SQLITE_PROTOCOL = 15; public const int SQLITE_EMPTY = 16; public const int SQLITE_SCHEMA = 17; public const int SQLITE_TOOBIG = 18; public const int SQLITE_CONSTRAINT = 19; public const int SQLITE_MISMATCH = 20; public const int SQLITE_MISUSE = 21; public const int SQLITE_NOLFS = 22; public const int SQLITE_AUTH = 23; public const int SQLITE_FORMAT = 24; public const int SQLITE_RANGE = 25; public const int SQLITE_NOTADB = 26; public const int SQLITE_NOTICE = 27; public const int SQLITE_WARNING = 28; public const int SQLITE_ROW = 100; public const int SQLITE_DONE = 101; public const int SQLITE_IOERR_READ = 266; public const int SQLITE_IOERR_SHORT_READ = 522; public const int SQLITE_IOERR_WRITE = 778; public const int SQLITE_IOERR_FSYNC = 1034; public const int SQLITE_IOERR_DIR_FSYNC = 1290; public const int SQLITE_IOERR_TRUNCATE = 1546; public const int SQLITE_IOERR_FSTAT = 1802; public const int SQLITE_IOERR_UNLOCK = 2058; public const int SQLITE_IOERR_RDLOCK = 2314; public const int SQLITE_IOERR_DELETE = 2570; public const int SQLITE_IOERR_BLOCKED = 2826; public const int SQLITE_IOERR_NOMEM = 3082; public const int SQLITE_IOERR_ACCESS = 3338; public const int SQLITE_IOERR_CHECKRESERVEDLOCK = 3594; public const int SQLITE_IOERR_LOCK = 3850; public const int SQLITE_IOERR_CLOSE = 4106; public const int SQLITE_IOERR_DIR_CLOSE = 4362; public const int SQLITE_IOERR_SHMOPEN = 4618; public const int SQLITE_IOERR_SHMSIZE = 4874; public const int SQLITE_IOERR_SHMLOCK = 5130; public const int SQLITE_IOERR_SHMMAP = 5386; public const int SQLITE_IOERR_SEEK = 5642; public const int SQLITE_IOERR_DELETE_NOENT = 5898; public const int SQLITE_IOERR_MMAP = 6154; public const int SQLITE_IOERR_GETTEMPPATH = 6410; public const int SQLITE_IOERR_CONVPATH = 6666; public const int SQLITE_LOCKED_SHAREDCACHE = 262; public const int SQLITE_BUSY_RECOVERY = 261; public const int SQLITE_BUSY_SNAPSHOT = 517; public const int SQLITE_CANTOPEN_NOTEMPDIR = 270; public const int SQLITE_CANTOPEN_ISDIR = 526; public const int SQLITE_CANTOPEN_FULLPATH = 782; public const int SQLITE_CANTOPEN_CONVPATH = 1038; public const int SQLITE_CORRUPT_VTAB = 267; public const int SQLITE_READONLY_RECOVERY = 264; public const int SQLITE_READONLY_CANTLOCK = 520; public const int SQLITE_READONLY_ROLLBACK = 776; public const int SQLITE_READONLY_DBMOVED = 1032; public const int SQLITE_ABORT_ROLLBACK = 516; public const int SQLITE_CONSTRAINT_CHECK = 275; public const int SQLITE_CONSTRAINT_COMMITHOOK = 531; public const int SQLITE_CONSTRAINT_FOREIGNKEY = 787; public const int SQLITE_CONSTRAINT_FUNCTION = 1043; public const int SQLITE_CONSTRAINT_NOTNULL = 1299; public const int SQLITE_CONSTRAINT_PRIMARYKEY = 1555; public const int SQLITE_CONSTRAINT_TRIGGER = 1811; public const int SQLITE_CONSTRAINT_UNIQUE = 2067; public const int SQLITE_CONSTRAINT_VTAB = 2323; public const int SQLITE_CONSTRAINT_ROWID = 2579; public const int SQLITE_NOTICE_RECOVER_WAL = 283; public const int SQLITE_NOTICE_RECOVER_ROLLBACK = 539; public const int SQLITE_WARNING_AUTOINDEX = 284; public const int SQLITE_CREATE_INDEX = 1; public const int SQLITE_CREATE_TABLE = 2; public const int SQLITE_CREATE_TEMP_INDEX = 3; public const int SQLITE_CREATE_TEMP_TABLE = 4; public const int SQLITE_CREATE_TEMP_TRIGGER = 5; public const int SQLITE_CREATE_TEMP_VIEW = 6; public const int SQLITE_CREATE_TRIGGER = 7; public const int SQLITE_CREATE_VIEW = 8; public const int SQLITE_DELETE = 9; public const int SQLITE_DROP_INDEX = 10; public const int SQLITE_DROP_TABLE = 11; public const int SQLITE_DROP_TEMP_INDEX = 12; public const int SQLITE_DROP_TEMP_TABLE = 13; public const int SQLITE_DROP_TEMP_TRIGGER = 14; public const int SQLITE_DROP_TEMP_VIEW = 15; public const int SQLITE_DROP_TRIGGER = 16; public const int SQLITE_DROP_VIEW = 17; public const int SQLITE_INSERT = 18; public const int SQLITE_PRAGMA = 19; public const int SQLITE_READ = 20; public const int SQLITE_SELECT = 21; public const int SQLITE_TRANSACTION = 22; public const int SQLITE_UPDATE = 23; public const int SQLITE_ATTACH = 24; public const int SQLITE_DETACH = 25; public const int SQLITE_ALTER_TABLE = 26; public const int SQLITE_REINDEX = 27; public const int SQLITE_ANALYZE = 28; public const int SQLITE_CREATE_VTABLE = 29; public const int SQLITE_DROP_VTABLE = 30; public const int SQLITE_FUNCTION = 31; public const int SQLITE_SAVEPOINT = 32; public const int SQLITE_COPY = 0; public const int SQLITE_RECURSIVE = 33; public const int SQLITE_CHECKPOINT_PASSIVE = 0; public const int SQLITE_CHECKPOINT_FULL = 1; public const int SQLITE_CHECKPOINT_RESTART = 2; public const int SQLITE_CHECKPOINT_TRUNCATE = 3; public const int SQLITE_DBSTATUS_LOOKASIDE_USED = 0; public const int SQLITE_DBSTATUS_CACHE_USED = 1; public const int SQLITE_DBSTATUS_SCHEMA_USED = 2; public const int SQLITE_DBSTATUS_STMT_USED = 3; public const int SQLITE_DBSTATUS_LOOKASIDE_HIT = 4; public const int SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = 5; public const int SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = 6; public const int SQLITE_DBSTATUS_CACHE_HIT = 7; public const int SQLITE_DBSTATUS_CACHE_MISS = 8; public const int SQLITE_DBSTATUS_CACHE_WRITE = 9; public const int SQLITE_DBSTATUS_DEFERRED_FKS = 10; public const int SQLITE_STATUS_MEMORY_USED = 0; public const int SQLITE_STATUS_PAGECACHE_USED = 1; public const int SQLITE_STATUS_PAGECACHE_OVERFLOW = 2; public const int SQLITE_STATUS_SCRATCH_USED = 3; public const int SQLITE_STATUS_SCRATCH_OVERFLOW = 4; public const int SQLITE_STATUS_MALLOC_SIZE = 5; public const int SQLITE_STATUS_PARSER_STACK = 6; public const int SQLITE_STATUS_PAGECACHE_SIZE = 7; public const int SQLITE_STATUS_SCRATCH_SIZE = 8; public const int SQLITE_STATUS_MALLOC_COUNT = 9; public const int SQLITE_STMTSTATUS_FULLSCAN_STEP = 1; public const int SQLITE_STMTSTATUS_SORT = 2; public const int SQLITE_STMTSTATUS_AUTOINDEX = 3; public const int SQLITE_STMTSTATUS_VM_STEP = 4; public const int SQLITE_DENY = 1; public const int SQLITE_IGNORE = 2; public const int SQLITE_TRACE_STMT = 1; public const int SQLITE_TRACE_PROFILE = 2; public const int SQLITE_TRACE_ROW = 4; public const int SQLITE_TRACE_CLOSE = 8; public const int SQLITE_SERIALIZE_NOCOPY = 1; public const int SQLITE_DESERIALIZE_FREEONCLOSE = 1; public const int SQLITE_DESERIALIZE_RESIZEABLE = 2; public const int SQLITE_DESERIALIZE_READONLY = 4; private static ISQLite3Provider Provider { get { if (_imp == null) { throw new Exception("You need to call SQLitePCL.raw.SetProvider(). If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init()."); } return _imp; } } static raw() { _frozen = false; } public static void SetProvider(ISQLite3Provider imp) { if (!_frozen) { imp.sqlite3_libversion_number(); _imp = imp; } } public static void FreezeProvider(bool b = true) { _frozen = b; } public static string GetNativeLibraryName() { return Provider.GetNativeLibraryName(); } public static int sqlite3_open(utf8z filename, out sqlite3 db) { IntPtr db2; int result = Provider.sqlite3_open(filename, out db2); db = sqlite3.New(db2); return result; } public static int sqlite3_open(string filename, out sqlite3 db) { return sqlite3_open(filename.to_utf8z(), out db); } public static int sqlite3_open_v2(utf8z filename, out sqlite3 db, int flags, utf8z vfs) { IntPtr db2; int result = Provider.sqlite3_open_v2(filename, out db2, flags, vfs); db = sqlite3.New(db2); return result; } public static int sqlite3_open_v2(string filename, out sqlite3 db, int flags, string vfs) { return sqlite3_open_v2(filename.to_utf8z(), out db, flags, vfs.to_utf8z()); } public static int sqlite3__vfs__delete(utf8z vfs, utf8z pathname, int syncdir) { return Provider.sqlite3__vfs__delete(vfs, pathname, syncdir); } public static int sqlite3__vfs__delete(string vfs, string pathname, int syncdir) { return sqlite3__vfs__delete(vfs.to_utf8z(), pathname.to_utf8z(), syncdir); } internal static int internal_sqlite3_close_v2(IntPtr p) { return Provider.sqlite3_close_v2(p); } internal static int internal_sqlite3_close(IntPtr p) { return Provider.sqlite3_close(p); } public static int sqlite3_close_v2(sqlite3 db) { return db.manual_close_v2(); } public static int sqlite3_close(sqlite3 db) { return db.manual_close(); } public static int sqlite3_enable_shared_cache(int enable) { return Provider.sqlite3_enable_shared_cache(enable); } public static void sqlite3_interrupt(sqlite3 db) { Provider.sqlite3_interrupt(db); } public static int sqlite3_config_log(delegate_log f, object v) { return Provider.sqlite3_config_log(f, v); } public static int sqlite3_config_log(strdelegate_log f, object v) { delegate_log f2 = ((f != null) ? ((delegate_log)delegate(object ob, int e, utf8z msg) { f(ob, e, msg.utf8_to_string()); }) : null); return sqlite3_config_log(f2, v); } public static void sqlite3_log(int errcode, utf8z s) { Provider.sqlite3_log(errcode, s); } public static void sqlite3_log(int errcode, string s) { sqlite3_log(errcode, s.to_utf8z()); } public static void sqlite3_commit_hook(sqlite3 db, delegate_commit f, object v) { Provider.sqlite3_commit_hook(db, f, v); } public static void sqlite3_rollback_hook(sqlite3 db, delegate_rollback f, object v) { Provider.sqlite3_rollback_hook(db, f, v); } public static void sqlite3_trace(sqlite3 db, delegate_trace f, object v) { Provider.sqlite3_trace(db, f, v); } public static void sqlite3_trace(sqlite3 db, strdelegate_trace f, object v) { delegate_trace f2 = ((f != null) ? ((delegate_trace)delegate(object ob, utf8z sp) { f(v, sp.utf8_to_string()); }) : null); sqlite3_trace(db, f2, v); } public static void sqlite3_profile(sqlite3 db, delegate_profile f, object v) { Provider.sqlite3_profile(db, f, v); } public static void sqlite3_profile(sqlite3 db, strdelegate_profile f, object v) { delegate_profile f2 = ((f != null) ? ((delegate_profile)delegate(object ob, utf8z sp, long ns) { f(v, sp.utf8_to_string(), ns); }) : null); sqlite3_profile(db, f2, v); } public static void sqlite3_progress_handler(sqlite3 db, int instructions, delegate_progress func, object v) { Provider.sqlite3_progress_handler(db, instructions, func, v); } public static void sqlite3_update_hook(sqlite3 db, delegate_update f, object v) { Provider.sqlite3_update_hook(db, f, v); } public static void sqlite3_update_hook(sqlite3 db, strdelegate_update f, object v) { delegate_update f2 = ((f != null) ? ((delegate_update)delegate(object ob, int typ, utf8z dbname, utf8z tbl, long rowid) { f(ob, typ, dbname.utf8_to_string(), tbl.utf8_to_string(), rowid); }) : null); sqlite3_update_hook(db, f2, v); } public static int sqlite3_create_collation(sqlite3 db, string name, object v, strdelegate_collation f) { byte[] name2 = name.to_utf8_with_z(); delegate_collation func = ((f != null) ? ((delegate_collation)((object ob, ReadOnlySpan<byte> s1, ReadOnlySpan<byte> s2) => f(ob, s1.utf8_span_to_string(), s2.utf8_span_to_string()))) : null); return Provider.sqlite3_create_collation(db, name2, v, func); } public static int sqlite3__create_collation_utf8(sqlite3 db, string name, object v, delegate_collation f) { byte[] name2 = name.to_utf8_with_z(); return Provider.sqlite3_create_collation(db, name2, v, f); } public static int sqlite3_create_function(sqlite3 db, string name, int nArg, int flags, object v, delegate_function_scalar func) { byte[] name2 = name.to_utf8_with_z(); return Provider.sqlite3_create_function(db, name2, nArg, flags, v, func); } public static int sqlite3_create_function(sqlite3 db, string name, int nArg, int flags, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final) { byte[] name2 = name.to_utf8_with_z(); return Provider.sqlite3_create_function(db, name2, nArg, flags, v, func_step, func_final); } public static int sqlite3_create_function(sqlite3 db, string name, int nArg, object v, delegate_function_scalar func) { return sqlite3_create_function(db, name, nArg, 0, v, func); } public static int sqlite3_create_function(sqlite3 db, string name, int nArg, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final) { return sqlite3_create_function(db, name, nArg, 0, v, func_step, func_final); } public static int sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg) { return Provider.sqlite3_db_status(db, op, out current, out highest, resetFlg); } public unsafe static string utf8_span_to_string(this ReadOnlySpan<byte> p) { if (p.Length == 0) { return ""; } fixed (byte* bytes = p) { return Encoding.UTF8.GetString(bytes, p.Length); } } public static int sqlite3_key(sqlite3 db, ReadOnlySpan<byte> k) { return Provider.sqlite3_key(db, k); } public static int sqlite3_key_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return Provider.sqlite3_key_v2(db, name, k); } public static int sqlite3_rekey(sqlite3 db, ReadOnlySpan<byte> k) { return Provider.sqlite3_rekey(db, k); } public static int sqlite3_rekey_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return Provider.sqlite3_rekey_v2(db, name, k); } public static utf8z sqlite3_libversion() { return Provider.sqlite3_libversion(); } public static int sqlite3_libversion_number() { return Provider.sqlite3_libversion_number(); } public static int sqlite3_threadsafe() { return Provider.sqlite3_threadsafe(); } public static int sqlite3_initialize() { return Provider.sqlite3_initialize(); } public static int sqlite3_shutdown() { return Provider.sqlite3_shutdown(); } public static int sqlite3_limit(sqlite3 db, int id, int newVal) { return Provider.sqlite3_limit(db, id, newVal); } public static int sqlite3_config(int op) { return Provider.sqlite3_config(op); } public static int sqlite3_config(int op, int val) { return Provider.sqlite3_config(op, val); } public static int sqlite3_db_config(sqlite3 db, int op, utf8z val) { return Provider.sqlite3_db_config(db, op, val); } public static int sqlite3_db_config(sqlite3 db, int op, int val, out int result) { return Provider.sqlite3_db_config(db, op, val, out result); } public static int sqlite3_db_config(sqlite3 db, int op, IntPtr ptr, int int0, int int1) { return Provider.sqlite3_db_config(db, op, ptr, int0, int1); } public static int sqlite3_enable_load_extension(sqlite3 db, int onoff) { return Provider.sqlite3_enable_load_extension(db, onoff); } public static int sqlite3_load_extension(sqlite3 db, utf8z file, utf8z proc, out utf8z errmsg) { return Provider.sqlite3_load_extension(db, file, proc, out errmsg); } public static utf8z sqlite3_sourceid() { return Provider.sqlite3_sourceid(); } public static long sqlite3_memory_used() { return Provider.sqlite3_memory_used(); } public static long sqlite3_memory_highwater(int resetFlag) { return Provider.sqlite3_memory_highwater(resetFlag); } public static long sqlite3_soft_heap_limit64(long n) { return Provider.sqlite3_soft_heap_limit64(n); } public static long sqlite3_hard_heap_limit64(long n) { return Provider.sqlite3_hard_heap_limit64(n); } public static int sqlite3_status(int op, out int current, out int highwater, int resetFlag) { return Provider.sqlite3_status(op, out current, out highwater, resetFlag); } public static utf8z sqlite3_errmsg(sqlite3 db) { return Provider.sqlite3_errmsg(db); } public static int sqlite3_db_readonly(sqlite3 db, utf8z dbName) { return Provider.sqlite3_db_readonly(db, dbName); } public static int sqlite3_db_readonly(sqlite3 db, string dbName) { return sqlite3_db_readonly(db, dbName.to_utf8z()); } public static utf8z sqlite3_db_filename(sqlite3 db, utf8z att) { return Provider.sqlite3_db_filename(db, att); } public static utf8z sqlite3_db_filename(sqlite3 db, string att) { return sqlite3_db_filename(db, att.to_utf8z()); } public static long sqlite3_last_insert_rowid(sqlite3 db) { return Provider.sqlite3_last_insert_rowid(db); } public static int sqlite3_changes(sqlite3 db) { return Provider.sqlite3_changes(db); } public static int sqlite3_total_changes(sqlite3 db) { return Provider.sqlite3_total_changes(db); } public static int sqlite3_get_autocommit(sqlite3 db) { return Provider.sqlite3_get_autocommit(db); } public static int sqlite3_busy_timeout(sqlite3 db, int ms) { return Provider.sqlite3_busy_timeout(db, ms); } public static int sqlite3_extended_result_codes(sqlite3 db, int onoff) { return Provider.sqlite3_extended_result_codes(db, onoff); } public static int sqlite3_errcode(sqlite3 db) { return Provider.sqlite3_errcode(db); } public static int sqlite3_extended_errcode(sqlite3 db) { return Provider.sqlite3_extended_errcode(db); } public static utf8z sqlite3_errstr(int rc) { return Provider.sqlite3_errstr(rc); } public static int sqlite3_prepare_v2(sqlite3 db, ReadOnlySpan<byte> sql, out sqlite3_stmt stmt) { IntPtr stmt2; ReadOnlySpan<byte> remain; int result = Provider.sqlite3_prepare_v2(db, sql, out stmt2, out remain); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v2(sqlite3 db, utf8z sql, out sqlite3_stmt stmt) { IntPtr stmt2; utf8z remain; int result = Provider.sqlite3_prepare_v2(db, sql, out stmt2, out remain); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v2(sqlite3 db, string sql, out sqlite3_stmt stmt) { byte[] array = sql.to_utf8_with_z(); ReadOnlySpan<byte> sql2 = new ReadOnlySpan<byte>(array); ReadOnlySpan<byte> tail; return sqlite3_prepare_v2(db, sql2, out stmt, out tail); } public static int sqlite3_prepare_v2(sqlite3 db, ReadOnlySpan<byte> sql, out sqlite3_stmt stmt, out ReadOnlySpan<byte> tail) { IntPtr stmt2; int result = Provider.sqlite3_prepare_v2(db, sql, out stmt2, out tail); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v2(sqlite3 db, utf8z sql, out sqlite3_stmt stmt, out utf8z tail) { IntPtr stmt2; int result = Provider.sqlite3_prepare_v2(db, sql, out stmt2, out tail); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v2(sqlite3 db, string sql, out sqlite3_stmt stmt, out string tail) { byte[] array = sql.to_utf8_with_z(); ReadOnlySpan<byte> sql2 = new ReadOnlySpan<byte>(array); ReadOnlySpan<byte> tail2; int result = sqlite3_prepare_v2(db, sql2, out stmt, out tail2); tail = tail2.Slice(0, tail2.Length - 1).utf8_span_to_string(); return result; } public static int sqlite3_prepare_v3(sqlite3 db, ReadOnlySpan<byte> sql, uint flags, out sqlite3_stmt stmt) { IntPtr stmt2; ReadOnlySpan<byte> remain; int result = Provider.sqlite3_prepare_v3(db, sql, flags, out stmt2, out remain); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v3(sqlite3 db, utf8z sql, uint flags, out sqlite3_stmt stmt) { IntPtr stmt2; utf8z remain; int result = Provider.sqlite3_prepare_v3(db, sql, flags, out stmt2, out remain); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v3(sqlite3 db, string sql, uint flags, out sqlite3_stmt stmt) { byte[] array = sql.to_utf8_with_z(); ReadOnlySpan<byte> sql2 = new ReadOnlySpan<byte>(array); ReadOnlySpan<byte> tail; return sqlite3_prepare_v3(db, sql2, flags, out stmt, out tail); } public static int sqlite3_prepare_v3(sqlite3 db, ReadOnlySpan<byte> sql, uint flags, out sqlite3_stmt stmt, out ReadOnlySpan<byte> tail) { IntPtr stmt2; int result = Provider.sqlite3_prepare_v3(db, sql, flags, out stmt2, out tail); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v3(sqlite3 db, utf8z sql, uint flags, out sqlite3_stmt stmt, out utf8z tail) { IntPtr stmt2; int result = Provider.sqlite3_prepare_v3(db, sql, flags, out stmt2, out tail); stmt = sqlite3_stmt.From(stmt2, db); return result; } public static int sqlite3_prepare_v3(sqlite3 db, string sql, uint flags, out sqlite3_stmt stmt, out string tail) { byte[] array = sql.to_utf8_with_z(); ReadOnlySpan<byte> sql2 = new ReadOnlySpan<byte>(array); ReadOnlySpan<byte> tail2; int result = sqlite3_prepare_v3(db, sql2, flags, out stmt, out tail2); tail = tail2.Slice(0, tail2.Length - 1).utf8_span_to_string(); return result; } public static int sqlite3_exec(sqlite3 db, string sql, strdelegate_exec callback, object user_data, out string errMsg) { delegate_exec callback2 = ((callback == null) ? null : ((delegate_exec)delegate(object ob, IntPtr[] values, IntPtr[] names) { string[] array = new string[values.Length]; string[] array2 = new string[names.Length]; for (int i = 0; i < values.Length; i++) { array[i] = util.from_utf8_z(values[i]); array2[i] = util.from_utf8_z(names[i]); } return callback(ob, array, array2); })); IntPtr errMsg2; int result = Provider.sqlite3_exec(db, sql.to_utf8z(), callback2, user_data, out errMsg2); if (errMsg2 == IntPtr.Zero) { errMsg = null; return result; } errMsg = util.from_utf8_z(errMsg2); Provider.sqlite3_free(errMsg2); return result; } public static int sqlite3_exec(sqlite3 db, string sql, out string errMsg) { IntPtr errMsg2; int result = Provider.sqlite3_exec(db, sql.to_utf8z(), null, null, out errMsg2); if (errMsg2 == IntPtr.Zero) { errMsg = null; return result; } errMsg = util.from_utf8_z(errMsg2); Provider.sqlite3_free(errMsg2); return result; } public static int sqlite3_exec(sqlite3 db, string sql) { IntPtr errMsg; int result = Provider.sqlite3_exec(db, sql.to_utf8z(), null, null, out errMsg); if (!(errMsg == IntPtr.Zero)) { Provider.sqlite3_free(errMsg); } return result; } public static int sqlite3_step(sqlite3_stmt stmt) { return Provider.sqlite3_step(stmt); } public static int sqlite3_finalize(sqlite3_stmt stmt) { return stmt.manual_close(); } public static int internal_sqlite3_finalize(IntPtr stmt) { return Provider.sqlite3_finalize(stmt); } public static int sqlite3_reset(sqlite3_stmt stmt) { return Provider.sqlite3_reset(stmt); } public static int sqlite3_clear_bindings(sqlite3_stmt stmt) { return Provider.sqlite3_clear_bindings(stmt); } public static int sqlite3_stmt_status(sqlite3_stmt stmt, int op, int resetFlg) { return Provider.sqlite3_stmt_status(stmt, op, resetFlg); } public static int sqlite3_complete(utf8z sql) { return Provider.sqlite3_complete(sql); } public static int sqlite3_complete(string sql) { return sqlite3_complete(sql.to_utf8z()); } public static int sqlite3_compileoption_used(utf8z s) { return Provider.sqlite3_compileoption_used(s); } public static int sqlite3_compileoption_used(string s) { return sqlite3_compileoption_used(s.to_utf8z()); } public static utf8z sqlite3_compileoption_get(int n) { return Provider.sqlite3_compileoption_get(n); } public static int sqlite3_table_column_metadata(sqlite3 db, utf8z dbName, utf8z tblName, utf8z colName, out utf8z dataType, out utf8z collSeq, out int notNull, out int primaryKey, out int autoInc) { return Provider.sqlite3_table_column_metadata(db, dbName, tblName, colName, out dataType, out collSeq, out notNull, out primaryKey, out autoInc); } public static int sqlite3_table_column_metadata(sqlite3 db, string dbName, string tblName, string colName, out string dataType, out string collSeq, out int notNull, out int primaryKey, out int autoInc) { utf8z dataType2; utf8z collSeq2; int result = sqlite3_table_column_metadata(db, dbName.to_utf8z(), tblName.to_utf8z(), colName.to_utf8z(), out dataType2, out collSeq2, out notNull, out primaryKey, out autoInc); dataType = dataType2.utf8_to_string(); collSeq = collSeq2.utf8_to_string(); return result; } public static utf8z sqlite3_sql(sqlite3_stmt stmt) { return Provider.sqlite3_sql(stmt); } public static sqlite3 sqlite3_db_handle(sqlite3_stmt stmt) { return stmt.db; } public static sqlite3_stmt sqlite3_next_stmt(sqlite3 db, sqlite3_stmt stmt) { IntPtr intPtr = Provider.sqlite3_next_stmt(db, stmt?.ptr ?? IntPtr.Zero); if (intPtr == IntPtr.Zero) { return null; } return db.find_stmt(intPtr); } public static int sqlite3_bind_zeroblob(sqlite3_stmt stmt, int index, int size) { return Provider.sqlite3_bind_zeroblob(stmt, index, size); } public static utf8z sqlite3_bind_parameter_name(sqlite3_stmt stmt, int index) { return Provider.sqlite3_bind_parameter_name(stmt, index); } public static object sqlite3_user_data(sqlite3_context context) { return context.user_data; } public static void sqlite3_result_null(sqlite3_context context) { Provider.sqlite3_result_null(context.ptr); } public static void sqlite3_result_blob(sqlite3_context context, ReadOnlySpan<byte> val) { Provider.sqlite3_result_blob(context.ptr, val); } public static void sqlite3_result_error(sqlite3_context context, ReadOnlySpan<byte> val) { Provider.sqlite3_result_error(context.ptr, val); } public static void sqlite3_result_error(sqlite3_context context, utf8z val) { Provider.sqlite3_result_error(context.ptr, val); } public static void sqlite3_result_error(sqlite3_context context, string val) { sqlite3_result_error(context, val.to_utf8z()); } public static void sqlite3_result_text(sqlite3_context context, ReadOnlySpan<byte> val) { Provider.sqlite3_result_text(context.ptr, val); } public static void sqlite3_result_text(sqlite3_context context, utf8z val) { Provider.sqlite3_result_text(context.ptr, val); } public static void sqlite3_result_text(sqlite3_context context, string val) { sqlite3_result_text(context, val.to_utf8z()); } public static void sqlite3_result_double(sqlite3_context context, double val) { Provider.sqlite3_result_double(context.ptr, val); } public static void sqlite3_result_int(sqlite3_context context, int val) { Provider.sqlite3_result_int(context.ptr, val); } public static void sqlite3_result_int64(sqlite3_context context, long val) { Provider.sqlite3_result_int64(context.ptr, val); } public static void sqlite3_result_zeroblob(sqlite3_context context, int n) { Provider.sqlite3_result_zeroblob(context.ptr, n); } public static void sqlite3_result_error_toobig(sqlite3_context context) { Provider.sqlite3_result_error_toobig(context.ptr); } public static void sqlite3_result_error_nomem(sqlite3_context context) { Provider.sqlite3_result_error_nomem(context.ptr); } public static void sqlite3_result_error_code(sqlite3_context context, int code) { Provider.sqlite3_result_error_code(context.ptr, code); } public static ReadOnlySpan<byte> sqlite3_value_blob(sqlite3_value val) { return Provider.sqlite3_value_blob(val.ptr); } public static int sqlite3_value_bytes(sqlite3_value val) { return Provider.sqlite3_value_bytes(val.ptr); } public static double sqlite3_value_double(sqlite3_value val) { return Provider.sqlite3_value_double(val.ptr); } public static int sqlite3_value_int(sqlite3_value val) { return Provider.sqlite3_value_int(val.ptr); } public static long sqlite3_value_int64(sqlite3_value val) { return Provider.sqlite3_value_int64(val.ptr); } public static int sqlite3_value_type(sqlite3_value val) { return Provider.sqlite3_value_type(val.ptr); } public static utf8z sqlite3_value_text(sqlite3_value val) { return Provider.sqlite3_value_text(val.ptr); } public static int sqlite3_bind_blob(sqlite3_stmt stmt, int index, ReadOnlySpan<byte> blob) { return Provider.sqlite3_bind_blob(stmt, index, blob); } public static int sqlite3_bind_double(sqlite3_stmt stmt, int index, double val) { return Provider.sqlite3_bind_double(stmt, index, val); } public static int sqlite3_bind_int(sqlite3_stmt stmt, int index, int val) { return Provider.sqlite3_bind_int(stmt, index, val); } public static int sqlite3_bind_int64(sqlite3_stmt stmt, int index, long val) { return Provider.sqlite3_bind_int64(stmt, index, val); } public static int sqlite3_bind_null(sqlite3_stmt stmt, int index) { return Provider.sqlite3_bind_null(stmt, index); } public static int sqlite3_bind_text(sqlite3_stmt stmt, int index, ReadOnlySpan<byte> val) { return Provider.sqlite3_bind_text(stmt, index, val); } public static int sqlite3_bind_text16(sqlite3_stmt stmt, int index, ReadOnlySpan<char> val) { return Provider.sqlite3_bind_text16(stmt, index, val); } public static int sqlite3_bind_text(sqlite3_stmt stmt, int index, utf8z val) { return Provider.sqlite3_bind_text(stmt, index, val); } public unsafe static int sqlite3_bind_text(sqlite3_stmt stmt, int index, string val) { if (val != null && val.Length <= 512) { int byteCount = Encoding.UTF8.GetByteCount(val); if (byteCount <= 512 && byteCount > 0) { Span<byte> span = stackalloc byte[byteCount]; fixed (char* chars = val) { fixed (byte* bytes = span) { Encoding.UTF8.GetBytes(chars, val.Length, bytes, byteCount); } } return sqlite3_bind_text(stmt, index, span); } } return sqlite3_bind_text(stmt, index, val.to_utf8z()); } public static int sqlite3_bind_parameter_count(sqlite3_stmt stmt) { return Provider.sqlite3_bind_parameter_count(stmt); } public static int sqlite3_bind_parameter_index(sqlite3_stmt stmt, utf8z strName) { return Provider.sqlite3_bind_parameter_index(stmt, strName); } public static int sqlite3_bind_parameter_index(sqlite3_stmt stmt, string strName) { return sqlite3_bind_parameter_index(stmt, strName.to_utf8z()); } public static int sqlite3_stmt_isexplain(sqlite3_stmt stmt) { return _imp.sqlite3_stmt_isexplain(stmt); } public static int sqlite3_stmt_busy(sqlite3_stmt stmt) { return Provider.sqlite3_stmt_busy(stmt); } public static int sqlite3_stmt_readonly(sqlite3_stmt stmt) { return Provider.sqlite3_stmt_readonly(stmt); } public static utf8z sqlite3_column_database_name(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_database_name(stmt, index); } public static utf8z sqlite3_column_name(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_name(stmt, index); } public static utf8z sqlite3_column_origin_name(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_origin_name(stmt, index); } public static utf8z sqlite3_column_table_name(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_table_name(stmt, index); } public static utf8z sqlite3_column_text(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_text(stmt, index); } public static int sqlite3_column_count(sqlite3_stmt stmt) { return Provider.sqlite3_column_count(stmt); } public static int sqlite3_data_count(sqlite3_stmt stmt) { return Provider.sqlite3_data_count(stmt); } public static double sqlite3_column_double(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_double(stmt, index); } public static int sqlite3_column_int(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_int(stmt, index); } public static long sqlite3_column_int64(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_int64(stmt, index); } public static ReadOnlySpan<byte> sqlite3_column_blob(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_blob(stmt, index); } public static int sqlite3_column_bytes(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_bytes(stmt, index); } public static int sqlite3_column_type(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_type(stmt, index); } public static utf8z sqlite3_column_decltype(sqlite3_stmt stmt, int index) { return Provider.sqlite3_column_decltype(stmt, index); } public static sqlite3_backup sqlite3_backup_init(sqlite3 destDb, string destName, sqlite3 sourceDb, string sourceName) { return Provider.sqlite3_backup_init(destDb, destName.to_utf8z(), sourceDb, sourceName.to_utf8z()); } public static int sqlite3_backup_step(sqlite3_backup backup, int nPage) { return Provider.sqlite3_backup_step(backup, nPage); } public static int sqlite3_backup_remaining(sqlite3_backup backup) { return Provider.sqlite3_backup_remaining(backup); } public static int sqlite3_backup_pagecount(sqlite3_backup backup) { return Provider.sqlite3_backup_pagecount(backup); } public static int sqlite3_backup_finish(sqlite3_backup backup) { return backup.manual_close(); } internal static int internal_sqlite3_backup_finish(IntPtr p) { return Provider.sqlite3_backup_finish(p); } public static int sqlite3_snapshot_get(sqlite3 db, string schema, out sqlite3_snapshot snap) { IntPtr snap2; int result = Provider.sqlite3_snapshot_get(db, schema.to_utf8z(), out snap2); snap = sqlite3_snapshot.From(snap2); return result; } public static int sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2) { return Provider.sqlite3_snapshot_cmp(p1, p2); } public static int sqlite3_snapshot_open(sqlite3 db, string schema, sqlite3_snapshot snap) { return Provider.sqlite3_snapshot_open(db, schema.to_utf8z(), snap); } public static int sqlite3_snapshot_recover(sqlite3 db, string name) { return Provider.sqlite3_snapshot_recover(db, name.to_utf8z()); } public static void sqlite3_snapshot_free(sqlite3_snapshot snap) { snap.manual_close(); } internal static void internal_sqlite3_snapshot_free(IntPtr p) { Provider.sqlite3_snapshot_free(p); } public static int sqlite3_blob_open(sqlite3 db, utf8z db_utf8, utf8z table_utf8, utf8z col_utf8, long rowid, int flags, out sqlite3_blob blob) { return Provider.sqlite3_blob_open(db, db_utf8, table_utf8, col_utf8, rowid, flags, out blob); } public static int sqlite3_blob_open(sqlite3 db, string sdb, string table, string col, long rowid, int flags, out sqlite3_blob blob) { return sqlite3_blob_open(db, sdb.to_utf8z(), table.to_utf8z(), col.to_utf8z(), rowid, flags, out blob); } public static int sqlite3_blob_bytes(sqlite3_blob blob) { return Provider.sqlite3_blob_bytes(blob); } public static int sqlite3_blob_reopen(sqlite3_blob blob, long rowid) { return Provider.sqlite3_blob_reopen(blob, rowid); } public static int sqlite3_blob_write(sqlite3_blob blob, ReadOnlySpan<byte> b, int offset) { return Provider.sqlite3_blob_write(blob, b, offset); } public static int sqlite3_blob_read(sqlite3_blob blob, Span<byte> b, int offset) { return Provider.sqlite3_blob_read(blob, b, offset); } public static int sqlite3_blob_close(sqlite3_blob blob) { return blob.manual_close(); } internal static int internal_sqlite3_blob_close(IntPtr blob) { return Provider.sqlite3_blob_close(blob); } public static int sqlite3_wal_autocheckpoint(sqlite3 db, int n) { return Provider.sqlite3_wal_autocheckpoint(db, n); } public static int sqlite3_wal_checkpoint(sqlite3 db, string dbName) { return Provider.sqlite3_wal_checkpoint(db, dbName.to_utf8z()); } public static int sqlite3_wal_checkpoint_v2(sqlite3 db, string dbName, int eMode, out int logSize, out int framesCheckPointed) { return Provider.sqlite3_wal_checkpoint_v2(db, dbName.to_utf8z(), eMode, out logSize, out framesCheckPointed); } public static int sqlite3_set_authorizer(sqlite3 db, delegate_authorizer f, object user_data) { return Provider.sqlite3_set_authorizer(db, f, user_data); } public static int sqlite3_set_authorizer(sqlite3 db, strdelegate_authorizer f, object user_data) { delegate_authorizer f2 = ((f != null) ? ((delegate_authorizer)((object ob, int a, utf8z p0, utf8z p1, utf8z dbname, utf8z v) => f(ob, a, p0.utf8_to_string(), p1.utf8_to_string(), dbname.utf8_to_string(), v.utf8_to_string()))) : null); return sqlite3_set_authorizer(db, f2, user_data); } public static int sqlite3_win32_set_directory(int typ, string path) { return Provider.sqlite3_win32_set_directory(typ, path.to_utf8z()); } public static int sqlite3_keyword_count() { return Provider.sqlite3_keyword_count(); } public static int sqlite3_keyword_name(int i, out string name) { return Provider.sqlite3_keyword_name(i, out name); } public static IntPtr sqlite3_malloc(int n) { return Provider.sqlite3_malloc(n); } public static IntPtr sqlite3_malloc64(long n) { return Provider.sqlite3_malloc64(n); } public static void sqlite3_free(IntPtr p) { Provider.sqlite3_free(p); } public static IntPtr sqlite3_serialize(sqlite3 db, string schema, out long size, int flags) { return Provider.sqlite3_serialize(db, schema.to_utf8z(), out size, flags); } public static int sqlite3_deserialize(sqlite3 db, string schema, IntPtr data, long deserializedDataSize, long maxDataSize, int flags) { return Provider.sqlite3_deserialize(db, schema.to_utf8z(), data, deserializedDataSize, maxDataSize, flags); } } public class sqlite3_backup : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; private sqlite3_backup() : base(IntPtr.Zero, ownsHandle: true) { } public static sqlite3_backup From(IntPtr p) { sqlite3_backup obj = new sqlite3_backup(); obj.SetHandle(p); return obj; } protected override bool ReleaseHandle() { raw.internal_sqlite3_backup_finish(handle); return true; } public int manual_close() { int result = raw.internal_sqlite3_backup_finish(handle); handle = IntPtr.Zero; return result; } } public class sqlite3_context { private IntPtr _p; private object _user_data; public object state; internal object user_data => _user_data; internal IntPtr ptr => _p; protected sqlite3_context(object user_data) { _user_data = user_data; } protected void set_context_ptr(IntPtr p) { _p = p; } } public class sqlite3_value { private IntPtr _p; internal IntPtr ptr => _p; public sqlite3_value(IntPtr p) { _p = p; } } public class sqlite3_blob : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; private sqlite3_blob() : base(IntPtr.Zero, ownsHandle: true) { } internal static sqlite3_blob From(IntPtr p) { sqlite3_blob obj = new sqlite3_blob(); obj.SetHandle(p); return obj; } protected override bool ReleaseHandle() { raw.internal_sqlite3_blob_close(handle); return true; } public int manual_close() { int result = raw.internal_sqlite3_blob_close(handle); handle = IntPtr.Zero; return result; } } public class sqlite3_snapshot : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; private sqlite3_snapshot() : base(IntPtr.Zero, ownsHandle: true) { } internal static sqlite3_snapshot From(IntPtr p) { sqlite3_snapshot obj = new sqlite3_snapshot(); obj.SetHandle(p); return obj; } protected override bool ReleaseHandle() { raw.internal_sqlite3_snapshot_free(handle); return true; } public void manual_close() { raw.internal_sqlite3_snapshot_free(handle); handle = IntPtr.Zero; } } public class sqlite3_stmt : SafeHandle { private sqlite3 _db; public override bool IsInvalid => handle == IntPtr.Zero; internal IntPtr ptr => handle; internal sqlite3 db => _db; internal static sqlite3_stmt From(IntPtr p, sqlite3 db) { sqlite3_stmt sqlite3_stmt2 = new sqlite3_stmt(); sqlite3_stmt2.SetHandle(p); db.add_stmt(sqlite3_stmt2); sqlite3_stmt2._db = db; return sqlite3_stmt2; } private sqlite3_stmt() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { raw.internal_sqlite3_finalize(handle); _db.remove_stmt(this); return true; } public int manual_close() { int result = raw.internal_sqlite3_finalize(handle); handle = IntPtr.Zero; _db.remove_stmt(this); return result; } } public class sqlite3 : SafeHandle { private ConcurrentDictionary<IntPtr, sqlite3_stmt> _stmts; private IDisposable extra; public override bool IsInvalid => handle == IntPtr.Zero; private sqlite3() : base(IntPtr.Zero, ownsHandle: true) { } protected override bool ReleaseHandle() { raw.internal_sqlite3_close_v2(handle); dispose_extra(); return true; } public int manual_close_v2() { int result = raw.internal_sqlite3_close_v2(handle); handle = IntPtr.Zero; dispose_extra(); return result; } public int manual_close() { int result = raw.internal_sqlite3_close(handle); handle = IntPtr.Zero; dispose_extra(); return result; } internal static sqlite3 New(IntPtr p) { sqlite3 obj = new sqlite3(); obj.SetHandle(p); return obj; } public void enable_sqlite3_next_stmt(bool enabled) { if (enabled) { if (_stmts == null) { _stmts = new ConcurrentDictionary<IntPtr, sqlite3_stmt>(); } } else { _stmts = null; } } internal void add_stmt(sqlite3_stmt stmt) { if (_stmts != null) { _stmts[stmt.ptr] = stmt; } } internal sqlite3_stmt find_stmt(IntPtr p) { if (_stmts != null) { return _stmts[p]; } throw new Exception("The sqlite3_next_stmt() function is disabled. To enable it, call sqlite3.enable_sqlite3_next_stmt(true) immediately after opening the sqlite3 connection."); } internal void remove_stmt(sqlite3_stmt s) { if (_stmts != null) { _stmts.TryRemove(s.ptr, out var _); } } public T GetOrCreateExtra<T>(Func<T> f) where T : class, IDisposable { if (extra != null) { return (T)extra; } return (T)(extra = f()); } private void dispose_extra() { if (extra != null) { extra.Dispose(); extra = null; } } } public delegate int delegate_collation(object user_data, ReadOnlySpan<byte> s1, ReadOnlySpan<byte> s2); public delegate void delegate_update(object user_data, int type, utf8z database, utf8z table, long rowid); public delegate void delegate_log(object user_data, int errorCode, utf8z msg); public delegate int delegate_authorizer(object user_data, int action_code, utf8z param0, utf8z param1, utf8z dbName, utf8z inner_most_trigger_or_view); public delegate int delegate_exec(object user_data, IntPtr[] values, IntPtr[] names); public delegate int delegate_commit(object user_data); public delegate void delegate_rollback(object user_data); public delegate void delegate_trace(object user_data, utf8z statement); public delegate void delegate_profile(object user_data, utf8z statement, long ns); public delegate int delegate_progress(object user_data); public delegate void delegate_function_scalar(sqlite3_context ctx, object user_data, sqlite3_value[] args); public delegate void delegate_function_aggregate_step(sqlite3_context ctx, object user_data, sqlite3_value[] args); public delegate void delegate_function_aggregate_final(sqlite3_context ctx, object user_data); public interface ISQLite3Provider { string GetNativeLibraryName(); int sqlite3_open(utf8z filename, out IntPtr db); int sqlite3_open_v2(utf8z filename, out IntPtr db, int flags, utf8z vfs); int sqlite3_close_v2(IntPtr db); int sqlite3_close(IntPtr db); int sqlite3_enable_shared_cache(int enable); void sqlite3_interrupt(sqlite3 db); int sqlite3__vfs__delete(utf8z vfs, utf8z pathname, int syncDir); int sqlite3_threadsafe(); utf8z sqlite3_libversion(); int sqlite3_libversion_number(); utf8z sqlite3_sourceid(); long sqlite3_memory_used(); long sqlite3_memory_highwater(int resetFlag); long sqlite3_soft_heap_limit64(long n); long sqlite3_hard_heap_limit64(long n); int sqlite3_status(int op, out int current, out int highwater, int resetFlag); int sqlite3_db_readonly(sqlite3 db, utf8z dbName); utf8z sqlite3_db_filename(sqlite3 db, utf8z att); utf8z sqlite3_errmsg(sqlite3 db); long sqlite3_last_insert_rowid(sqlite3 db); int sqlite3_changes(sqlite3 db); int sqlite3_total_changes(sqlite3 db); int sqlite3_get_autocommit(sqlite3 db); int sqlite3_busy_timeout(sqlite3 db, int ms); int sqlite3_extended_result_codes(sqlite3 db, int onoff); int sqlite3_errcode(sqlite3 db); int sqlite3_extended_errcode(sqlite3 db); utf8z sqlite3_errstr(int rc); int sqlite3_prepare_v2(sqlite3 db, ReadOnlySpan<byte> sql, out IntPtr stmt, out ReadOnlySpan<byte> remain); int sqlite3_prepare_v3(sqlite3 db, ReadOnlySpan<byte> sql, uint flags, out IntPtr stmt, out ReadOnlySpan<byte> remain); [Obsolete] int sqlite3_prepare_v2(sqlite3 db, utf8z sql, out IntPtr stmt, out utf8z remain); [Obsolete] int sqlite3_prepare_v3(sqlite3 db, utf8z sql, uint flags, out IntPtr stmt, out utf8z remain); int sqlite3_step(sqlite3_stmt stmt); int sqlite3_finalize(IntPtr stmt); int sqlite3_reset(sqlite3_stmt stmt); int sqlite3_clear_bindings(sqlite3_stmt stmt); int sqlite3_stmt_status(sqlite3_stmt stmt, int op, int resetFlg); utf8z sqlite3_sql(sqlite3_stmt stmt); IntPtr sqlite3_db_handle(IntPtr stmt); IntPtr sqlite3_next_stmt(sqlite3 db, IntPtr stmt); int sqlite3_bind_zeroblob(sqlite3_stmt stmt, int index, int size); utf8z sqlite3_bind_parameter_name(sqlite3_stmt stmt, int index); int sqlite3_bind_blob(sqlite3_stmt stmt, int index, ReadOnlySpan<byte> blob); int sqlite3_bind_double(sqlite3_stmt stmt, int index, double val); int sqlite3_bind_int(sqlite3_stmt stmt, int index, int val); int sqlite3_bind_int64(sqlite3_stmt stmt, int index, long val); int sqlite3_bind_null(sqlite3_stmt stmt, int index); int sqlite3_bind_text(sqlite3_stmt stmt, int index, ReadOnlySpan<byte> text); int sqlite3_bind_text16(sqlite3_stmt stmt, int index, ReadOnlySpan<char> text); int sqlite3_bind_text(sqlite3_stmt stmt, int index, utf8z text); int sqlite3_bind_parameter_count(sqlite3_stmt stmt); int sqlite3_bind_parameter_index(sqlite3_stmt stmt, utf8z strName); utf8z sqlite3_column_database_name(sqlite3_stmt stmt, int index); utf8z sqlite3_column_name(sqlite3_stmt stmt, int index); utf8z sqlite3_column_origin_name(sqlite3_stmt stmt, int index); utf8z sqlite3_column_table_name(sqlite3_stmt stmt, int index); utf8z sqlite3_column_text(sqlite3_stmt stmt, int index); int sqlite3_data_count(sqlite3_stmt stmt); int sqlite3_column_count(sqlite3_stmt stmt); double sqlite3_column_double(sqlite3_stmt stmt, int index); int sqlite3_column_int(sqlite3_stmt stmt, int index); long sqlite3_column_int64(sqlite3_stmt stmt, int index); ReadOnlySpan<byte> sqlite3_column_blob(sqlite3_stmt stmt, int index); int sqlite3_column_bytes(sqlite3_stmt stmt, int index); int sqlite3_column_type(sqlite3_stmt stmt, int index); utf8z sqlite3_column_decltype(sqlite3_stmt stmt, int index); int sqlite3_snapshot_get(sqlite3 db, utf8z schema, out IntPtr snap); int sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2); int sqlite3_snapshot_open(sqlite3 db, utf8z schema, sqlite3_snapshot snap); int sqlite3_snapshot_recover(sqlite3 db, utf8z name); void sqlite3_snapshot_free(IntPtr snap); sqlite3_backup sqlite3_backup_init(sqlite3 destDb, utf8z destName, sqlite3 sourceDb, utf8z sourceName); int sqlite3_backup_step(sqlite3_backup backup, int nPage); int sqlite3_backup_remaining(sqlite3_backup backup); int sqlite3_backup_pagecount(sqlite3_backup backup); int sqlite3_backup_finish(IntPtr backup); int sqlite3_blob_open(sqlite3 db, utf8z db_utf8, utf8z table_utf8, utf8z col_utf8, long rowid, int flags, out sqlite3_blob blob); int sqlite3_blob_bytes(sqlite3_blob blob); int sqlite3_blob_reopen(sqlite3_blob blob, long rowid); int sqlite3_blob_write(sqlite3_blob blob, ReadOnlySpan<byte> b, int offset); int sqlite3_blob_read(sqlite3_blob blob, Span<byte> b, int offset); int sqlite3_blob_close(IntPtr blob); int sqlite3_config_log(delegate_log func, object v); void sqlite3_log(int errcode, utf8z s); void sqlite3_commit_hook(sqlite3 db, delegate_commit func, object v); void sqlite3_rollback_hook(sqlite3 db, delegate_rollback func, object v); void sqlite3_trace(sqlite3 db, delegate_trace func, object v); void sqlite3_profile(sqlite3 db, delegate_profile func, object v); void sqlite3_progress_handler(sqlite3 db, int instructions, delegate_progress func, object v); void sqlite3_update_hook(sqlite3 db, delegate_update func, object v); int sqlite3_create_collation(sqlite3 db, byte[] name, object v, delegate_collation func); int sqlite3_create_function(sqlite3 db, byte[] name, int nArg, int flags, object v, delegate_function_scalar func); int sqlite3_create_function(sqlite3 db, byte[] name, int nArg, int flags, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final); int sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg); void sqlite3_result_blob(IntPtr context, ReadOnlySpan<byte> val); void sqlite3_result_double(IntPtr context, double val); void sqlite3_result_error(IntPtr context, ReadOnlySpan<byte> strErr); void sqlite3_result_error(IntPtr context, utf8z strErr); void sqlite3_result_int(IntPtr context, int val); void sqlite3_result_int64(IntPtr context, long val); void sqlite3_result_null(IntPtr context); void sqlite3_result_text(IntPtr context, ReadOnlySpan<byte> val); void sqlite3_result_text(IntPtr context, utf8z val); void sqlite3_result_zeroblob(IntPtr context, int n); void sqlite3_result_error_toobig(IntPtr context); void sqlite3_result_error_nomem(IntPtr context); void sqlite3_result_error_code(IntPtr context, int code); ReadOnlySpan<byte> sqlite3_value_blob(IntPtr p); int sqlite3_value_bytes(IntPtr p); double sqlite3_value_double(IntPtr p); int sqlite3_value_int(IntPtr p); long sqlite3_value_int64(IntPtr p); int sqlite3_value_type(IntPtr p); utf8z sqlite3_value_text(IntPtr p); int sqlite3_stmt_isexplain(sqlite3_stmt stmt); int sqlite3_stmt_busy(sqlite3_stmt stmt); int sqlite3_stmt_readonly(sqlite3_stmt stmt); int sqlite3_exec(sqlite3 db, utf8z sql, delegate_exec callback, object user_data, out IntPtr errMsg); int sqlite3_complete(utf8z sql); int sqlite3_compileoption_used(utf8z sql); utf8z sqlite3_compileoption_get(int n); int sqlite3_wal_autocheckpoint(sqlite3 db, int n); int sqlite3_wal_checkpoint(sqlite3 db, utf8z dbName); int sqlite3_wal_checkpoint_v2(sqlite3 db, utf8z dbName, int eMode, out int logSize, out int framesCheckPointed); int sqlite3_table_column_metadata(sqlite3 db, utf8z dbName, utf8z tblName, utf8z colName, out utf8z dataType, out utf8z collSeq, out int notNull, out int primaryKey, out int autoInc); int sqlite3_set_authorizer(sqlite3 db, delegate_authorizer authorizer, object user_data); int sqlite3_stricmp(IntPtr p, IntPtr q); int sqlite3_strnicmp(IntPtr p, IntPtr q, int n); IntPtr sqlite3_malloc(int n); IntPtr sqlite3_malloc64(long n); void sqlite3_free(IntPtr p); int sqlite3_key(sqlite3 db, ReadOnlySpan<byte> key); int sqlite3_key_v2(sqlite3 db, utf8z dbname, ReadOnlySpan<byte> key); int sqlite3_rekey(sqlite3 db, ReadOnlySpan<byte> key); int sqlite3_rekey_v2(sqlite3 db, utf8z dbname, ReadOnlySpan<byte> key); int sqlite3_load_extension(sqlite3 db, utf8z zFile, utf8z zProc, out utf8z pzErrMsg); int sqlite3_initialize(); int sqlite3_shutdown(); int sqlite3_limit(sqlite3 db, int id, int newVal); int sqlite3_config(int op); int sqlite3_config(int op, int val); int sqlite3_db_config(sqlite3 db, int op, utf8z val); int sqlite3_db_config(sqlite3 db, int op, int val, out int result); int sqlite3_db_config(sqlite3 db, int op, IntPtr ptr, int int0, int int1); int sqlite3_enable_load_extension(sqlite3 db, int enable); int sqlite3_win32_set_directory(int typ, utf8z path); int sqlite3_keyword_count(); int sqlite3_keyword_name(int i, out string name); IntPtr sqlite3_serialize(sqlite3 db, utf8z schema, out long size, int flags); int sqlite3_deserialize(sqlite3 db, utf8z schema, IntPtr data, long szDb, long szBuf, int flags); } internal static class util { public static utf8z to_utf8z(this string s) { return utf8z.FromString(s); } public static byte[] to_utf8_with_z(this string sourceText) { if (sourceText == null) { return null; } byte[] array = new byte[Encoding.UTF8.GetByteCount(sourceText) + 1]; int bytes = Encoding.UTF8.GetBytes(sourceText, 0, sourceText.Length, array, 0); array[bytes] = 0; return array; } private static int my_strlen(IntPtr nativeString) { int i = 0; if (nativeString != IntPtr.Zero) { for (; Marshal.ReadByte(nativeString, i) > 0; i++) { } } return i; } public static string from_utf8_z(IntPtr nativeString) { return from_utf8(nativeString, my_strlen(nativeString)); } public unsafe static string from_utf8(IntPtr nativeString, int size) { string result = null; if (nativeString != IntPtr.Zero) { result = Encoding.UTF8.GetString((byte*)nativeString.ToPointer(), size); } return result; } } public readonly ref struct utf8z { private readonly ReadOnlySpan<byte> sp; public ref readonly byte GetPinnableReference() { return ref sp.GetPinnableReference(); } private utf8z(ReadOnlySpan<byte> a) { sp = a; } public static utf8z FromSpan(ReadOnlySpan<byte> span) { if (span.Length > 0 && span[span.Length - 1] != 0) { throw new ArgumentException("zero terminator required"); } return new utf8z(span); } public static utf8z FromString(string s) { if (s == null) { return new utf8z(ReadOnlySpan<byte>.Empty); } return new utf8z(s.to_utf8_with_z()); } private unsafe static long my_strlen(byte* p) { byte* ptr; for (ptr = p; *ptr != 0; ptr++) { } return ptr - p; } private unsafe static ReadOnlySpan<byte> find_zero_terminator(byte* p) { int num = (int)my_strlen(p); return new ReadOnlySpan<byte>(p, num + 1); } public unsafe static utf8z FromPtr(byte* p) { if (p == null) { return new utf8z(ReadOnlySpan<byte>.Empty); } return new utf8z(find_zero_terminator(p)); } public unsafe static utf8z FromPtrLen(byte* p, int len) { if (p == null) { return new utf8z(ReadOnlySpan<byte>.Empty); } return FromSpan(new ReadOnlySpan<byte>(p, len + 1)); } public unsafe static utf8z FromIntPtr(IntPtr p) { if (p == IntPtr.Zero) { return new utf8z(ReadOnlySpan<byte>.Empty); } return new utf8z(find_zero_terminator((byte*)p.ToPointer())); } public unsafe string utf8_to_string() { if (sp.Length == 0) { return null; } fixed (byte* bytes = sp) { return Encoding.UTF8.GetString(bytes, sp.Length - 1); } } public static byte[] GetZeroTerminatedUTF8Bytes(string value) { return value.to_utf8_with_z(); } } public sealed class PreserveAttribute : Attribute { public bool AllMembers; public bool Conditional; } public sealed class MonoPInvokeCallbackAttribute : Attribute { public MonoPInvokeCallbackAttribute(Type t) { } } public class SafeGCHandle : SafeHandle { public override bool IsInvalid => handle == IntPtr.Zero; public SafeGCHandle(object v, GCHandleType typ) : base(IntPtr.Zero, ownsHandle: true) { if (v != null) { GCHandle value = GCHandle.Alloc(v, typ); SetHandle(GCHandle.ToIntPtr(value)); } } protected override bool ReleaseHandle() { GCHandle.FromIntPtr(handle).Free(); return true; } } public class hook_handle : SafeGCHandle { public hook_handle(object target) : base(target, GCHandleType.Normal) { } public IDisposable ForDispose() { if (IsInvalid) { return null; } return this; } } internal class CompareBuf : EqualityComparer<byte[]> { private Func<IntPtr, IntPtr, int, bool> _f; public CompareBuf(Func<IntPtr, IntPtr, int, bool> f) { _f = f; } public override bool Equals(byte[] p1, byte[] p2) { if (p1.Length != p2.Length) { return false; } GCHandle gCHandle = GCHandle.Alloc(p1, GCHandleType.Pinned); GCHandle gCHandle2 = GCHandle.Alloc(p2, GCHandleType.Pinned); bool result = _f(gCHandle.AddrOfPinnedObject(), gCHandle2.AddrOfPinnedObject(), p1.Length); gCHandle.Free(); gCHandle2.Free(); return result; } public override int GetHashCode(byte[] p) { return p.Length; } } internal class FuncName { public byte[] name { get; private set; } public int n { get; private set; } public FuncName(byte[] _name, int _n) { name = _name; n = _n; } } internal class CompareFuncName : EqualityComparer<FuncName> { private IEqualityComparer<byte[]> _ptrlencmp; public CompareFuncName(IEqualityComparer<byte[]> ptrlencmp) { _ptrlencmp = ptrlencmp; } public override bool Equals(FuncName p1, FuncName p2) { if (p1.n != p2.n) { return false; } return _ptrlencmp.Equals(p1.name, p2.name); } public override int GetHashCode(FuncName p) { return p.n + p.name.Length; } } public class hook_handles : IDisposable { private readonly ConcurrentDictionary<byte[], IDisposable> collation; private readonly ConcurrentDictionary<FuncName, IDisposable> scalar; private readonly ConcurrentDictionary<FuncName, IDisposable> agg; public IDisposable update; public IDisposable rollback; public IDisposable commit; public IDisposable trace; public IDisposable profile; public IDisposable progress; public IDisposable authorizer; public hook_handles(Func<IntPtr, IntPtr, int, bool> f) { CompareBuf compareBuf = new CompareBuf(f); collation = new ConcurrentDictionary<byte[], IDisposable>(compareBuf); scalar = new ConcurrentDictionary<FuncName, IDisposable>(new CompareFuncName(compareBuf)); agg = new ConcurrentDictionary<FuncName, IDisposable>(new CompareFuncName(compareBuf)); } public bool RemoveScalarFunction(byte[] name, int nargs) { FuncName key = new FuncName(name, nargs); if (scalar.TryRemove(key, out var value)) { value.Dispose(); return true; } return false; } public void AddScalarFunction(byte[] name, int nargs, IDisposable d) { FuncName key = new FuncName(name, nargs); scalar[key] = d; } public bool RemoveAggFunction(byte[] name, int nargs) { FuncName key = new FuncName(name, nargs); if (agg.TryRemove(key, out var value)) { value.Dispose(); return true; } return false; } public void AddAggFunction(byte[] name, int nargs, IDisposable d) { FuncName key = new FuncName(name, nargs); agg[key] = d; } public bool RemoveCollation(byte[] name) { if (collation.TryRemove(name, out var value)) { value.Dispose(); return true; } return false; } public void AddCollation(byte[] name, IDisposable d) { collation[name] = d; } public void Dispose() { foreach (IDisposable value in collation.Values) { value.Dispose(); } foreach (IDisposable value2 in scalar.Values) { value2.Dispose(); } foreach (IDisposable value3 in agg.Values) { value3.Dispose(); } if (update != null) { update.Dispose(); } if (rollback != null) { rollback.Dispose(); } if (commit != null) { commit.Dispose(); } if (trace != null) { trace.Dispose(); } if (profile != null) { profile.Dispose(); } if (progress != null) { progress.Dispose(); } if (authorizer != null) { authorizer.Dispose(); } } } public class log_hook_info { private delegate_log _func; private object _user_data; public log_hook_info(delegate_log func, object v) { _func = func; _user_data = v; } public static log_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as log_hook_info; } public void call(int rc, utf8z msg) { _func(_user_data, rc, msg); } } public class commit_hook_info { public delegate_commit _func { get; private set; } public object _user_data { get; private set; } public commit_hook_info(delegate_commit func, object v) { _func = func; _user_data = v; } public int call() { return _func(_user_data); } public static commit_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as commit_hook_info; } } public class rollback_hook_info { private delegate_rollback _func; private object _user_data; public rollback_hook_info(delegate_rollback func, object v) { _func = func; _user_data = v; } public static rollback_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as rollback_hook_info; } public void call() { _func(_user_data); } } public class trace_hook_info { private delegate_trace _func; private object _user_data; public trace_hook_info(delegate_trace func, object v) { _func = func; _user_data = v; } public static trace_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as trace_hook_info; } public void call(utf8z s) { _func(_user_data, s); } } public class profile_hook_info { private delegate_profile _func; private object _user_data; public profile_hook_info(delegate_profile func, object v) { _func = func; _user_data = v; } public static profile_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as profile_hook_info; } public void call(utf8z s, long elapsed) { _func(_user_data, s, elapsed); } } public class progress_hook_info { private delegate_progress _func; private object _user_data; public progress_hook_info(delegate_progress func, object v) { _func = func; _user_data = v; } public static progress_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as progress_hook_info; } public int call() { return _func(_user_data); } } public class update_hook_info { private delegate_update _func; private object _user_data; public update_hook_info(delegate_update func, object v) { _func = func; _user_data = v; } public static update_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as update_hook_info; } public void call(int typ, utf8z db, utf8z tbl, long rowid) { _func(_user_data, typ, db, tbl, rowid); } } public class collation_hook_info { private delegate_collation _func; private object _user_data; public collation_hook_info(delegate_collation func, object v) { _func = func; _user_data = v; } public static collation_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as collation_hook_info; } public int call(ReadOnlySpan<byte> s1, ReadOnlySpan<byte> s2) { return _func(_user_data, s1, s2); } } public class exec_hook_info { private delegate_exec _func; private object _user_data; public exec_hook_info(delegate_exec func, object v) { _func = func; _user_data = v; } public static exec_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as exec_hook_info; } public int call(int n, IntPtr values_ptr, IntPtr names_ptr) { IntPtr[] array = new IntPtr[n]; IntPtr[] array2 = new IntPtr[n]; int num = Marshal.SizeOf(typeof(IntPtr)); for (int i = 0; i < n; i++) { IntPtr intPtr = Marshal.ReadIntPtr(values_ptr, i * num); array[i] = intPtr; intPtr = Marshal.ReadIntPtr(names_ptr, i * num); array2[i] = intPtr; } return _func(_user_data, array, array2); } } public class function_hook_info { private class agg_sqlite3_context : sqlite3_context { public agg_sqlite3_context(object v) : base(v) { } public void fix_ptr(IntPtr p) { set_context_ptr(p); } } private class scalar_sqlite3_context : sqlite3_context { public scalar_sqlite3_context(IntPtr p, object v) : base(v) { set_context_ptr(p); } } private delegate_function_scalar _func_scalar; private delegate_function_aggregate_step _func_step; private delegate_function_aggregate_final _func_final; private object _user_data; public function_hook_info(delegate_function_scalar func_scalar, object user_data) { _func_scalar = func_scalar; _user_data = user_data; } public function_hook_info(delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final, object user_data) { _func_step = func_step; _func_final = func_final; _user_data = user_data; } public static function_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as function_hook_info; } private sqlite3_context get_context(IntPtr context, IntPtr agg_context) { IntPtr intPtr = Marshal.ReadIntPtr(agg_context); agg_sqlite3_context agg_sqlite3_context; if (intPtr == IntPtr.Zero) { agg_sqlite3_context = new agg_sqlite3_context(_user_data); GCHandle gCHandle = GCHandle.Alloc(agg_sqlite3_context); Marshal.WriteIntPtr(agg_context, (IntPtr)gCHandle); } else { agg_sqlite3_context = ((GCHandle)intPtr).Target as agg_sqlite3_context; } agg_sqlite3_context.fix_ptr(context); return agg_sqlite3_context; } public void call_scalar(IntPtr context, int num_args, IntPtr argsptr) { scalar_sqlite3_context ctx = new scalar_sqlite3_context(context, _user_data); sqlite3_value[] array = new sqlite3_value[num_args]; int num = Marshal.SizeOf(typeof(IntPtr)); for (int i = 0; i < num_args; i++) { IntPtr p = Marshal.ReadIntPtr(argsptr, i * num); array[i] = new sqlite3_value(p); } _func_scalar(ctx, _user_data, array); } public void call_step(IntPtr context, IntPtr agg_context, int num_args, IntPtr argsptr) { sqlite3_context ctx = get_context(context, agg_context); sqlite3_value[] array = new sqlite3_value[num_args]; int num = Marshal.SizeOf(typeof(IntPtr)); for (int i = 0; i < num_args; i++) { IntPtr p = Marshal.ReadIntPtr(argsptr, i * num); array[i] = new sqlite3_value(p); } _func_step(ctx, _user_data, array); } public void call_final(IntPtr context, IntPtr agg_context) { sqlite3_context ctx = get_context(context, agg_context); _func_final(ctx, _user_data); ((GCHandle)Marshal.ReadIntPtr(agg_context)).Free(); } } public class authorizer_hook_info { private delegate_authorizer _func; private object _user_data; public authorizer_hook_info(delegate_authorizer func, object v) { _func = func; _user_data = v; } public static authorizer_hook_info from_ptr(IntPtr p) { return ((GCHandle)p).Target as authorizer_hook_info; } public int call(int action_code, utf8z param0, utf8z param1, utf8z dbName, utf8z inner_most_trigger_or_view) { return _func(_user_data, action_code, param0, param1, dbName, inner_most_trigger_or_view); } } public sealed class EntryPointAttribute : Attribute { public string Name { get; private set; } public EntryPointAttribute(string name) { Name = name; } } public interface IGetFunctionPointer { IntPtr GetFunctionPointer(string name); } }
plugins/SQLitePCLRaw.provider.e_sqlite3.dll
Decompiled 3 hours agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; [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("SourceGear")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2014-2024 SourceGear, LLC")] [assembly: AssemblyDescription("SQLitePCLRaw is a Portable Class Library (PCL) for low-level (raw) access to SQLite")] [assembly: AssemblyFileVersion("2.1.13.3146")] [assembly: AssemblyInformationalVersion("2.1.13")] [assembly: AssemblyTitle("SQLitePCLRaw.provider.e_sqlite3")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ericsink/SQLitePCL.raw")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.13.3146")] [module: UnverifiableCode] namespace SQLitePCL; [Preserve(AllMembers = true)] public sealed class SQLite3Provider_e_sqlite3 : ISQLite3Provider { private struct sqlite3_vfs { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate int SQLiteDeleteDelegate(IntPtr pVfs, byte* zName, int syncDir); public int iVersion; public int szOsFile; public int mxPathname; public IntPtr pNext; public IntPtr zName; public IntPtr pAppData; public IntPtr xOpen; public SQLiteDeleteDelegate xDelete; public IntPtr xAccess; public IntPtr xFullPathname; public IntPtr xDlOpen; public IntPtr xDlError; public IntPtr xDlSym; public IntPtr xDlClose; public IntPtr xRandomness; public IntPtr xSleep; public IntPtr xCurrentTime; public IntPtr xGetLastError; } private static class NativeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_log(IntPtr pUserData, int errorCode, IntPtr pMessage); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_scalar_function(IntPtr context, int nArgs, IntPtr argsptr); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_agg_function_step(IntPtr context, int nArgs, IntPtr argsptr); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_agg_function_final(IntPtr context); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_destroy(IntPtr p); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int callback_collation(IntPtr puser, int len1, IntPtr pv1, int len2, IntPtr pv2); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_update(IntPtr p, int typ, IntPtr db, IntPtr tbl, long rowid); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int callback_commit(IntPtr puser); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_profile(IntPtr puser, IntPtr statement, long elapsed); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int callback_progress_handler(IntPtr puser); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int callback_authorizer(IntPtr puser, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_trace(IntPtr puser, IntPtr statement); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void callback_rollback(IntPtr puser); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int callback_exec(IntPtr db, int n, IntPtr values, IntPtr names); private const string SQLITE_DLL = "e_sqlite3"; [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_close(IntPtr db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_close_v2(IntPtr db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_enable_shared_cache(int enable); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_interrupt(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_finalize(IntPtr stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_reset(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_clear_bindings(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_stmt_status(sqlite3_stmt stm, int op, int resetFlg); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_bind_parameter_name(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_database_name(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_decltype(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_name(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_origin_name(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_table_name(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_column_text(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_errmsg(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_db_readonly(sqlite3 db, byte* dbName); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_db_filename(sqlite3 db, byte* att); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_prepare_v2(sqlite3 db, byte* pSql, int nBytes, out IntPtr stmt, out byte* ptrRemain); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_prepare_v3(sqlite3 db, byte* pSql, int nBytes, uint flags, out IntPtr stmt, out byte* ptrRemain); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_complete(byte* pSql); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_compileoption_used(byte* pSql); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_compileoption_get(int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_table_column_metadata(sqlite3 db, byte* dbName, byte* tblName, byte* colName, out byte* ptrDataType, out byte* ptrCollSeq, out int notNull, out int primaryKey, out int autoInc); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_value_text(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_enable_load_extension(sqlite3 db, int enable); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_limit(sqlite3 db, int id, int newVal); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_initialize(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_shutdown(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_libversion(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_libversion_number(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_threadsafe(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_sourceid(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_malloc(int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_malloc64(long n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_realloc(IntPtr p, int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_free(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_stricmp(IntPtr p, IntPtr q); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_strnicmp(IntPtr p, IntPtr q, int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_open(byte* filename, out IntPtr db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_open_v2(byte* filename, out IntPtr db, int flags, byte* vfs); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern IntPtr sqlite3_vfs_find(byte* vfs); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_last_insert_rowid(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_changes(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_total_changes(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_memory_used(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_memory_highwater(int resetFlag); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_soft_heap_limit64(long n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_hard_heap_limit64(long n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_status(int op, out int current, out int highwater, int resetFlag); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_busy_timeout(sqlite3 db, int ms); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_bind_blob(sqlite3_stmt stmt, int index, byte* val, int nSize, IntPtr nTransient); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_zeroblob(sqlite3_stmt stmt, int index, int size); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_double(sqlite3_stmt stmt, int index, double val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_int(sqlite3_stmt stmt, int index, int val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_int64(sqlite3_stmt stmt, int index, long val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_null(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_bind_text(sqlite3_stmt stmt, int index, byte* val, int nlen, IntPtr pvReserved); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_bind_text16(sqlite3_stmt stmt, int index, char* val, int nlen, IntPtr pvReserved); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_bind_parameter_count(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_bind_parameter_index(sqlite3_stmt stmt, byte* strName); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_column_count(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_data_count(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_step(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_sql(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern double sqlite3_column_double(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_column_int(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_column_int64(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_column_blob(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_column_bytes(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_column_type(sqlite3_stmt stmt, int index); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_aggregate_count(IntPtr context); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_value_blob(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_value_bytes(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern double sqlite3_value_double(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_value_int(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern long sqlite3_value_int64(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_value_type(IntPtr p); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_user_data(IntPtr context); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_blob(IntPtr context, IntPtr val, int nSize, IntPtr pvReserved); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_double(IntPtr context, double val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern void sqlite3_result_error(IntPtr context, byte* strErr, int nLen); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_int(IntPtr context, int val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_int64(IntPtr context, long val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_null(IntPtr context); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern void sqlite3_result_text(IntPtr context, byte* val, int nLen, IntPtr pvReserved); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_zeroblob(IntPtr context, int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_error_toobig(IntPtr context); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_error_nomem(IntPtr context); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_result_error_code(IntPtr context, int code); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_aggregate_context(IntPtr context, int nBytes); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_config", ExactSpelling = true)] public static extern int sqlite3_config_none(int op); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_config", ExactSpelling = true)] public static extern int sqlite3_config_int(int op, int val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_config", ExactSpelling = true)] public static extern int sqlite3_config_int_arm64cc(int op, IntPtr dummy1, IntPtr dummy2, IntPtr dummy3, IntPtr dummy4, IntPtr dummy5, IntPtr dummy6, IntPtr dummy7, int val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_config", ExactSpelling = true)] public static extern int sqlite3_config_log(int op, callback_log func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_config", ExactSpelling = true)] public static extern int sqlite3_config_log_arm64cc(int op, IntPtr dummy1, IntPtr dummy2, IntPtr dummy3, IntPtr dummy4, IntPtr dummy5, IntPtr dummy6, IntPtr dummy7, callback_log func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public unsafe static extern int sqlite3_db_config_charptr(sqlite3 db, int op, byte* val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public unsafe static extern int sqlite3_db_config_charptr_arm64cc(sqlite3 db, int op, IntPtr dummy2, IntPtr dummy3, IntPtr dummy4, IntPtr dummy5, IntPtr dummy6, IntPtr dummy7, byte* val); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public unsafe static extern int sqlite3_db_config_int_outint(sqlite3 db, int op, int val, int* result); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public unsafe static extern int sqlite3_db_config_int_outint_arm64cc(sqlite3 db, int op, IntPtr dummy2, IntPtr dummy3, IntPtr dummy4, IntPtr dummy5, IntPtr dummy6, IntPtr dummy7, int val, int* result); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public static extern int sqlite3_db_config_intptr_int_int(sqlite3 db, int op, IntPtr ptr, int int0, int int1); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, EntryPoint = "sqlite3_db_config", ExactSpelling = true)] public static extern int sqlite3_db_config_intptr_int_int_arm64cc(sqlite3 db, int op, IntPtr dummy2, IntPtr dummy3, IntPtr dummy4, IntPtr dummy5, IntPtr dummy6, IntPtr dummy7, IntPtr ptr, int int0, int int1); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_create_collation(sqlite3 db, byte[] strName, int nType, hook_handle pvUser, callback_collation func); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_update_hook(sqlite3 db, callback_update func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_commit_hook(sqlite3 db, callback_commit func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_profile(sqlite3 db, callback_profile func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_progress_handler(sqlite3 db, int instructions, callback_progress_handler func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_trace(sqlite3 db, callback_trace func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_rollback_hook(sqlite3 db, callback_rollback func, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_db_handle(IntPtr stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern IntPtr sqlite3_next_stmt(sqlite3 db, IntPtr stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_stmt_isexplain(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_stmt_busy(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_stmt_readonly(sqlite3_stmt stmt); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_exec(sqlite3 db, byte* strSql, callback_exec cb, hook_handle pvParam, out IntPtr errMsg); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_get_autocommit(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_extended_result_codes(sqlite3 db, int onoff); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_errcode(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_extended_errcode(sqlite3 db); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern byte* sqlite3_errstr(int rc); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern void sqlite3_log(int iErrCode, byte* zFormat); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_file_control(sqlite3 db, byte[] zDbName, int op, IntPtr pArg); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern sqlite3_backup sqlite3_backup_init(sqlite3 destDb, byte* zDestName, sqlite3 sourceDb, byte* zSourceName); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_backup_step(sqlite3_backup backup, int nPage); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_backup_remaining(sqlite3_backup backup); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_backup_pagecount(sqlite3_backup backup); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_backup_finish(IntPtr backup); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_snapshot_get(sqlite3 db, byte* schema, out IntPtr snap); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_snapshot_open(sqlite3 db, byte* schema, sqlite3_snapshot snap); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_snapshot_recover(sqlite3 db, byte* name); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern void sqlite3_snapshot_free(IntPtr snap); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_blob_open(sqlite3 db, byte* sdb, byte* table, byte* col, long rowid, int flags, out sqlite3_blob blob); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_blob_write(sqlite3_blob blob, byte* b, int n, int offset); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_blob_read(sqlite3_blob blob, byte* b, int n, int offset); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_blob_bytes(sqlite3_blob blob); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_blob_reopen(sqlite3_blob blob, long rowid); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_blob_close(IntPtr blob); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_wal_autocheckpoint(sqlite3 db, int n); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_wal_checkpoint(sqlite3 db, byte* dbName); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_wal_checkpoint_v2(sqlite3 db, byte* dbName, int eMode, out int logSize, out int framesCheckPointed); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_set_authorizer(sqlite3 db, callback_authorizer cb, hook_handle pvUser); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_win32_set_directory8(uint directoryType, byte* directoryPath); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_create_function_v2(sqlite3 db, byte[] strName, int nArgs, int nType, hook_handle pvUser, callback_scalar_function func, callback_agg_function_step fstep, callback_agg_function_final ffinal, callback_destroy fdestroy); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public static extern int sqlite3_keyword_count(); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_keyword_name(int i, out byte* name, out int length); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern IntPtr sqlite3_serialize(sqlite3 db, byte* schema, out long size, int flags); [DllImport("e_sqlite3", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] public unsafe static extern int sqlite3_deserialize(sqlite3 db, byte* schema, IntPtr data, long szDb, long szBuf, int flags); } private const CallingConvention CALLING_CONVENTION = CallingConvention.Cdecl; private static readonly bool IsArm64cc = RuntimeInformation.ProcessArchitecture == Architecture.Arm64 && (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Create("IOS"))); private readonly NativeMethods.callback_commit commit_hook_bridge = commit_hook_bridge_impl; private readonly NativeMethods.callback_scalar_function scalar_function_hook_bridge = scalar_function_hook_bridge_impl; private static hook_handle disp_log_hook_handle; private readonly NativeMethods.callback_log log_hook_bridge = log_hook_bridge_impl; private readonly NativeMethods.callback_agg_function_step agg_function_step_hook_bridge = agg_function_step_hook_bridge_impl; private readonly NativeMethods.callback_agg_function_final agg_function_final_hook_bridge = agg_function_final_hook_bridge_impl; private readonly NativeMethods.callback_collation collation_hook_bridge = collation_hook_bridge_impl; private readonly NativeMethods.callback_update update_hook_bridge = update_hook_bridge_impl; private readonly NativeMethods.callback_rollback rollback_hook_bridge = rollback_hook_bridge_impl; private readonly NativeMethods.callback_trace trace_hook_bridge = trace_hook_bridge_impl; private readonly NativeMethods.callback_profile profile_hook_bridge = profile_hook_bridge_impl; private readonly NativeMethods.callback_progress_handler progress_handler_hook_bridge = progress_handler_hook_bridge_impl; private readonly NativeMethods.callback_authorizer authorizer_hook_bridge = authorizer_hook_bridge_impl; string ISQLite3Provider.GetNativeLibraryName() { return "e_sqlite3"; } private bool my_streq(IntPtr p, IntPtr q, int len) { return NativeMethods.sqlite3_strnicmp(p, q, len) == 0; } private hook_handles get_hooks(sqlite3 db) { return db.GetOrCreateExtra<hook_handles>((Func<hook_handles>)(() => new hook_handles((Func<IntPtr, IntPtr, int, bool>)my_streq))); } unsafe int ISQLite3Provider.sqlite3_win32_set_directory(int typ, utf8z path) { fixed (byte* directoryPath = ((utf8z)(ref path)).GetPinnableReference()) { return NativeMethods.sqlite3_win32_set_directory8((uint)typ, directoryPath); } } unsafe int ISQLite3Provider.sqlite3_open(utf8z filename, out IntPtr db) { fixed (byte* filename2 = ((utf8z)(ref filename)).GetPinnableReference()) { return NativeMethods.sqlite3_open(filename2, out db); } } unsafe int ISQLite3Provider.sqlite3_open_v2(utf8z filename, out IntPtr db, int flags, utf8z vfs) { fixed (byte* filename2 = ((utf8z)(ref filename)).GetPinnableReference()) { fixed (byte* vfs2 = ((utf8z)(ref vfs)).GetPinnableReference()) { return NativeMethods.sqlite3_open_v2(filename2, out db, flags, vfs2); } } } unsafe int ISQLite3Provider.sqlite3__vfs__delete(utf8z vfs, utf8z filename, int syncDir) { fixed (byte* vfs2 = ((utf8z)(ref vfs)).GetPinnableReference()) { fixed (byte* zName = ((utf8z)(ref filename)).GetPinnableReference()) { IntPtr intPtr = NativeMethods.sqlite3_vfs_find(vfs2); return ((sqlite3_vfs)Marshal.PtrToStructure(intPtr, typeof(sqlite3_vfs))).xDelete(intPtr, zName, 1); } } } int ISQLite3Provider.sqlite3_close_v2(IntPtr db) { return NativeMethods.sqlite3_close_v2(db); } int ISQLite3Provider.sqlite3_close(IntPtr db) { return NativeMethods.sqlite3_close(db); } IntPtr ISQLite3Provider.sqlite3_malloc(int n) { return NativeMethods.sqlite3_malloc(n); } IntPtr ISQLite3Provider.sqlite3_malloc64(long n) { return NativeMethods.sqlite3_malloc64(n); } void ISQLite3Provider.sqlite3_free(IntPtr p) { NativeMethods.sqlite3_free(p); } int ISQLite3Provider.sqlite3_stricmp(IntPtr p, IntPtr q) { return NativeMethods.sqlite3_stricmp(p, q); } int ISQLite3Provider.sqlite3_strnicmp(IntPtr p, IntPtr q, int n) { return NativeMethods.sqlite3_strnicmp(p, q, n); } int ISQLite3Provider.sqlite3_enable_shared_cache(int enable) { return NativeMethods.sqlite3_enable_shared_cache(enable); } void ISQLite3Provider.sqlite3_interrupt(sqlite3 db) { NativeMethods.sqlite3_interrupt(db); } [MonoPInvokeCallback(typeof(NativeMethods.callback_exec))] private static int exec_hook_bridge_impl(IntPtr p, int n, IntPtr values_ptr, IntPtr names_ptr) { return exec_hook_info.from_ptr(p).call(n, values_ptr, names_ptr); } unsafe int ISQLite3Provider.sqlite3_exec(sqlite3 db, utf8z sql, delegate_exec func, object user_data, out IntPtr errMsg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown NativeMethods.callback_exec cb; exec_hook_info val; if (func != null) { cb = exec_hook_bridge_impl; val = new exec_hook_info(func, user_data); } else { cb = null; val = null; } hook_handle val2 = new hook_handle((object)val); int result; fixed (byte* strSql = ((utf8z)(ref sql)).GetPinnableReference()) { result = NativeMethods.sqlite3_exec(db, strSql, cb, val2, out errMsg); } ((SafeHandle)(object)val2).Dispose(); return result; } unsafe int ISQLite3Provider.sqlite3_complete(utf8z sql) { fixed (byte* pSql = ((utf8z)(ref sql)).GetPinnableReference()) { return NativeMethods.sqlite3_complete(pSql); } } unsafe utf8z ISQLite3Provider.sqlite3_compileoption_get(int n) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_compileoption_get(n)); } unsafe int ISQLite3Provider.sqlite3_compileoption_used(utf8z s) { fixed (byte* pSql = ((utf8z)(ref s)).GetPinnableReference()) { return NativeMethods.sqlite3_compileoption_used(pSql); } } unsafe int ISQLite3Provider.sqlite3_table_column_metadata(sqlite3 db, utf8z dbName, utf8z tblName, utf8z colName, out utf8z dataType, out utf8z collSeq, out int notNull, out int primaryKey, out int autoInc) { //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_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) fixed (byte* dbName2 = ((utf8z)(ref dbName)).GetPinnableReference()) { fixed (byte* tblName2 = ((utf8z)(ref tblName)).GetPinnableReference()) { fixed (byte* colName2 = ((utf8z)(ref colName)).GetPinnableReference()) { byte* ptrDataType; byte* ptrCollSeq; int result = NativeMethods.sqlite3_table_column_metadata(db, dbName2, tblName2, colName2, out ptrDataType, out ptrCollSeq, out notNull, out primaryKey, out autoInc); dataType = utf8z.FromPtr(ptrDataType); collSeq = utf8z.FromPtr(ptrCollSeq); return result; } } } } int ISQLite3Provider.sqlite3_key(sqlite3 db, ReadOnlySpan<byte> k) { return 1; } int ISQLite3Provider.sqlite3_key_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return 1; } int ISQLite3Provider.sqlite3_rekey(sqlite3 db, ReadOnlySpan<byte> k) { return 1; } int ISQLite3Provider.sqlite3_rekey_v2(sqlite3 db, utf8z name, ReadOnlySpan<byte> k) { return 1; } unsafe int ISQLite3Provider.sqlite3_prepare_v2(sqlite3 db, ReadOnlySpan<byte> sql, out IntPtr stm, out ReadOnlySpan<byte> tail) { fixed (byte* ptr = sql) { byte* ptrRemain; int result = NativeMethods.sqlite3_prepare_v2(db, ptr, sql.Length, out stm, out ptrRemain); int num = (int)(ptrRemain - ptr); int num2 = sql.Length - num; if (num2 > 0) { tail = sql.Slice(num, num2); return result; } tail = ReadOnlySpan<byte>.Empty; return result; } } unsafe int ISQLite3Provider.sqlite3_prepare_v2(sqlite3 db, utf8z sql, out IntPtr stm, out utf8z tail) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) fixed (byte* pSql = ((utf8z)(ref sql)).GetPinnableReference()) { byte* ptrRemain; int result = NativeMethods.sqlite3_prepare_v2(db, pSql, -1, out stm, out ptrRemain); tail = utf8z.FromPtr(ptrRemain); return result; } } unsafe int ISQLite3Provider.sqlite3_prepare_v3(sqlite3 db, ReadOnlySpan<byte> sql, uint flags, out IntPtr stm, out ReadOnlySpan<byte> tail) { fixed (byte* ptr = sql) { byte* ptrRemain; int result = NativeMethods.sqlite3_prepare_v3(db, ptr, sql.Length, flags, out stm, out ptrRemain); int num = (int)(ptrRemain - ptr); int num2 = sql.Length - num; if (num2 > 0) { tail = sql.Slice(num, num2); return result; } tail = ReadOnlySpan<byte>.Empty; return result; } } unsafe int ISQLite3Provider.sqlite3_prepare_v3(sqlite3 db, utf8z sql, uint flags, out IntPtr stm, out utf8z tail) { //IL_001b: 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) fixed (byte* pSql = ((utf8z)(ref sql)).GetPinnableReference()) { byte* ptrRemain; int result = NativeMethods.sqlite3_prepare_v3(db, pSql, -1, flags, out stm, out ptrRemain); tail = utf8z.FromPtr(ptrRemain); return result; } } int ISQLite3Provider.sqlite3_db_status(sqlite3 db, int op, out int current, out int highest, int resetFlg) { return NativeMethods.sqlite3_db_status(db, op, out current, out highest, resetFlg); } unsafe utf8z ISQLite3Provider.sqlite3_sql(sqlite3_stmt stmt) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_sql(stmt)); } IntPtr ISQLite3Provider.sqlite3_db_handle(IntPtr stmt) { return NativeMethods.sqlite3_db_handle(stmt); } unsafe int ISQLite3Provider.sqlite3_blob_open(sqlite3 db, utf8z db_utf8, utf8z table_utf8, utf8z col_utf8, long rowid, int flags, out sqlite3_blob blob) { fixed (byte* sdb = ((utf8z)(ref db_utf8)).GetPinnableReference()) { fixed (byte* table = ((utf8z)(ref table_utf8)).GetPinnableReference()) { fixed (byte* col = ((utf8z)(ref col_utf8)).GetPinnableReference()) { return NativeMethods.sqlite3_blob_open(db, sdb, table, col, rowid, flags, out blob); } } } } int ISQLite3Provider.sqlite3_blob_bytes(sqlite3_blob blob) { return NativeMethods.sqlite3_blob_bytes(blob); } int ISQLite3Provider.sqlite3_blob_reopen(sqlite3_blob blob, long rowid) { return NativeMethods.sqlite3_blob_reopen(blob, rowid); } unsafe int ISQLite3Provider.sqlite3_blob_read(sqlite3_blob blob, Span<byte> b, int offset) { fixed (byte* b2 = b) { return NativeMethods.sqlite3_blob_read(blob, b2, b.Length, offset); } } unsafe int ISQLite3Provider.sqlite3_blob_write(sqlite3_blob blob, ReadOnlySpan<byte> b, int offset) { fixed (byte* b2 = b) { return NativeMethods.sqlite3_blob_write(blob, b2, b.Length, offset); } } int ISQLite3Provider.sqlite3_blob_close(IntPtr blob) { return NativeMethods.sqlite3_blob_close(blob); } unsafe int ISQLite3Provider.sqlite3_snapshot_get(sqlite3 db, utf8z schema, out IntPtr snap) { fixed (byte* schema2 = ((utf8z)(ref schema)).GetPinnableReference()) { return NativeMethods.sqlite3_snapshot_get(db, schema2, out snap); } } int ISQLite3Provider.sqlite3_snapshot_cmp(sqlite3_snapshot p1, sqlite3_snapshot p2) { return NativeMethods.sqlite3_snapshot_cmp(p1, p2); } unsafe int ISQLite3Provider.sqlite3_snapshot_open(sqlite3 db, utf8z schema, sqlite3_snapshot snap) { fixed (byte* schema2 = ((utf8z)(ref schema)).GetPinnableReference()) { return NativeMethods.sqlite3_snapshot_open(db, schema2, snap); } } unsafe int ISQLite3Provider.sqlite3_snapshot_recover(sqlite3 db, utf8z name) { fixed (byte* name2 = ((utf8z)(ref name)).GetPinnableReference()) { return NativeMethods.sqlite3_snapshot_recover(db, name2); } } void ISQLite3Provider.sqlite3_snapshot_free(IntPtr snap) { NativeMethods.sqlite3_snapshot_free(snap); } unsafe sqlite3_backup ISQLite3Provider.sqlite3_backup_init(sqlite3 destDb, utf8z destName, sqlite3 sourceDb, utf8z sourceName) { fixed (byte* zDestName = ((utf8z)(ref destName)).GetPinnableReference()) { fixed (byte* zSourceName = ((utf8z)(ref sourceName)).GetPinnableReference()) { return NativeMethods.sqlite3_backup_init(destDb, zDestName, sourceDb, zSourceName); } } } int ISQLite3Provider.sqlite3_backup_step(sqlite3_backup backup, int nPage) { return NativeMethods.sqlite3_backup_step(backup, nPage); } int ISQLite3Provider.sqlite3_backup_remaining(sqlite3_backup backup) { return NativeMethods.sqlite3_backup_remaining(backup); } int ISQLite3Provider.sqlite3_backup_pagecount(sqlite3_backup backup) { return NativeMethods.sqlite3_backup_pagecount(backup); } int ISQLite3Provider.sqlite3_backup_finish(IntPtr backup) { return NativeMethods.sqlite3_backup_finish(backup); } IntPtr ISQLite3Provider.sqlite3_next_stmt(sqlite3 db, IntPtr stmt) { return NativeMethods.sqlite3_next_stmt(db, stmt); } long ISQLite3Provider.sqlite3_last_insert_rowid(sqlite3 db) { return NativeMethods.sqlite3_last_insert_rowid(db); } int ISQLite3Provider.sqlite3_changes(sqlite3 db) { return NativeMethods.sqlite3_changes(db); } int ISQLite3Provider.sqlite3_total_changes(sqlite3 db) { return NativeMethods.sqlite3_total_changes(db); } int ISQLite3Provider.sqlite3_extended_result_codes(sqlite3 db, int onoff) { return NativeMethods.sqlite3_extended_result_codes(db, onoff); } unsafe utf8z ISQLite3Provider.sqlite3_errstr(int rc) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_errstr(rc)); } int ISQLite3Provider.sqlite3_errcode(sqlite3 db) { return NativeMethods.sqlite3_errcode(db); } int ISQLite3Provider.sqlite3_extended_errcode(sqlite3 db) { return NativeMethods.sqlite3_extended_errcode(db); } int ISQLite3Provider.sqlite3_busy_timeout(sqlite3 db, int ms) { return NativeMethods.sqlite3_busy_timeout(db, ms); } int ISQLite3Provider.sqlite3_get_autocommit(sqlite3 db) { return NativeMethods.sqlite3_get_autocommit(db); } unsafe int ISQLite3Provider.sqlite3_db_readonly(sqlite3 db, utf8z dbName) { fixed (byte* dbName2 = ((utf8z)(ref dbName)).GetPinnableReference()) { return NativeMethods.sqlite3_db_readonly(db, dbName2); } } unsafe utf8z ISQLite3Provider.sqlite3_db_filename(sqlite3 db, utf8z att) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) fixed (byte* att2 = ((utf8z)(ref att)).GetPinnableReference()) { return utf8z.FromPtr(NativeMethods.sqlite3_db_filename(db, att2)); } } unsafe utf8z ISQLite3Provider.sqlite3_errmsg(sqlite3 db) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_errmsg(db)); } unsafe utf8z ISQLite3Provider.sqlite3_libversion() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_libversion()); } int ISQLite3Provider.sqlite3_libversion_number() { return NativeMethods.sqlite3_libversion_number(); } int ISQLite3Provider.sqlite3_threadsafe() { return NativeMethods.sqlite3_threadsafe(); } int ISQLite3Provider.sqlite3_config(int op) { return NativeMethods.sqlite3_config_none(op); } int ISQLite3Provider.sqlite3_config(int op, int val) { if (IsArm64cc) { return NativeMethods.sqlite3_config_int_arm64cc(op, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, val); } return NativeMethods.sqlite3_config_int(op, val); } unsafe int ISQLite3Provider.sqlite3_db_config(sqlite3 db, int op, utf8z val) { fixed (byte* val2 = ((utf8z)(ref val)).GetPinnableReference()) { if (IsArm64cc) { return NativeMethods.sqlite3_db_config_charptr_arm64cc(db, op, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, val2); } return NativeMethods.sqlite3_db_config_charptr(db, op, val2); } } unsafe int ISQLite3Provider.sqlite3_db_config(sqlite3 db, int op, int val, out int result) { int num = 0; int result2 = ((!IsArm64cc) ? NativeMethods.sqlite3_db_config_int_outint(db, op, val, &num) : NativeMethods.sqlite3_db_config_int_outint_arm64cc(db, op, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, val, &num)); result = num; return result2; } int ISQLite3Provider.sqlite3_db_config(sqlite3 db, int op, IntPtr ptr, int int0, int int1) { if (IsArm64cc) { return NativeMethods.sqlite3_db_config_intptr_int_int_arm64cc(db, op, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ptr, int0, int1); } return NativeMethods.sqlite3_db_config_intptr_int_int(db, op, ptr, int0, int1); } int ISQLite3Provider.sqlite3_limit(sqlite3 db, int id, int newVal) { return NativeMethods.sqlite3_limit(db, id, newVal); } int ISQLite3Provider.sqlite3_initialize() { return NativeMethods.sqlite3_initialize(); } int ISQLite3Provider.sqlite3_shutdown() { return NativeMethods.sqlite3_shutdown(); } int ISQLite3Provider.sqlite3_enable_load_extension(sqlite3 db, int onoff) { return NativeMethods.sqlite3_enable_load_extension(db, onoff); } unsafe int ISQLite3Provider.sqlite3_load_extension(sqlite3 db, utf8z zFile, utf8z zProc, out utf8z pzErrMsg) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) pzErrMsg = utf8z.FromPtr((byte*)null); return 1; } [MonoPInvokeCallback(typeof(NativeMethods.callback_commit))] private static int commit_hook_bridge_impl(IntPtr p) { return commit_hook_info.from_ptr(p).call(); } void ISQLite3Provider.sqlite3_commit_hook(sqlite3 db, delegate_commit func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.commit != null) { val.commit.Dispose(); val.commit = null; } NativeMethods.callback_commit func2; commit_hook_info val2; if (func != null) { func2 = commit_hook_bridge; val2 = new commit_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); NativeMethods.sqlite3_commit_hook(db, func2, val3); val.commit = val3.ForDispose(); } [MonoPInvokeCallback(typeof(NativeMethods.callback_scalar_function))] private static void scalar_function_hook_bridge_impl(IntPtr context, int num_args, IntPtr argsptr) { function_hook_info.from_ptr(NativeMethods.sqlite3_user_data(context)).call_scalar(context, num_args, argsptr); } int ISQLite3Provider.sqlite3_create_function(sqlite3 db, byte[] name, int nargs, int flags, object v, delegate_function_scalar func) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Expected O, but got Unknown hook_handles val = get_hooks(db); val.RemoveScalarFunction(name, nargs); int nType = 1 | flags; NativeMethods.callback_scalar_function callback_scalar_function; function_hook_info val2; if (func != null) { callback_scalar_function = scalar_function_hook_bridge; val2 = new function_hook_info(func, v); } else { callback_scalar_function = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); int num = NativeMethods.sqlite3_create_function_v2(db, name, nargs, nType, val3, callback_scalar_function, null, null, null); if (num == 0 && callback_scalar_function != null) { val.AddScalarFunction(name, nargs, val3.ForDispose()); } return num; } [MonoPInvokeCallback(typeof(NativeMethods.callback_log))] private static void log_hook_bridge_impl(IntPtr p, int rc, IntPtr s) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) log_hook_info.from_ptr(p).call(rc, utf8z.FromIntPtr(s)); } int ISQLite3Provider.sqlite3_config_log(delegate_log func, object v) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if (disp_log_hook_handle != null) { ((SafeHandle)(object)disp_log_hook_handle).Dispose(); disp_log_hook_handle = null; } NativeMethods.callback_log func2; log_hook_info val; if (func != null) { func2 = log_hook_bridge; val = new log_hook_info(func, v); } else { func2 = null; val = null; } hook_handle pvUser = (disp_log_hook_handle = new hook_handle((object)val)); if (IsArm64cc) { return NativeMethods.sqlite3_config_log_arm64cc(16, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, func2, pvUser); } return NativeMethods.sqlite3_config_log(16, func2, pvUser); } unsafe void ISQLite3Provider.sqlite3_log(int errcode, utf8z s) { fixed (byte* zFormat = ((utf8z)(ref s)).GetPinnableReference()) { NativeMethods.sqlite3_log(errcode, zFormat); } } [MonoPInvokeCallback(typeof(NativeMethods.callback_agg_function_step))] private static void agg_function_step_hook_bridge_impl(IntPtr context, int num_args, IntPtr argsptr) { IntPtr intPtr = NativeMethods.sqlite3_aggregate_context(context, 8); function_hook_info.from_ptr(NativeMethods.sqlite3_user_data(context)).call_step(context, intPtr, num_args, argsptr); } [MonoPInvokeCallback(typeof(NativeMethods.callback_agg_function_final))] private static void agg_function_final_hook_bridge_impl(IntPtr context) { IntPtr intPtr = NativeMethods.sqlite3_aggregate_context(context, 8); function_hook_info.from_ptr(NativeMethods.sqlite3_user_data(context)).call_final(context, intPtr); } int ISQLite3Provider.sqlite3_create_function(sqlite3 db, byte[] name, int nargs, int flags, object v, delegate_function_aggregate_step func_step, delegate_function_aggregate_final func_final) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown hook_handles val = get_hooks(db); val.RemoveAggFunction(name, nargs); int nType = 1 | flags; NativeMethods.callback_agg_function_step callback_agg_function_step; NativeMethods.callback_agg_function_final ffinal; function_hook_info val2; if (func_step != null) { callback_agg_function_step = agg_function_step_hook_bridge; ffinal = agg_function_final_hook_bridge; val2 = new function_hook_info(func_step, func_final, v); } else { callback_agg_function_step = null; ffinal = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); int num = NativeMethods.sqlite3_create_function_v2(db, name, nargs, nType, val3, null, callback_agg_function_step, ffinal, null); if (num == 0 && callback_agg_function_step != null) { val.AddAggFunction(name, nargs, val3.ForDispose()); } return num; } [MonoPInvokeCallback(typeof(NativeMethods.callback_collation))] private unsafe static int collation_hook_bridge_impl(IntPtr p, int len1, IntPtr pv1, int len2, IntPtr pv2) { collation_hook_info obj = collation_hook_info.from_ptr(p); ReadOnlySpan<byte> readOnlySpan = new ReadOnlySpan<byte>(pv1.ToPointer(), len1); ReadOnlySpan<byte> readOnlySpan2 = new ReadOnlySpan<byte>(pv2.ToPointer(), len2); return obj.call(readOnlySpan, readOnlySpan2); } int ISQLite3Provider.sqlite3_create_collation(sqlite3 db, byte[] name, object v, delegate_collation func) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown hook_handles val = get_hooks(db); val.RemoveCollation(name); NativeMethods.callback_collation callback_collation; collation_hook_info val2; if (func != null) { callback_collation = collation_hook_bridge; val2 = new collation_hook_info(func, v); } else { callback_collation = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); int num = NativeMethods.sqlite3_create_collation(db, name, 1, val3, callback_collation); if (num == 0 && callback_collation != null) { val.AddCollation(name, val3.ForDispose()); } return num; } [MonoPInvokeCallback(typeof(NativeMethods.callback_update))] private static void update_hook_bridge_impl(IntPtr p, int typ, IntPtr db, IntPtr tbl, long rowid) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) update_hook_info.from_ptr(p).call(typ, utf8z.FromIntPtr(db), utf8z.FromIntPtr(tbl), rowid); } void ISQLite3Provider.sqlite3_update_hook(sqlite3 db, delegate_update func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.update != null) { val.update.Dispose(); val.update = null; } NativeMethods.callback_update func2; update_hook_info val2; if (func != null) { func2 = update_hook_bridge; val2 = new update_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.update = val3.ForDispose(); NativeMethods.sqlite3_update_hook(db, func2, val3); } [MonoPInvokeCallback(typeof(NativeMethods.callback_rollback))] private static void rollback_hook_bridge_impl(IntPtr p) { rollback_hook_info.from_ptr(p).call(); } void ISQLite3Provider.sqlite3_rollback_hook(sqlite3 db, delegate_rollback func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.rollback != null) { val.rollback.Dispose(); val.rollback = null; } NativeMethods.callback_rollback func2; rollback_hook_info val2; if (func != null) { func2 = rollback_hook_bridge; val2 = new rollback_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.rollback = val3.ForDispose(); NativeMethods.sqlite3_rollback_hook(db, func2, val3); } [MonoPInvokeCallback(typeof(NativeMethods.callback_trace))] private static void trace_hook_bridge_impl(IntPtr p, IntPtr s) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) trace_hook_info.from_ptr(p).call(utf8z.FromIntPtr(s)); } void ISQLite3Provider.sqlite3_trace(sqlite3 db, delegate_trace func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.trace != null) { val.trace.Dispose(); val.trace = null; } NativeMethods.callback_trace func2; trace_hook_info val2; if (func != null) { func2 = trace_hook_bridge; val2 = new trace_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.trace = val3.ForDispose(); NativeMethods.sqlite3_trace(db, func2, val3); } [MonoPInvokeCallback(typeof(NativeMethods.callback_profile))] private static void profile_hook_bridge_impl(IntPtr p, IntPtr s, long elapsed) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) profile_hook_info.from_ptr(p).call(utf8z.FromIntPtr(s), elapsed); } void ISQLite3Provider.sqlite3_profile(sqlite3 db, delegate_profile func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.profile != null) { val.profile.Dispose(); val.profile = null; } NativeMethods.callback_profile func2; profile_hook_info val2; if (func != null) { func2 = profile_hook_bridge; val2 = new profile_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.profile = val3.ForDispose(); NativeMethods.sqlite3_profile(db, func2, val3); } [MonoPInvokeCallback(typeof(NativeMethods.callback_progress_handler))] private static int progress_handler_hook_bridge_impl(IntPtr p) { return progress_hook_info.from_ptr(p).call(); } void ISQLite3Provider.sqlite3_progress_handler(sqlite3 db, int instructions, delegate_progress func, object v) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.progress != null) { val.progress.Dispose(); val.progress = null; } NativeMethods.callback_progress_handler func2; progress_hook_info val2; if (func != null) { func2 = progress_handler_hook_bridge; val2 = new progress_hook_info(func, v); } else { func2 = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.progress = val3.ForDispose(); NativeMethods.sqlite3_progress_handler(db, instructions, func2, val3); } [MonoPInvokeCallback(typeof(NativeMethods.callback_authorizer))] private static int authorizer_hook_bridge_impl(IntPtr p, int action_code, IntPtr param0, IntPtr param1, IntPtr dbName, IntPtr inner_most_trigger_or_view) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) return authorizer_hook_info.from_ptr(p).call(action_code, utf8z.FromIntPtr(param0), utf8z.FromIntPtr(param1), utf8z.FromIntPtr(dbName), utf8z.FromIntPtr(inner_most_trigger_or_view)); } int ISQLite3Provider.sqlite3_set_authorizer(sqlite3 db, delegate_authorizer func, object v) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown hook_handles val = get_hooks(db); if (val.authorizer != null) { val.authorizer.Dispose(); val.authorizer = null; } NativeMethods.callback_authorizer cb; authorizer_hook_info val2; if (func != null) { cb = authorizer_hook_bridge; val2 = new authorizer_hook_info(func, v); } else { cb = null; val2 = null; } hook_handle val3 = new hook_handle((object)val2); val.authorizer = val3.ForDispose(); return NativeMethods.sqlite3_set_authorizer(db, cb, val3); } long ISQLite3Provider.sqlite3_memory_used() { return NativeMethods.sqlite3_memory_used(); } long ISQLite3Provider.sqlite3_memory_highwater(int resetFlag) { return NativeMethods.sqlite3_memory_highwater(resetFlag); } long ISQLite3Provider.sqlite3_soft_heap_limit64(long n) { return NativeMethods.sqlite3_soft_heap_limit64(n); } long ISQLite3Provider.sqlite3_hard_heap_limit64(long n) { return NativeMethods.sqlite3_hard_heap_limit64(n); } int ISQLite3Provider.sqlite3_status(int op, out int current, out int highwater, int resetFlag) { return NativeMethods.sqlite3_status(op, out current, out highwater, resetFlag); } unsafe utf8z ISQLite3Provider.sqlite3_sourceid() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_sourceid()); } void ISQLite3Provider.sqlite3_result_int64(IntPtr ctx, long val) { NativeMethods.sqlite3_result_int64(ctx, val); } void ISQLite3Provider.sqlite3_result_int(IntPtr ctx, int val) { NativeMethods.sqlite3_result_int(ctx, val); } void ISQLite3Provider.sqlite3_result_double(IntPtr ctx, double val) { NativeMethods.sqlite3_result_double(ctx, val); } void ISQLite3Provider.sqlite3_result_null(IntPtr stm) { NativeMethods.sqlite3_result_null(stm); } unsafe void ISQLite3Provider.sqlite3_result_error(IntPtr ctx, ReadOnlySpan<byte> val) { fixed (byte* strErr = val) { NativeMethods.sqlite3_result_error(ctx, strErr, val.Length); } } unsafe void ISQLite3Provider.sqlite3_result_error(IntPtr ctx, utf8z val) { fixed (byte* strErr = ((utf8z)(ref val)).GetPinnableReference()) { NativeMethods.sqlite3_result_error(ctx, strErr, -1); } } unsafe void ISQLite3Provider.sqlite3_result_text(IntPtr ctx, ReadOnlySpan<byte> val) { fixed (byte* val2 = val) { NativeMethods.sqlite3_result_text(ctx, val2, val.Length, new IntPtr(-1)); } } unsafe void ISQLite3Provider.sqlite3_result_text(IntPtr ctx, utf8z val) { fixed (byte* val2 = ((utf8z)(ref val)).GetPinnableReference()) { NativeMethods.sqlite3_result_text(ctx, val2, -1, new IntPtr(-1)); } } unsafe void ISQLite3Provider.sqlite3_result_blob(IntPtr ctx, ReadOnlySpan<byte> blob) { fixed (byte* ptr = blob) { NativeMethods.sqlite3_result_blob(ctx, (IntPtr)ptr, blob.Length, new IntPtr(-1)); } } void ISQLite3Provider.sqlite3_result_zeroblob(IntPtr ctx, int n) { NativeMethods.sqlite3_result_zeroblob(ctx, n); } void ISQLite3Provider.sqlite3_result_error_toobig(IntPtr ctx) { NativeMethods.sqlite3_result_error_toobig(ctx); } void ISQLite3Provider.sqlite3_result_error_nomem(IntPtr ctx) { NativeMethods.sqlite3_result_error_nomem(ctx); } void ISQLite3Provider.sqlite3_result_error_code(IntPtr ctx, int code) { NativeMethods.sqlite3_result_error_code(ctx, code); } unsafe ReadOnlySpan<byte> ISQLite3Provider.sqlite3_value_blob(IntPtr p) { IntPtr intPtr = NativeMethods.sqlite3_value_blob(p); if (intPtr == IntPtr.Zero) { return null; } int length = NativeMethods.sqlite3_value_bytes(p); return new ReadOnlySpan<byte>(intPtr.ToPointer(), length); } int ISQLite3Provider.sqlite3_value_bytes(IntPtr p) { return NativeMethods.sqlite3_value_bytes(p); } double ISQLite3Provider.sqlite3_value_double(IntPtr p) { return NativeMethods.sqlite3_value_double(p); } int ISQLite3Provider.sqlite3_value_int(IntPtr p) { return NativeMethods.sqlite3_value_int(p); } long ISQLite3Provider.sqlite3_value_int64(IntPtr p) { return NativeMethods.sqlite3_value_int64(p); } int ISQLite3Provider.sqlite3_value_type(IntPtr p) { return NativeMethods.sqlite3_value_type(p); } unsafe utf8z ISQLite3Provider.sqlite3_value_text(IntPtr p) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_value_text(p)); } int ISQLite3Provider.sqlite3_bind_int(sqlite3_stmt stm, int paramIndex, int val) { return NativeMethods.sqlite3_bind_int(stm, paramIndex, val); } int ISQLite3Provider.sqlite3_bind_int64(sqlite3_stmt stm, int paramIndex, long val) { return NativeMethods.sqlite3_bind_int64(stm, paramIndex, val); } unsafe int ISQLite3Provider.sqlite3_bind_text(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<byte> t) { if (t.Length == 0) { byte b = 0; return NativeMethods.sqlite3_bind_text(stm, paramIndex, &b, 0, new IntPtr(-1)); } fixed (byte* val = t) { return NativeMethods.sqlite3_bind_text(stm, paramIndex, val, t.Length, new IntPtr(-1)); } } unsafe int ISQLite3Provider.sqlite3_bind_text16(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<char> t) { if (t.Length == 0) { char c = '\0'; return NativeMethods.sqlite3_bind_text16(stm, paramIndex, &c, 0, new IntPtr(-1)); } fixed (char* val = t) { return NativeMethods.sqlite3_bind_text16(stm, paramIndex, val, t.Length * 2, new IntPtr(-1)); } } unsafe int ISQLite3Provider.sqlite3_bind_text(sqlite3_stmt stm, int paramIndex, utf8z t) { fixed (byte* val = ((utf8z)(ref t)).GetPinnableReference()) { return NativeMethods.sqlite3_bind_text(stm, paramIndex, val, -1, new IntPtr(-1)); } } int ISQLite3Provider.sqlite3_bind_double(sqlite3_stmt stm, int paramIndex, double val) { return NativeMethods.sqlite3_bind_double(stm, paramIndex, val); } unsafe int ISQLite3Provider.sqlite3_bind_blob(sqlite3_stmt stm, int paramIndex, ReadOnlySpan<byte> blob) { if (blob.Length == 0) { byte b = 0; return NativeMethods.sqlite3_bind_blob(stm, paramIndex, &b, 0, new IntPtr(-1)); } fixed (byte* val = blob) { return NativeMethods.sqlite3_bind_blob(stm, paramIndex, val, blob.Length, new IntPtr(-1)); } } int ISQLite3Provider.sqlite3_bind_zeroblob(sqlite3_stmt stm, int paramIndex, int size) { return NativeMethods.sqlite3_bind_zeroblob(stm, paramIndex, size); } int ISQLite3Provider.sqlite3_bind_null(sqlite3_stmt stm, int paramIndex) { return NativeMethods.sqlite3_bind_null(stm, paramIndex); } int ISQLite3Provider.sqlite3_bind_parameter_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_bind_parameter_count(stm); } unsafe utf8z ISQLite3Provider.sqlite3_bind_parameter_name(sqlite3_stmt stm, int paramIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_bind_parameter_name(stm, paramIndex)); } unsafe int ISQLite3Provider.sqlite3_bind_parameter_index(sqlite3_stmt stm, utf8z paramName) { fixed (byte* strName = ((utf8z)(ref paramName)).GetPinnableReference()) { return NativeMethods.sqlite3_bind_parameter_index(stm, strName); } } int ISQLite3Provider.sqlite3_step(sqlite3_stmt stm) { return NativeMethods.sqlite3_step(stm); } int ISQLite3Provider.sqlite3_stmt_isexplain(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_isexplain(stm); } int ISQLite3Provider.sqlite3_stmt_busy(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_busy(stm); } int ISQLite3Provider.sqlite3_stmt_readonly(sqlite3_stmt stm) { return NativeMethods.sqlite3_stmt_readonly(stm); } int ISQLite3Provider.sqlite3_column_int(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_int(stm, columnIndex); } long ISQLite3Provider.sqlite3_column_int64(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_int64(stm, columnIndex); } unsafe utf8z ISQLite3Provider.sqlite3_column_text(sqlite3_stmt stm, int columnIndex) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) byte* intPtr = NativeMethods.sqlite3_column_text(stm, columnIndex); int num = NativeMethods.sqlite3_column_bytes(stm, columnIndex); return utf8z.FromPtrLen(intPtr, num); } unsafe utf8z ISQLite3Provider.sqlite3_column_decltype(sqlite3_stmt stm, int columnIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_column_decltype(stm, columnIndex)); } double ISQLite3Provider.sqlite3_column_double(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_double(stm, columnIndex); } unsafe ReadOnlySpan<byte> ISQLite3Provider.sqlite3_column_blob(sqlite3_stmt stm, int columnIndex) { IntPtr intPtr = NativeMethods.sqlite3_column_blob(stm, columnIndex); if (intPtr == IntPtr.Zero) { return null; } int length = NativeMethods.sqlite3_column_bytes(stm, columnIndex); return new ReadOnlySpan<byte>(intPtr.ToPointer(), length); } int ISQLite3Provider.sqlite3_column_type(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_type(stm, columnIndex); } int ISQLite3Provider.sqlite3_column_bytes(sqlite3_stmt stm, int columnIndex) { return NativeMethods.sqlite3_column_bytes(stm, columnIndex); } int ISQLite3Provider.sqlite3_column_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_column_count(stm); } int ISQLite3Provider.sqlite3_data_count(sqlite3_stmt stm) { return NativeMethods.sqlite3_data_count(stm); } unsafe utf8z ISQLite3Provider.sqlite3_column_name(sqlite3_stmt stm, int columnIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_column_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_origin_name(sqlite3_stmt stm, int columnIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_column_origin_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_table_name(sqlite3_stmt stm, int columnIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_column_table_name(stm, columnIndex)); } unsafe utf8z ISQLite3Provider.sqlite3_column_database_name(sqlite3_stmt stm, int columnIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return utf8z.FromPtr(NativeMethods.sqlite3_column_database_name(stm, columnIndex)); } int ISQLite3Provider.sqlite3_reset(sqlite3_stmt stm) { return NativeMethods.sqlite3_reset(stm); } int ISQLite3Provider.sqlite3_clear_bindings(sqlite3_stmt stm) { return NativeMethods.sqlite3_clear_bindings(stm); } int ISQLite3Provider.sqlite3_stmt_status(sqlite3_stmt stm, int op, int resetFlg) { return NativeMethods.sqlite3_stmt_status(stm, op, resetFlg); } int ISQLite3Provider.sqlite3_finalize(IntPtr stm) { return NativeMethods.sqlite3_finalize(stm); } int ISQLite3Provider.sqlite3_wal_autocheckpoint(sqlite3 db, int n) { return NativeMethods.sqlite3_wal_autocheckpoint(db, n); } unsafe int ISQLite3Provider.sqlite3_wal_checkpoint(sqlite3 db, utf8z dbName) { fixed (byte* dbName2 = ((utf8z)(ref dbName)).GetPinnableReference()) { return NativeMethods.sqlite3_wal_checkpoint(db, dbName2); } } unsafe int ISQLite3Provider.sqlite3_wal_checkpoint_v2(sqlite3 db, utf8z dbName, int eMode, out int logSize, out int framesCheckPointed) { fixed (byte* dbName2 = ((utf8z)(ref dbName)).GetPinnableReference()) { return NativeMethods.sqlite3_wal_checkpoint_v2(db, dbName2, eMode, out logSize, out framesCheckPointed); } } int ISQLite3Provider.sqlite3_keyword_count() { return NativeMethods.sqlite3_keyword_count(); } unsafe int ISQLite3Provider.sqlite3_keyword_name(int i, out string name) { byte* name2; int length; int result = NativeMethods.sqlite3_keyword_name(i, out name2, out length); name = Encoding.UTF8.GetString(name2, length); return result; } unsafe IntPtr ISQLite3Provider.sqlite3_serialize(sqlite3 db, utf8z schema, out long size, int flags) { fixed (byte* schema2 = ((utf8z)(ref schema)).GetPinnableReference()) { return NativeMethods.sqlite3_serialize(db, schema2, out size, flags); } } unsafe int ISQLite3Provider.sqlite3_deserialize(sqlite3 db, utf8z schema, IntPtr data, long szDb, long szBuf, int flags) { fixed (byte* schema2 = ((utf8z)(ref schema)).GetPinnableReference()) { return NativeMethods.sqlite3_deserialize(db, schema2, data, szDb, szBuf, flags); } } }
plugins/System.Buffers.dll
Decompiled 3 hours agousing System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Threading; using FxResources.System.Buffers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Buffers")] [assembly: AssemblyDescription("System.Buffers")] [assembly: AssemblyDefaultAlias("System.Buffers")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.25519.03")] [assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.2.0")] [module: UnverifiableCode] namespace FxResources.System.Buffers { internal static class SR { } } namespace System { internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Buffers.SR"; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool", null); internal static Type ResourceType => typeof(SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Buffers { public abstract class ArrayPool<T> { private static ArrayPool<T> s_sharedInstance; public static ArrayPool<T> Shared { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Volatile.Read(ref s_sharedInstance) ?? EnsureSharedCreated(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static ArrayPool<T> EnsureSharedCreated() { Interlocked.CompareExchange(ref s_sharedInstance, Create(), null); return s_sharedInstance; } public static ArrayPool<T> Create() { return new DefaultArrayPool<T>(); } public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) { return new DefaultArrayPool<T>(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal static readonly System.Buffers.ArrayPoolEventSource Log = new System.Buffers.ArrayPoolEventSource(); [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); WriteEventCore(1, 4, ptr); } [Event(2, Level = EventLevel.Informational)] internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason) { EventData* ptr = stackalloc EventData[5]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&reason); WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } } internal sealed class DefaultArrayPool<T> : ArrayPool<T> { private sealed class Bucket { internal readonly int _bufferLength; private readonly T[][] _buffers; private readonly int _poolId; private SpinLock _lock; private int _index; internal int Id => GetHashCode(); internal Bucket(int bufferLength, int numberOfBuffers, int poolId) { _lock = new SpinLock(Debugger.IsAttached); _buffers = new T[numberOfBuffers][]; _bufferLength = bufferLength; _poolId = poolId; } internal T[] Rent() { T[][] buffers = _buffers; T[] array = null; bool lockTaken = false; bool flag = false; try { _lock.Enter(ref lockTaken); if (_index < buffers.Length) { array = buffers[_index]; buffers[_index++] = null; flag = array == null; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (flag) { array = new T[_bufferLength]; System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(System.SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; try { _lock.Enter(ref lockTaken); if (_index != 0) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } } } private const int DefaultMaxArrayLength = 1048576; private const int DefaultMaxNumberOfArraysPerBucket = 50; private static T[] s_emptyArray; private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal DefaultArrayPool() : this(1048576, 50) { } internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket) { if (maxArrayLength <= 0) { throw new ArgumentOutOfRangeException("maxArrayLength"); } if (maxArraysPerBucket <= 0) { throw new ArgumentOutOfRangeException("maxArraysPerBucket"); } if (maxArrayLength > 1073741824) { maxArrayLength = 1073741824; } else if (maxArrayLength < 16) { maxArrayLength = 16; } int id = Id; int num = System.Buffers.Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(System.Buffers.Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return s_emptyArray ?? (s_emptyArray = new T[0]); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; T[] array = null; int num = System.Buffers.Utilities.SelectBucketIndex(minimumLength); if (num < _buckets.Length) { int num2 = num; do { array = _buckets[num2].Rent(); if (array != null) { if (log.IsEnabled()) { log.BufferRented(array.GetHashCode(), array.Length, Id, _buckets[num2].Id); } return array; } } while (++num2 < _buckets.Length && num2 != num + 2); array = new T[_buckets[num]._bufferLength]; } else { array = new T[minimumLength]; } if (log.IsEnabled()) { int hashCode = array.GetHashCode(); int bucketId = -1; log.BufferRented(hashCode, array.Length, Id, bucketId); log.BufferAllocated(hashCode, array.Length, Id, bucketId, (num >= _buckets.Length) ? System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : System.Buffers.ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Length == 0) { return; } int num = System.Buffers.Utilities.SelectBucketIndex(array.Length); if (num < _buckets.Length) { if (clearArray) { Array.Clear(array, 0, array.Length); } _buckets[num].Return(array); } System.Buffers.ArrayPoolEventSource log = System.Buffers.ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferReturned(array.GetHashCode(), array.Length, Id); } } } internal static class Utilities { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { uint num = (uint)(bufferSize - 1) >> 4; int num2 = 0; if (num > 65535) { num >>= 16; num2 = 16; } if (num > 255) { num >>= 8; num2 += 8; } if (num > 15) { num >>= 4; num2 += 4; } if (num > 3) { num >>= 2; num2 += 2; } if (num > 1) { num >>= 1; num2++; } return num2 + (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } } }
plugins/System.Numerics.Vectors.dll
Decompiled 3 hours ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Diagnostics; using System.Globalization; using System.Numerics.Hashing; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using FxResources.System.Numerics.Vectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyTitle("System.Numerics.Vectors")] [assembly: AssemblyDescription("System.Numerics.Vectors")] [assembly: AssemblyDefaultAlias("System.Numerics.Vectors")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyProduct("Microsoft® .NET Framework")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyFileVersion("4.6.25519.03")] [assembly: AssemblyInformationalVersion("4.6.25519.03 built by: dlab-DDVSOWINAGE013. Commit Hash: 8321c729934c0f8be754953439b88e6e1c120c24")] [assembly: CLSCompliant(true)] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata("PreferInbox", "True")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.1.3.0")] [module: UnverifiableCode] namespace FxResources.System.Numerics.Vectors { internal static class SR { } } namespace System { internal static class MathF { public const float PI = 3.1415927f; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Acos(float x) { return (float)Math.Acos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Cos(float x) { return (float)Math.Cos(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float IEEERemainder(float x, float y) { return (float)Math.IEEERemainder(x, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sin(float x) { return (float)Math.Sin(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sqrt(float x) { return (float)Math.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Tan(float x) { return (float)Math.Tan(x); } } internal static class SR { private static ResourceManager s_resourceManager; private const string s_resourcesName = "FxResources.System.Numerics.Vectors.SR"; private static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(ResourceType)); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException", null); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination", null); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef", null); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported", null); internal static Type ResourceType => typeof(SR); [MethodImpl(MethodImplOptions.NoInlining)] private static bool UsingResourceKeys() { return false; } internal static string GetResourceString(string resourceKey, string defaultString) { string text = null; try { text = ResourceManager.GetString(resourceKey); } catch (MissingManifestResourceException) { } if (defaultString != null && resourceKey.Equals(text, StringComparison.Ordinal)) { return defaultString; } return text; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.All)] internal class __BlockReflectionAttribute : Attribute { } } namespace System.Numerics { internal class ConstantHelper { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte GetByteWithAllBitsSet() { byte result = 0; result = byte.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte GetSByteWithAllBitsSet() { sbyte result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort GetUInt16WithAllBitsSet() { ushort result = 0; result = ushort.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short GetInt16WithAllBitsSet() { short result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint GetUInt32WithAllBitsSet() { uint result = 0u; result = uint.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetInt32WithAllBitsSet() { int result = 0; result = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong GetUInt64WithAllBitsSet() { ulong result = 0uL; result = ulong.MaxValue; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long GetInt64WithAllBitsSet() { long result = 0L; result = -1L; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float GetSingleWithAllBitsSet() { float result = 0f; *(int*)(&result) = -1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double GetDoubleWithAllBitsSet() { double result = 0.0; *(long*)(&result) = -1L; return result; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] internal class JitIntrinsicAttribute : Attribute { } [StructLayout(LayoutKind.Explicit)] internal struct Register { [FieldOffset(0)] internal byte byte_0; [FieldOffset(1)] internal byte byte_1; [FieldOffset(2)] internal byte byte_2; [FieldOffset(3)] internal byte byte_3; [FieldOffset(4)] internal byte byte_4; [FieldOffset(5)] internal byte byte_5; [FieldOffset(6)] internal byte byte_6; [FieldOffset(7)] internal byte byte_7; [FieldOffset(8)] internal byte byte_8; [FieldOffset(9)] internal byte byte_9; [FieldOffset(10)] internal byte byte_10; [FieldOffset(11)] internal byte byte_11; [FieldOffset(12)] internal byte byte_12; [FieldOffset(13)] internal byte byte_13; [FieldOffset(14)] internal byte byte_14; [FieldOffset(15)] internal byte byte_15; [FieldOffset(0)] internal sbyte sbyte_0; [FieldOffset(1)] internal sbyte sbyte_1; [FieldOffset(2)] internal sbyte sbyte_2; [FieldOffset(3)] internal sbyte sbyte_3; [FieldOffset(4)] internal sbyte sbyte_4; [FieldOffset(5)] internal sbyte sbyte_5; [FieldOffset(6)] internal sbyte sbyte_6; [FieldOffset(7)] internal sbyte sbyte_7; [FieldOffset(8)] internal sbyte sbyte_8; [FieldOffset(9)] internal sbyte sbyte_9; [FieldOffset(10)] internal sbyte sbyte_10; [FieldOffset(11)] internal sbyte sbyte_11; [FieldOffset(12)] internal sbyte sbyte_12; [FieldOffset(13)] internal sbyte sbyte_13; [FieldOffset(14)] internal sbyte sbyte_14; [FieldOffset(15)] internal sbyte sbyte_15; [FieldOffset(0)] internal ushort uint16_0; [FieldOffset(2)] internal ushort uint16_1; [FieldOffset(4)] internal ushort uint16_2; [FieldOffset(6)] internal ushort uint16_3; [FieldOffset(8)] internal ushort uint16_4; [FieldOffset(10)] internal ushort uint16_5; [FieldOffset(12)] internal ushort uint16_6; [FieldOffset(14)] internal ushort uint16_7; [FieldOffset(0)] internal short int16_0; [FieldOffset(2)] internal short int16_1; [FieldOffset(4)] internal short int16_2; [FieldOffset(6)] internal short int16_3; [FieldOffset(8)] internal short int16_4; [FieldOffset(10)] internal short int16_5; [FieldOffset(12)] internal short int16_6; [FieldOffset(14)] internal short int16_7; [FieldOffset(0)] internal uint uint32_0; [FieldOffset(4)] internal uint uint32_1; [FieldOffset(8)] internal uint uint32_2; [FieldOffset(12)] internal uint uint32_3; [FieldOffset(0)] internal int int32_0; [FieldOffset(4)] internal int int32_1; [FieldOffset(8)] internal int int32_2; [FieldOffset(12)] internal int int32_3; [FieldOffset(0)] internal ulong uint64_0; [FieldOffset(8)] internal ulong uint64_1; [FieldOffset(0)] internal long int64_0; [FieldOffset(8)] internal long int64_1; [FieldOffset(0)] internal float single_0; [FieldOffset(4)] internal float single_1; [FieldOffset(8)] internal float single_2; [FieldOffset(12)] internal float single_3; [FieldOffset(0)] internal double double_0; [FieldOffset(8)] internal double double_1; } public struct Vector<T> : IEquatable<Vector<T>>, IFormattable where T : struct { private struct VectorSizeHelper { internal Vector<T> _placeholder; internal byte _byte; } private System.Numerics.Register register; private static readonly int s_count = InitializeCount(); private static readonly Vector<T> zero = new Vector<T>(GetZeroValue()); private static readonly Vector<T> one = new Vector<T>(GetOneValue()); private static readonly Vector<T> allOnes = new Vector<T>(GetAllBitsSetValue()); [JitIntrinsic] public static int Count => s_count; [JitIntrinsic] public static Vector<T> Zero => zero; [JitIntrinsic] public static Vector<T> One => one; internal static Vector<T> AllOnes => allOnes; [JitIntrinsic] public unsafe T this[int index] { get { if (index >= Count || index < 0) { throw new IndexOutOfRangeException(System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, index)); } if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { return (T)(object)ptr[index]; } } if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { return (T)(object)ptr2[index]; } } if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { return (T)(object)ptr3[index]; } } if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { return (T)(object)ptr4[index]; } } if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { return (T)(object)ptr5[index]; } } if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { return (T)(object)ptr6[index]; } } if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { return (T)(object)ptr7[index]; } } if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { return (T)(object)ptr8[index]; } } if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { return (T)(object)ptr9[index]; } } if (typeof(T) == typeof(double)) { fixed (double* ptr10 = ®ister.double_0) { return (T)(object)ptr10[index]; } } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } } private unsafe static int InitializeCount() { VectorSizeHelper vectorSizeHelper = default(VectorSizeHelper); byte* ptr = &vectorSizeHelper._placeholder.register.byte_0; byte* ptr2 = &vectorSizeHelper._byte; int num = (int)(ptr2 - ptr); int num2 = -1; if (typeof(T) == typeof(byte)) { num2 = 1; } else if (typeof(T) == typeof(sbyte)) { num2 = 1; } else if (typeof(T) == typeof(ushort)) { num2 = 2; } else if (typeof(T) == typeof(short)) { num2 = 2; } else if (typeof(T) == typeof(uint)) { num2 = 4; } else if (typeof(T) == typeof(int)) { num2 = 4; } else if (typeof(T) == typeof(ulong)) { num2 = 8; } else if (typeof(T) == typeof(long)) { num2 = 8; } else if (typeof(T) == typeof(float)) { num2 = 4; } else { if (!(typeof(T) == typeof(double))) { throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } num2 = 8; } return num / num2; } [JitIntrinsic] public unsafe Vector(T value) { this = default(Vector<T>); if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)value; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)value; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)value; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)value; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)value; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)value; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)value; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)value; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)value; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)value; } } } } else if (typeof(T) == typeof(byte)) { register.byte_0 = (byte)(object)value; register.byte_1 = (byte)(object)value; register.byte_2 = (byte)(object)value; register.byte_3 = (byte)(object)value; register.byte_4 = (byte)(object)value; register.byte_5 = (byte)(object)value; register.byte_6 = (byte)(object)value; register.byte_7 = (byte)(object)value; register.byte_8 = (byte)(object)value; register.byte_9 = (byte)(object)value; register.byte_10 = (byte)(object)value; register.byte_11 = (byte)(object)value; register.byte_12 = (byte)(object)value; register.byte_13 = (byte)(object)value; register.byte_14 = (byte)(object)value; register.byte_15 = (byte)(object)value; } else if (typeof(T) == typeof(sbyte)) { register.sbyte_0 = (sbyte)(object)value; register.sbyte_1 = (sbyte)(object)value; register.sbyte_2 = (sbyte)(object)value; register.sbyte_3 = (sbyte)(object)value; register.sbyte_4 = (sbyte)(object)value; register.sbyte_5 = (sbyte)(object)value; register.sbyte_6 = (sbyte)(object)value; register.sbyte_7 = (sbyte)(object)value; register.sbyte_8 = (sbyte)(object)value; register.sbyte_9 = (sbyte)(object)value; register.sbyte_10 = (sbyte)(object)value; register.sbyte_11 = (sbyte)(object)value; register.sbyte_12 = (sbyte)(object)value; register.sbyte_13 = (sbyte)(object)value; register.sbyte_14 = (sbyte)(object)value; register.sbyte_15 = (sbyte)(object)value; } else if (typeof(T) == typeof(ushort)) { register.uint16_0 = (ushort)(object)value; register.uint16_1 = (ushort)(object)value; register.uint16_2 = (ushort)(object)value; register.uint16_3 = (ushort)(object)value; register.uint16_4 = (ushort)(object)value; register.uint16_5 = (ushort)(object)value; register.uint16_6 = (ushort)(object)value; register.uint16_7 = (ushort)(object)value; } else if (typeof(T) == typeof(short)) { register.int16_0 = (short)(object)value; register.int16_1 = (short)(object)value; register.int16_2 = (short)(object)value; register.int16_3 = (short)(object)value; register.int16_4 = (short)(object)value; register.int16_5 = (short)(object)value; register.int16_6 = (short)(object)value; register.int16_7 = (short)(object)value; } else if (typeof(T) == typeof(uint)) { register.uint32_0 = (uint)(object)value; register.uint32_1 = (uint)(object)value; register.uint32_2 = (uint)(object)value; register.uint32_3 = (uint)(object)value; } else if (typeof(T) == typeof(int)) { register.int32_0 = (int)(object)value; register.int32_1 = (int)(object)value; register.int32_2 = (int)(object)value; register.int32_3 = (int)(object)value; } else if (typeof(T) == typeof(ulong)) { register.uint64_0 = (ulong)(object)value; register.uint64_1 = (ulong)(object)value; } else if (typeof(T) == typeof(long)) { register.int64_0 = (long)(object)value; register.int64_1 = (long)(object)value; } else if (typeof(T) == typeof(float)) { register.single_0 = (float)(object)value; register.single_1 = (float)(object)value; register.single_2 = (float)(object)value; register.single_3 = (float)(object)value; } else if (typeof(T) == typeof(double)) { register.double_0 = (double)(object)value; register.double_1 = (double)(object)value; } } [JitIntrinsic] public Vector(T[] values) : this(values, 0) { } public unsafe Vector(T[] values, int index) { this = default(Vector<T>); if (values == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { throw new IndexOutOfRangeException(); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)values[i + index]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)values[j + index]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)values[k + index]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)values[l + index]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)values[m + index]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)values[n + index]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)values[num + index]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)values[num2 + index]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)values[num3 + index]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)values[num4 + index]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = ®ister.byte_0) { *ptr11 = (byte)(object)values[index]; ptr11[1] = (byte)(object)values[1 + index]; ptr11[2] = (byte)(object)values[2 + index]; ptr11[3] = (byte)(object)values[3 + index]; ptr11[4] = (byte)(object)values[4 + index]; ptr11[5] = (byte)(object)values[5 + index]; ptr11[6] = (byte)(object)values[6 + index]; ptr11[7] = (byte)(object)values[7 + index]; ptr11[8] = (byte)(object)values[8 + index]; ptr11[9] = (byte)(object)values[9 + index]; ptr11[10] = (byte)(object)values[10 + index]; ptr11[11] = (byte)(object)values[11 + index]; ptr11[12] = (byte)(object)values[12 + index]; ptr11[13] = (byte)(object)values[13 + index]; ptr11[14] = (byte)(object)values[14 + index]; ptr11[15] = (byte)(object)values[15 + index]; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = ®ister.sbyte_0) { *ptr12 = (sbyte)(object)values[index]; ptr12[1] = (sbyte)(object)values[1 + index]; ptr12[2] = (sbyte)(object)values[2 + index]; ptr12[3] = (sbyte)(object)values[3 + index]; ptr12[4] = (sbyte)(object)values[4 + index]; ptr12[5] = (sbyte)(object)values[5 + index]; ptr12[6] = (sbyte)(object)values[6 + index]; ptr12[7] = (sbyte)(object)values[7 + index]; ptr12[8] = (sbyte)(object)values[8 + index]; ptr12[9] = (sbyte)(object)values[9 + index]; ptr12[10] = (sbyte)(object)values[10 + index]; ptr12[11] = (sbyte)(object)values[11 + index]; ptr12[12] = (sbyte)(object)values[12 + index]; ptr12[13] = (sbyte)(object)values[13 + index]; ptr12[14] = (sbyte)(object)values[14 + index]; ptr12[15] = (sbyte)(object)values[15 + index]; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = ®ister.uint16_0) { *ptr13 = (ushort)(object)values[index]; ptr13[1] = (ushort)(object)values[1 + index]; ptr13[2] = (ushort)(object)values[2 + index]; ptr13[3] = (ushort)(object)values[3 + index]; ptr13[4] = (ushort)(object)values[4 + index]; ptr13[5] = (ushort)(object)values[5 + index]; ptr13[6] = (ushort)(object)values[6 + index]; ptr13[7] = (ushort)(object)values[7 + index]; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = ®ister.int16_0) { *ptr14 = (short)(object)values[index]; ptr14[1] = (short)(object)values[1 + index]; ptr14[2] = (short)(object)values[2 + index]; ptr14[3] = (short)(object)values[3 + index]; ptr14[4] = (short)(object)values[4 + index]; ptr14[5] = (short)(object)values[5 + index]; ptr14[6] = (short)(object)values[6 + index]; ptr14[7] = (short)(object)values[7 + index]; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = ®ister.uint32_0) { *ptr15 = (uint)(object)values[index]; ptr15[1] = (uint)(object)values[1 + index]; ptr15[2] = (uint)(object)values[2 + index]; ptr15[3] = (uint)(object)values[3 + index]; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = ®ister.int32_0) { *ptr16 = (int)(object)values[index]; ptr16[1] = (int)(object)values[1 + index]; ptr16[2] = (int)(object)values[2 + index]; ptr16[3] = (int)(object)values[3 + index]; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = ®ister.uint64_0) { *ptr17 = (ulong)(object)values[index]; ptr17[1] = (ulong)(object)values[1 + index]; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = ®ister.int64_0) { *ptr18 = (long)(object)values[index]; ptr18[1] = (long)(object)values[1 + index]; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = ®ister.single_0) { *ptr19 = (float)(object)values[index]; ptr19[1] = (float)(object)values[1 + index]; ptr19[2] = (float)(object)values[2 + index]; ptr19[3] = (float)(object)values[3 + index]; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = ®ister.double_0) { *ptr20 = (double)(object)values[index]; ptr20[1] = (double)(object)values[1 + index]; } } } internal unsafe Vector(void* dataPointer) : this(dataPointer, 0) { } internal unsafe Vector(void* dataPointer, int offset) { this = default(Vector<T>); if (typeof(T) == typeof(byte)) { byte* ptr = (byte*)dataPointer; ptr += offset; fixed (byte* ptr2 = ®ister.byte_0) { for (int i = 0; i < Count; i++) { ptr2[i] = ptr[i]; } } return; } if (typeof(T) == typeof(sbyte)) { sbyte* ptr3 = (sbyte*)dataPointer; ptr3 += offset; fixed (sbyte* ptr4 = ®ister.sbyte_0) { for (int j = 0; j < Count; j++) { ptr4[j] = ptr3[j]; } } return; } if (typeof(T) == typeof(ushort)) { ushort* ptr5 = (ushort*)dataPointer; ptr5 += offset; fixed (ushort* ptr6 = ®ister.uint16_0) { for (int k = 0; k < Count; k++) { ptr6[k] = ptr5[k]; } } return; } if (typeof(T) == typeof(short)) { short* ptr7 = (short*)dataPointer; ptr7 += offset; fixed (short* ptr8 = ®ister.int16_0) { for (int l = 0; l < Count; l++) { ptr8[l] = ptr7[l]; } } return; } if (typeof(T) == typeof(uint)) { uint* ptr9 = (uint*)dataPointer; ptr9 += offset; fixed (uint* ptr10 = ®ister.uint32_0) { for (int m = 0; m < Count; m++) { ptr10[m] = ptr9[m]; } } return; } if (typeof(T) == typeof(int)) { int* ptr11 = (int*)dataPointer; ptr11 += offset; fixed (int* ptr12 = ®ister.int32_0) { for (int n = 0; n < Count; n++) { ptr12[n] = ptr11[n]; } } return; } if (typeof(T) == typeof(ulong)) { ulong* ptr13 = (ulong*)dataPointer; ptr13 += offset; fixed (ulong* ptr14 = ®ister.uint64_0) { for (int num = 0; num < Count; num++) { ptr14[num] = ptr13[num]; } } return; } if (typeof(T) == typeof(long)) { long* ptr15 = (long*)dataPointer; ptr15 += offset; fixed (long* ptr16 = ®ister.int64_0) { for (int num2 = 0; num2 < Count; num2++) { ptr16[num2] = ptr15[num2]; } } return; } if (typeof(T) == typeof(float)) { float* ptr17 = (float*)dataPointer; ptr17 += offset; fixed (float* ptr18 = ®ister.single_0) { for (int num3 = 0; num3 < Count; num3++) { ptr18[num3] = ptr17[num3]; } } return; } if (typeof(T) == typeof(double)) { double* ptr19 = (double*)dataPointer; ptr19 += offset; fixed (double* ptr20 = ®ister.double_0) { for (int num4 = 0; num4 < Count; num4++) { ptr20[num4] = ptr19[num4]; } } return; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } private Vector(ref System.Numerics.Register existingRegister) { register = existingRegister; } [JitIntrinsic] public void CopyTo(T[] destination) { CopyTo(destination, 0); } [JitIntrinsic] public unsafe void CopyTo(T[] destination, int startIndex) { if (destination == null) { throw new NullReferenceException(System.SR.Arg_NullArgumentNullRef); } if (startIndex < 0 || startIndex >= destination.Length) { throw new ArgumentOutOfRangeException("startIndex", System.SR.Format(System.SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(System.SR.Format(System.SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { fixed (byte* ptr = (byte[])(object)destination) { for (int i = 0; i < Count; i++) { ptr[startIndex + i] = (byte)(object)this[i]; } } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr2 = (sbyte[])(object)destination) { for (int j = 0; j < Count; j++) { ptr2[startIndex + j] = (sbyte)(object)this[j]; } } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr3 = (ushort[])(object)destination) { for (int k = 0; k < Count; k++) { ptr3[startIndex + k] = (ushort)(object)this[k]; } } } else if (typeof(T) == typeof(short)) { fixed (short* ptr4 = (short[])(object)destination) { for (int l = 0; l < Count; l++) { ptr4[startIndex + l] = (short)(object)this[l]; } } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr5 = (uint[])(object)destination) { for (int m = 0; m < Count; m++) { ptr5[startIndex + m] = (uint)(object)this[m]; } } } else if (typeof(T) == typeof(int)) { fixed (int* ptr6 = (int[])(object)destination) { for (int n = 0; n < Count; n++) { ptr6[startIndex + n] = (int)(object)this[n]; } } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr7 = (ulong[])(object)destination) { for (int num = 0; num < Count; num++) { ptr7[startIndex + num] = (ulong)(object)this[num]; } } } else if (typeof(T) == typeof(long)) { fixed (long* ptr8 = (long[])(object)destination) { for (int num2 = 0; num2 < Count; num2++) { ptr8[startIndex + num2] = (long)(object)this[num2]; } } } else if (typeof(T) == typeof(float)) { fixed (float* ptr9 = (float[])(object)destination) { for (int num3 = 0; num3 < Count; num3++) { ptr9[startIndex + num3] = (float)(object)this[num3]; } } } else { if (!(typeof(T) == typeof(double))) { return; } fixed (double* ptr10 = (double[])(object)destination) { for (int num4 = 0; num4 < Count; num4++) { ptr10[startIndex + num4] = (double)(object)this[num4]; } } } } else if (typeof(T) == typeof(byte)) { fixed (byte* ptr11 = (byte[])(object)destination) { ptr11[startIndex] = register.byte_0; ptr11[startIndex + 1] = register.byte_1; ptr11[startIndex + 2] = register.byte_2; ptr11[startIndex + 3] = register.byte_3; ptr11[startIndex + 4] = register.byte_4; ptr11[startIndex + 5] = register.byte_5; ptr11[startIndex + 6] = register.byte_6; ptr11[startIndex + 7] = register.byte_7; ptr11[startIndex + 8] = register.byte_8; ptr11[startIndex + 9] = register.byte_9; ptr11[startIndex + 10] = register.byte_10; ptr11[startIndex + 11] = register.byte_11; ptr11[startIndex + 12] = register.byte_12; ptr11[startIndex + 13] = register.byte_13; ptr11[startIndex + 14] = register.byte_14; ptr11[startIndex + 15] = register.byte_15; } } else if (typeof(T) == typeof(sbyte)) { fixed (sbyte* ptr12 = (sbyte[])(object)destination) { ptr12[startIndex] = register.sbyte_0; ptr12[startIndex + 1] = register.sbyte_1; ptr12[startIndex + 2] = register.sbyte_2; ptr12[startIndex + 3] = register.sbyte_3; ptr12[startIndex + 4] = register.sbyte_4; ptr12[startIndex + 5] = register.sbyte_5; ptr12[startIndex + 6] = register.sbyte_6; ptr12[startIndex + 7] = register.sbyte_7; ptr12[startIndex + 8] = register.sbyte_8; ptr12[startIndex + 9] = register.sbyte_9; ptr12[startIndex + 10] = register.sbyte_10; ptr12[startIndex + 11] = register.sbyte_11; ptr12[startIndex + 12] = register.sbyte_12; ptr12[startIndex + 13] = register.sbyte_13; ptr12[startIndex + 14] = register.sbyte_14; ptr12[startIndex + 15] = register.sbyte_15; } } else if (typeof(T) == typeof(ushort)) { fixed (ushort* ptr13 = (ushort[])(object)destination) { ptr13[startIndex] = register.uint16_0; ptr13[startIndex + 1] = register.uint16_1; ptr13[startIndex + 2] = register.uint16_2; ptr13[startIndex + 3] = register.uint16_3; ptr13[startIndex + 4] = register.uint16_4; ptr13[startIndex + 5] = register.uint16_5; ptr13[startIndex + 6] = register.uint16_6; ptr13[startIndex + 7] = register.uint16_7; } } else if (typeof(T) == typeof(short)) { fixed (short* ptr14 = (short[])(object)destination) { ptr14[startIndex] = register.int16_0; ptr14[startIndex + 1] = register.int16_1; ptr14[startIndex + 2] = register.int16_2; ptr14[startIndex + 3] = register.int16_3; ptr14[startIndex + 4] = register.int16_4; ptr14[startIndex + 5] = register.int16_5; ptr14[startIndex + 6] = register.int16_6; ptr14[startIndex + 7] = register.int16_7; } } else if (typeof(T) == typeof(uint)) { fixed (uint* ptr15 = (uint[])(object)destination) { ptr15[startIndex] = register.uint32_0; ptr15[startIndex + 1] = register.uint32_1; ptr15[startIndex + 2] = register.uint32_2; ptr15[startIndex + 3] = register.uint32_3; } } else if (typeof(T) == typeof(int)) { fixed (int* ptr16 = (int[])(object)destination) { ptr16[startIndex] = register.int32_0; ptr16[startIndex + 1] = register.int32_1; ptr16[startIndex + 2] = register.int32_2; ptr16[startIndex + 3] = register.int32_3; } } else if (typeof(T) == typeof(ulong)) { fixed (ulong* ptr17 = (ulong[])(object)destination) { ptr17[startIndex] = register.uint64_0; ptr17[startIndex + 1] = register.uint64_1; } } else if (typeof(T) == typeof(long)) { fixed (long* ptr18 = (long[])(object)destination) { ptr18[startIndex] = register.int64_0; ptr18[startIndex + 1] = register.int64_1; } } else if (typeof(T) == typeof(float)) { fixed (float* ptr19 = (float[])(object)destination) { ptr19[startIndex] = register.single_0; ptr19[startIndex + 1] = register.single_1; ptr19[startIndex + 2] = register.single_2; ptr19[startIndex + 3] = register.single_3; } } else if (typeof(T) == typeof(double)) { fixed (double* ptr20 = (double[])(object)destination) { ptr20[startIndex] = register.double_0; ptr20[startIndex + 1] = register.double_1; } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { if (!(obj is Vector<T>)) { return false; } return Equals((Vector<T>)obj); } [JitIntrinsic] public bool Equals(Vector<T> other) { if (Vector.IsHardwareAccelerated) { for (int i = 0; i < Count; i++) { if (!ScalarEquals(this[i], other[i])) { return false; } } return true; } if (typeof(T) == typeof(byte)) { if (register.byte_0 == other.register.byte_0 && register.byte_1 == other.register.byte_1 && register.byte_2 == other.register.byte_2 && register.byte_3 == other.register.byte_3 && register.byte_4 == other.register.byte_4 && register.byte_5 == other.register.byte_5 && register.byte_6 == other.register.byte_6 && register.byte_7 == other.register.byte_7 && register.byte_8 == other.register.byte_8 && register.byte_9 == other.register.byte_9 && register.byte_10 == other.register.byte_10 && register.byte_11 == other.register.byte_11 && register.byte_12 == other.register.byte_12 && register.byte_13 == other.register.byte_13 && register.byte_14 == other.register.byte_14) { return register.byte_15 == other.register.byte_15; } return false; } if (typeof(T) == typeof(sbyte)) { if (register.sbyte_0 == other.register.sbyte_0 && register.sbyte_1 == other.register.sbyte_1 && register.sbyte_2 == other.register.sbyte_2 && register.sbyte_3 == other.register.sbyte_3 && register.sbyte_4 == other.register.sbyte_4 && register.sbyte_5 == other.register.sbyte_5 && register.sbyte_6 == other.register.sbyte_6 && register.sbyte_7 == other.register.sbyte_7 && register.sbyte_8 == other.register.sbyte_8 && register.sbyte_9 == other.register.sbyte_9 && register.sbyte_10 == other.register.sbyte_10 && register.sbyte_11 == other.register.sbyte_11 && register.sbyte_12 == other.register.sbyte_12 && register.sbyte_13 == other.register.sbyte_13 && register.sbyte_14 == other.register.sbyte_14) { return register.sbyte_15 == other.register.sbyte_15; } return false; } if (typeof(T) == typeof(ushort)) { if (register.uint16_0 == other.register.uint16_0 && register.uint16_1 == other.register.uint16_1 && register.uint16_2 == other.register.uint16_2 && register.uint16_3 == other.register.uint16_3 && register.uint16_4 == other.register.uint16_4 && register.uint16_5 == other.register.uint16_5 && register.uint16_6 == other.register.uint16_6) { return register.uint16_7 == other.register.uint16_7; } return false; } if (typeof(T) == typeof(short)) { if (register.int16_0 == other.register.int16_0 && register.int16_1 == other.register.int16_1 && register.int16_2 == other.register.int16_2 && register.int16_3 == other.register.int16_3 && register.int16_4 == other.register.int16_4 && register.int16_5 == other.register.int16_5 && register.int16_6 == other.register.int16_6) { return register.int16_7 == other.register.int16_7; } return false; } if (typeof(T) == typeof(uint)) { if (register.uint32_0 == other.register.uint32_0 && register.uint32_1 == other.register.uint32_1 && register.uint32_2 == other.register.uint32_2) { return register.uint32_3 == other.register.uint32_3; } return false; } if (typeof(T) == typeof(int)) { if (register.int32_0 == other.register.int32_0 && register.int32_1 == other.register.int32_1 && register.int32_2 == other.register.int32_2) { return register.int32_3 == other.register.int32_3; } return false; } if (typeof(T) == typeof(ulong)) { if (register.uint64_0 == other.register.uint64_0) { return register.uint64_1 == other.register.uint64_1; } return false; } if (typeof(T) == typeof(long)) { if (register.int64_0 == other.register.int64_0) { return register.int64_1 == other.register.int64_1; } return false; } if (typeof(T) == typeof(float)) { if (register.single_0 == other.register.single_0 && register.single_1 == other.register.single_1 && register.single_2 == other.register.single_2) { return register.single_3 == other.register.single_3; } return false; } if (typeof(T) == typeof(double)) { if (register.double_0 == other.register.double_0) { return register.double_1 == other.register.double_1; } return false; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override int GetHashCode() { int num = 0; if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { for (int i = 0; i < Count; i++) { num = HashHelpers.Combine(num, ((byte)(object)this[i]).GetHashCode()); } return num; } if (typeof(T) == typeof(sbyte)) { for (int j = 0; j < Count; j++) { num = HashHelpers.Combine(num, ((sbyte)(object)this[j]).GetHashCode()); } return num; } if (typeof(T) == typeof(ushort)) { for (int k = 0; k < Count; k++) { num = HashHelpers.Combine(num, ((ushort)(object)this[k]).GetHashCode()); } return num; } if (typeof(T) == typeof(short)) { for (int l = 0; l < Count; l++) { num = HashHelpers.Combine(num, ((short)(object)this[l]).GetHashCode()); } return num; } if (typeof(T) == typeof(uint)) { for (int m = 0; m < Count; m++) { num = HashHelpers.Combine(num, ((uint)(object)this[m]).GetHashCode()); } return num; } if (typeof(T) == typeof(int)) { for (int n = 0; n < Count; n++) { num = HashHelpers.Combine(num, ((int)(object)this[n]).GetHashCode()); } return num; } if (typeof(T) == typeof(ulong)) { for (int num2 = 0; num2 < Count; num2++) { num = HashHelpers.Combine(num, ((ulong)(object)this[num2]).GetHashCode()); } return num; } if (typeof(T) == typeof(long)) { for (int num3 = 0; num3 < Count; num3++) { num = HashHelpers.Combine(num, ((long)(object)this[num3]).GetHashCode()); } return num; } if (typeof(T) == typeof(float)) { for (int num4 = 0; num4 < Count; num4++) { num = HashHelpers.Combine(num, ((float)(object)this[num4]).GetHashCode()); } return num; } if (typeof(T) == typeof(double)) { for (int num5 = 0; num5 < Count; num5++) { num = HashHelpers.Combine(num, ((double)(object)this[num5]).GetHashCode()); } return num; } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } if (typeof(T) == typeof(byte)) { num = HashHelpers.Combine(num, register.byte_0.GetHashCode()); num = HashHelpers.Combine(num, register.byte_1.GetHashCode()); num = HashHelpers.Combine(num, register.byte_2.GetHashCode()); num = HashHelpers.Combine(num, register.byte_3.GetHashCode()); num = HashHelpers.Combine(num, register.byte_4.GetHashCode()); num = HashHelpers.Combine(num, register.byte_5.GetHashCode()); num = HashHelpers.Combine(num, register.byte_6.GetHashCode()); num = HashHelpers.Combine(num, register.byte_7.GetHashCode()); num = HashHelpers.Combine(num, register.byte_8.GetHashCode()); num = HashHelpers.Combine(num, register.byte_9.GetHashCode()); num = HashHelpers.Combine(num, register.byte_10.GetHashCode()); num = HashHelpers.Combine(num, register.byte_11.GetHashCode()); num = HashHelpers.Combine(num, register.byte_12.GetHashCode()); num = HashHelpers.Combine(num, register.byte_13.GetHashCode()); num = HashHelpers.Combine(num, register.byte_14.GetHashCode()); return HashHelpers.Combine(num, register.byte_15.GetHashCode()); } if (typeof(T) == typeof(sbyte)) { num = HashHelpers.Combine(num, register.sbyte_0.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_1.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_2.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_3.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_4.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_5.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_6.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_7.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_8.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_9.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_10.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_11.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_12.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_13.GetHashCode()); num = HashHelpers.Combine(num, register.sbyte_14.GetHashCode()); return HashHelpers.Combine(num, register.sbyte_15.GetHashCode()); } if (typeof(T) == typeof(ushort)) { num = HashHelpers.Combine(num, register.uint16_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_2.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_3.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_4.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_5.GetHashCode()); num = HashHelpers.Combine(num, register.uint16_6.GetHashCode()); return HashHelpers.Combine(num, register.uint16_7.GetHashCode()); } if (typeof(T) == typeof(short)) { num = HashHelpers.Combine(num, register.int16_0.GetHashCode()); num = HashHelpers.Combine(num, register.int16_1.GetHashCode()); num = HashHelpers.Combine(num, register.int16_2.GetHashCode()); num = HashHelpers.Combine(num, register.int16_3.GetHashCode()); num = HashHelpers.Combine(num, register.int16_4.GetHashCode()); num = HashHelpers.Combine(num, register.int16_5.GetHashCode()); num = HashHelpers.Combine(num, register.int16_6.GetHashCode()); return HashHelpers.Combine(num, register.int16_7.GetHashCode()); } if (typeof(T) == typeof(uint)) { num = HashHelpers.Combine(num, register.uint32_0.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_1.GetHashCode()); num = HashHelpers.Combine(num, register.uint32_2.GetHashCode()); return HashHelpers.Combine(num, register.uint32_3.GetHashCode()); } if (typeof(T) == typeof(int)) { num = HashHelpers.Combine(num, register.int32_0.GetHashCode()); num = HashHelpers.Combine(num, register.int32_1.GetHashCode()); num = HashHelpers.Combine(num, register.int32_2.GetHashCode()); return HashHelpers.Combine(num, register.int32_3.GetHashCode()); } if (typeof(T) == typeof(ulong)) { num = HashHelpers.Combine(num, register.uint64_0.GetHashCode()); return HashHelpers.Combine(num, register.uint64_1.GetHashCode()); } if (typeof(T) == typeof(long)) { num = HashHelpers.Combine(num, register.int64_0.GetHashCode()); return HashHelpers.Combine(num, register.int64_1.GetHashCode()); } if (typeof(T) == typeof(float)) { num = HashHelpers.Combine(num, register.single_0.GetHashCode()); num = HashHelpers.Combine(num, register.single_1.GetHashCode()); num = HashHelpers.Combine(num, register.single_2.GetHashCode()); return HashHelpers.Combine(num, register.single_3.GetHashCode()); } if (typeof(T) == typeof(double)) { num = HashHelpers.Combine(num, register.double_0.GetHashCode()); return HashHelpers.Combine(num, register.double_1.GetHashCode()); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } public override string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public string ToString(string format) { return ToString(format, CultureInfo.CurrentCulture); } public string ToString(string format, IFormatProvider formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)this[i]).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)this[Count - 1]).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public unsafe static Vector<T>operator +(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarAdd(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarAdd(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarAdd(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarAdd(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarAdd(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarAdd(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarAdd(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarAdd(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarAdd(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarAdd(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 + right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 + right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 + right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 + right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 + right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 + right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 + right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 + right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 + right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 + right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 + right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 + right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 + right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 + right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 + right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 + right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 + right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 + right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 + right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 + right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 + right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 + right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 + right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 + right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 + right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 + right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 + right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 + right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 + right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 + right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 + right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 + right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 + right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 + right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 + right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 + right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 + right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 + right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 + right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 + right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 + right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 + right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 + right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 + right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 + right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 + right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 + right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 + right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 + right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 + right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 + right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 + right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 + right.register.int32_0; result.register.int32_1 = left.register.int32_1 + right.register.int32_1; result.register.int32_2 = left.register.int32_2 + right.register.int32_2; result.register.int32_3 = left.register.int32_3 + right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 + right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 + right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 + right.register.int64_0; result.register.int64_1 = left.register.int64_1 + right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 + right.register.single_0; result.register.single_1 = left.register.single_1 + right.register.single_1; result.register.single_2 = left.register.single_2 + right.register.single_2; result.register.single_3 = left.register.single_3 + right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 + right.register.double_0; result.register.double_1 = left.register.double_1 + right.register.double_1; } return result; } public unsafe static Vector<T>operator -(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarSubtract(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarSubtract(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarSubtract(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarSubtract(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarSubtract(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarSubtract(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarSubtract(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarSubtract(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarSubtract(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarSubtract(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 - right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 - right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 - right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 - right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 - right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 - right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 - right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 - right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 - right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 - right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 - right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 - right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 - right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 - right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 - right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 - right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 - right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 - right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 - right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 - right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 - right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 - right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 - right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 - right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 - right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 - right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 - right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 - right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 - right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 - right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 - right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 - right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 - right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 - right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 - right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 - right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 - right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 - right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 - right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 - right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 - right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 - right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 - right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 - right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 - right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 - right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 - right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 - right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 - right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 - right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 - right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 - right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 - right.register.int32_0; result.register.int32_1 = left.register.int32_1 - right.register.int32_1; result.register.int32_2 = left.register.int32_2 - right.register.int32_2; result.register.int32_3 = left.register.int32_3 - right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 - right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 - right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 - right.register.int64_0; result.register.int64_1 = left.register.int64_1 - right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 - right.register.single_0; result.register.single_1 = left.register.single_1 - right.register.single_1; result.register.single_2 = left.register.single_2 - right.register.single_2; result.register.single_3 = left.register.single_3 - right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 - right.register.double_0; result.register.double_1 = left.register.double_1 - right.register.double_1; } return result; } public unsafe static Vector<T>operator *(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarMultiply(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarMultiply(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarMultiply(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarMultiply(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarMultiply(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarMultiply(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarMultiply(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarMultiply(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarMultiply(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarMultiply(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 * right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 * right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 * right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 * right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 * right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 * right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 * right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 * right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 * right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 * right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 * right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 * right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 * right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 * right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 * right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 * right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 * right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 * right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 * right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 * right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 * right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 * right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 * right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 * right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 * right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 * right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 * right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 * right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 * right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 * right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 * right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 * right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 * right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 * right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 * right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 * right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 * right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 * right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 * right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 * right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 * right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 * right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 * right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 * right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 * right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 * right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 * right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 * right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 * right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 * right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 * right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 * right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 * right.register.int32_0; result.register.int32_1 = left.register.int32_1 * right.register.int32_1; result.register.int32_2 = left.register.int32_2 * right.register.int32_2; result.register.int32_3 = left.register.int32_3 * right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 * right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 * right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 * right.register.int64_0; result.register.int64_1 = left.register.int64_1 * right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 * right.register.single_0; result.register.single_1 = left.register.single_1 * right.register.single_1; result.register.single_2 = left.register.single_2 * right.register.single_2; result.register.single_3 = left.register.single_3 * right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 * right.register.double_0; result.register.double_1 = left.register.double_1 * right.register.double_1; } return result; } public static Vector<T>operator *(Vector<T> value, T factor) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public static Vector<T>operator *(T factor, Vector<T> value) { if (Vector.IsHardwareAccelerated) { return new Vector<T>(factor) * value; } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(value.register.byte_0 * (byte)(object)factor); result.register.byte_1 = (byte)(value.register.byte_1 * (byte)(object)factor); result.register.byte_2 = (byte)(value.register.byte_2 * (byte)(object)factor); result.register.byte_3 = (byte)(value.register.byte_3 * (byte)(object)factor); result.register.byte_4 = (byte)(value.register.byte_4 * (byte)(object)factor); result.register.byte_5 = (byte)(value.register.byte_5 * (byte)(object)factor); result.register.byte_6 = (byte)(value.register.byte_6 * (byte)(object)factor); result.register.byte_7 = (byte)(value.register.byte_7 * (byte)(object)factor); result.register.byte_8 = (byte)(value.register.byte_8 * (byte)(object)factor); result.register.byte_9 = (byte)(value.register.byte_9 * (byte)(object)factor); result.register.byte_10 = (byte)(value.register.byte_10 * (byte)(object)factor); result.register.byte_11 = (byte)(value.register.byte_11 * (byte)(object)factor); result.register.byte_12 = (byte)(value.register.byte_12 * (byte)(object)factor); result.register.byte_13 = (byte)(value.register.byte_13 * (byte)(object)factor); result.register.byte_14 = (byte)(value.register.byte_14 * (byte)(object)factor); result.register.byte_15 = (byte)(value.register.byte_15 * (byte)(object)factor); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(value.register.sbyte_0 * (sbyte)(object)factor); result.register.sbyte_1 = (sbyte)(value.register.sbyte_1 * (sbyte)(object)factor); result.register.sbyte_2 = (sbyte)(value.register.sbyte_2 * (sbyte)(object)factor); result.register.sbyte_3 = (sbyte)(value.register.sbyte_3 * (sbyte)(object)factor); result.register.sbyte_4 = (sbyte)(value.register.sbyte_4 * (sbyte)(object)factor); result.register.sbyte_5 = (sbyte)(value.register.sbyte_5 * (sbyte)(object)factor); result.register.sbyte_6 = (sbyte)(value.register.sbyte_6 * (sbyte)(object)factor); result.register.sbyte_7 = (sbyte)(value.register.sbyte_7 * (sbyte)(object)factor); result.register.sbyte_8 = (sbyte)(value.register.sbyte_8 * (sbyte)(object)factor); result.register.sbyte_9 = (sbyte)(value.register.sbyte_9 * (sbyte)(object)factor); result.register.sbyte_10 = (sbyte)(value.register.sbyte_10 * (sbyte)(object)factor); result.register.sbyte_11 = (sbyte)(value.register.sbyte_11 * (sbyte)(object)factor); result.register.sbyte_12 = (sbyte)(value.register.sbyte_12 * (sbyte)(object)factor); result.register.sbyte_13 = (sbyte)(value.register.sbyte_13 * (sbyte)(object)factor); result.register.sbyte_14 = (sbyte)(value.register.sbyte_14 * (sbyte)(object)factor); result.register.sbyte_15 = (sbyte)(value.register.sbyte_15 * (sbyte)(object)factor); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(value.register.uint16_0 * (ushort)(object)factor); result.register.uint16_1 = (ushort)(value.register.uint16_1 * (ushort)(object)factor); result.register.uint16_2 = (ushort)(value.register.uint16_2 * (ushort)(object)factor); result.register.uint16_3 = (ushort)(value.register.uint16_3 * (ushort)(object)factor); result.register.uint16_4 = (ushort)(value.register.uint16_4 * (ushort)(object)factor); result.register.uint16_5 = (ushort)(value.register.uint16_5 * (ushort)(object)factor); result.register.uint16_6 = (ushort)(value.register.uint16_6 * (ushort)(object)factor); result.register.uint16_7 = (ushort)(value.register.uint16_7 * (ushort)(object)factor); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(value.register.int16_0 * (short)(object)factor); result.register.int16_1 = (short)(value.register.int16_1 * (short)(object)factor); result.register.int16_2 = (short)(value.register.int16_2 * (short)(object)factor); result.register.int16_3 = (short)(value.register.int16_3 * (short)(object)factor); result.register.int16_4 = (short)(value.register.int16_4 * (short)(object)factor); result.register.int16_5 = (short)(value.register.int16_5 * (short)(object)factor); result.register.int16_6 = (short)(value.register.int16_6 * (short)(object)factor); result.register.int16_7 = (short)(value.register.int16_7 * (short)(object)factor); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = value.register.uint32_0 * (uint)(object)factor; result.register.uint32_1 = value.register.uint32_1 * (uint)(object)factor; result.register.uint32_2 = value.register.uint32_2 * (uint)(object)factor; result.register.uint32_3 = value.register.uint32_3 * (uint)(object)factor; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = value.register.int32_0 * (int)(object)factor; result.register.int32_1 = value.register.int32_1 * (int)(object)factor; result.register.int32_2 = value.register.int32_2 * (int)(object)factor; result.register.int32_3 = value.register.int32_3 * (int)(object)factor; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = value.register.uint64_0 * (ulong)(object)factor; result.register.uint64_1 = value.register.uint64_1 * (ulong)(object)factor; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = value.register.int64_0 * (long)(object)factor; result.register.int64_1 = value.register.int64_1 * (long)(object)factor; } else if (typeof(T) == typeof(float)) { result.register.single_0 = value.register.single_0 * (float)(object)factor; result.register.single_1 = value.register.single_1 * (float)(object)factor; result.register.single_2 = value.register.single_2 * (float)(object)factor; result.register.single_3 = value.register.single_3 * (float)(object)factor; } else if (typeof(T) == typeof(double)) { result.register.double_0 = value.register.double_0 * (double)(object)factor; result.register.double_1 = value.register.double_1 * (double)(object)factor; } return result; } public unsafe static Vector<T>operator /(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(object)ScalarDivide(left[i], right[i]); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(object)ScalarDivide(left[j], right[j]); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(object)ScalarDivide(left[k], right[k]); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4 = stackalloc short[Count]; for (int l = 0; l < Count; l++) { ptr4[l] = (short)(object)ScalarDivide(left[l], right[l]); } return new Vector<T>(ptr4); } if (typeof(T) == typeof(uint)) { uint* ptr5 = stackalloc uint[Count]; for (int m = 0; m < Count; m++) { ptr5[m] = (uint)(object)ScalarDivide(left[m], right[m]); } return new Vector<T>(ptr5); } if (typeof(T) == typeof(int)) { int* ptr6 = stackalloc int[Count]; for (int n = 0; n < Count; n++) { ptr6[n] = (int)(object)ScalarDivide(left[n], right[n]); } return new Vector<T>(ptr6); } if (typeof(T) == typeof(ulong)) { ulong* ptr7 = stackalloc ulong[Count]; for (int num = 0; num < Count; num++) { ptr7[num] = (ulong)(object)ScalarDivide(left[num], right[num]); } return new Vector<T>(ptr7); } if (typeof(T) == typeof(long)) { long* ptr8 = stackalloc long[Count]; for (int num2 = 0; num2 < Count; num2++) { ptr8[num2] = (long)(object)ScalarDivide(left[num2], right[num2]); } return new Vector<T>(ptr8); } if (typeof(T) == typeof(float)) { float* ptr9 = stackalloc float[Count]; for (int num3 = 0; num3 < Count; num3++) { ptr9[num3] = (float)(object)ScalarDivide(left[num3], right[num3]); } return new Vector<T>(ptr9); } if (typeof(T) == typeof(double)) { double* ptr10 = stackalloc double[Count]; for (int num4 = 0; num4 < Count; num4++) { ptr10[num4] = (double)(object)ScalarDivide(left[num4], right[num4]); } return new Vector<T>(ptr10); } throw new NotSupportedException(System.SR.Arg_TypeNotSupported); } Vector<T> result = default(Vector<T>); if (typeof(T) == typeof(byte)) { result.register.byte_0 = (byte)(left.register.byte_0 / right.register.byte_0); result.register.byte_1 = (byte)(left.register.byte_1 / right.register.byte_1); result.register.byte_2 = (byte)(left.register.byte_2 / right.register.byte_2); result.register.byte_3 = (byte)(left.register.byte_3 / right.register.byte_3); result.register.byte_4 = (byte)(left.register.byte_4 / right.register.byte_4); result.register.byte_5 = (byte)(left.register.byte_5 / right.register.byte_5); result.register.byte_6 = (byte)(left.register.byte_6 / right.register.byte_6); result.register.byte_7 = (byte)(left.register.byte_7 / right.register.byte_7); result.register.byte_8 = (byte)(left.register.byte_8 / right.register.byte_8); result.register.byte_9 = (byte)(left.register.byte_9 / right.register.byte_9); result.register.byte_10 = (byte)(left.register.byte_10 / right.register.byte_10); result.register.byte_11 = (byte)(left.register.byte_11 / right.register.byte_11); result.register.byte_12 = (byte)(left.register.byte_12 / right.register.byte_12); result.register.byte_13 = (byte)(left.register.byte_13 / right.register.byte_13); result.register.byte_14 = (byte)(left.register.byte_14 / right.register.byte_14); result.register.byte_15 = (byte)(left.register.byte_15 / right.register.byte_15); } else if (typeof(T) == typeof(sbyte)) { result.register.sbyte_0 = (sbyte)(left.register.sbyte_0 / right.register.sbyte_0); result.register.sbyte_1 = (sbyte)(left.register.sbyte_1 / right.register.sbyte_1); result.register.sbyte_2 = (sbyte)(left.register.sbyte_2 / right.register.sbyte_2); result.register.sbyte_3 = (sbyte)(left.register.sbyte_3 / right.register.sbyte_3); result.register.sbyte_4 = (sbyte)(left.register.sbyte_4 / right.register.sbyte_4); result.register.sbyte_5 = (sbyte)(left.register.sbyte_5 / right.register.sbyte_5); result.register.sbyte_6 = (sbyte)(left.register.sbyte_6 / right.register.sbyte_6); result.register.sbyte_7 = (sbyte)(left.register.sbyte_7 / right.register.sbyte_7); result.register.sbyte_8 = (sbyte)(left.register.sbyte_8 / right.register.sbyte_8); result.register.sbyte_9 = (sbyte)(left.register.sbyte_9 / right.register.sbyte_9); result.register.sbyte_10 = (sbyte)(left.register.sbyte_10 / right.register.sbyte_10); result.register.sbyte_11 = (sbyte)(left.register.sbyte_11 / right.register.sbyte_11); result.register.sbyte_12 = (sbyte)(left.register.sbyte_12 / right.register.sbyte_12); result.register.sbyte_13 = (sbyte)(left.register.sbyte_13 / right.register.sbyte_13); result.register.sbyte_14 = (sbyte)(left.register.sbyte_14 / right.register.sbyte_14); result.register.sbyte_15 = (sbyte)(left.register.sbyte_15 / right.register.sbyte_15); } else if (typeof(T) == typeof(ushort)) { result.register.uint16_0 = (ushort)(left.register.uint16_0 / right.register.uint16_0); result.register.uint16_1 = (ushort)(left.register.uint16_1 / right.register.uint16_1); result.register.uint16_2 = (ushort)(left.register.uint16_2 / right.register.uint16_2); result.register.uint16_3 = (ushort)(left.register.uint16_3 / right.register.uint16_3); result.register.uint16_4 = (ushort)(left.register.uint16_4 / right.register.uint16_4); result.register.uint16_5 = (ushort)(left.register.uint16_5 / right.register.uint16_5); result.register.uint16_6 = (ushort)(left.register.uint16_6 / right.register.uint16_6); result.register.uint16_7 = (ushort)(left.register.uint16_7 / right.register.uint16_7); } else if (typeof(T) == typeof(short)) { result.register.int16_0 = (short)(left.register.int16_0 / right.register.int16_0); result.register.int16_1 = (short)(left.register.int16_1 / right.register.int16_1); result.register.int16_2 = (short)(left.register.int16_2 / right.register.int16_2); result.register.int16_3 = (short)(left.register.int16_3 / right.register.int16_3); result.register.int16_4 = (short)(left.register.int16_4 / right.register.int16_4); result.register.int16_5 = (short)(left.register.int16_5 / right.register.int16_5); result.register.int16_6 = (short)(left.register.int16_6 / right.register.int16_6); result.register.int16_7 = (short)(left.register.int16_7 / right.register.int16_7); } else if (typeof(T) == typeof(uint)) { result.register.uint32_0 = left.register.uint32_0 / right.register.uint32_0; result.register.uint32_1 = left.register.uint32_1 / right.register.uint32_1; result.register.uint32_2 = left.register.uint32_2 / right.register.uint32_2; result.register.uint32_3 = left.register.uint32_3 / right.register.uint32_3; } else if (typeof(T) == typeof(int)) { result.register.int32_0 = left.register.int32_0 / right.register.int32_0; result.register.int32_1 = left.register.int32_1 / right.register.int32_1; result.register.int32_2 = left.register.int32_2 / right.register.int32_2; result.register.int32_3 = left.register.int32_3 / right.register.int32_3; } else if (typeof(T) == typeof(ulong)) { result.register.uint64_0 = left.register.uint64_0 / right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 / right.register.uint64_1; } else if (typeof(T) == typeof(long)) { result.register.int64_0 = left.register.int64_0 / right.register.int64_0; result.register.int64_1 = left.register.int64_1 / right.register.int64_1; } else if (typeof(T) == typeof(float)) { result.register.single_0 = left.register.single_0 / right.register.single_0; result.register.single_1 = left.register.single_1 / right.register.single_1; result.register.single_2 = left.register.single_2 / right.register.single_2; result.register.single_3 = left.register.single_3 / right.register.single_3; } else if (typeof(T) == typeof(double)) { result.register.double_0 = left.register.double_0 / right.register.double_0; result.register.double_1 = left.register.double_1 / right.register.double_1; } return result; } public static Vector<T>operator -(Vector<T> value) { return Zero - value; } [JitIntrinsic] public unsafe static Vector<T>operator &(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] & ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 & right.register.int64_0; result.register.int64_1 = left.register.int64_1 & right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator |(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] | ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 | right.register.int64_0; result.register.int64_1 = left.register.int64_1 | right.register.int64_1; } return result; } [JitIntrinsic] public unsafe static Vector<T>operator ^(Vector<T> left, Vector<T> right) { Vector<T> result = default(Vector<T>); if (Vector.IsHardwareAccelerated) { long* ptr = &result.register.int64_0; long* ptr2 = &left.register.int64_0; long* ptr3 = &right.register.int64_0; for (int i = 0; i < Vector<long>.Count; i++) { ptr[i] = ptr2[i] ^ ptr3[i]; } } else { result.register.int64_0 = left.register.int64_0 ^ right.register.int64_0; result.register.int64_1 = left.register.int64_1 ^ right.register.int64_1; } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector<T>operator ~(Vector<T> value) { return allOnes ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector<T> left, Vector<T> right) { return left.Equals(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector<T> left, Vector<T> right) { return !(left == right); } [JitIntrinsic] public static explicit operator Vector<byte>(Vector<T> value) { return new Vector<byte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<sbyte>(Vector<T> value) { return new Vector<sbyte>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ushort>(Vector<T> value) { return new Vector<ushort>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<short>(Vector<T> value) { return new Vector<short>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<uint>(Vector<T> value) { return new Vector<uint>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<int>(Vector<T> value) { return new Vector<int>(ref value.register); } [CLSCompliant(false)] [JitIntrinsic] public static explicit operator Vector<ulong>(Vector<T> value) { return new Vector<ulong>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<long>(Vector<T> value) { return new Vector<long>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<float>(Vector<T> value) { return new Vector<float>(ref value.register); } [JitIntrinsic] public static explicit operator Vector<double>(Vector<T> value) { return new Vector<double>(ref value.register); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [JitIntrinsic] internal unsafe static Vector<T> Equals(Vector<T> left, Vector<T> right) { if (Vector.IsHardwareAccelerated) { if (typeof(T) == typeof(byte)) { byte* ptr = stackalloc byte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int i = 0; i < Count; i++) { ptr[i] = (byte)(ScalarEquals(left[i], right[i]) ? ConstantHelper.GetByteWithAllBitsSet() : 0); } return new Vector<T>(ptr); } if (typeof(T) == typeof(sbyte)) { sbyte* ptr2 = stackalloc sbyte[(int)checked(unchecked((nuint)(uint)Count) * (nuint)1u)]; for (int j = 0; j < Count; j++) { ptr2[j] = (sbyte)(ScalarEquals(left[j], right[j]) ? ConstantHelper.GetSByteWithAllBitsSet() : 0); } return new Vector<T>(ptr2); } if (typeof(T) == typeof(ushort)) { ushort* ptr3 = stackalloc ushort[Count]; for (int k = 0; k < Count; k++) { ptr3[k] = (ushort)(ScalarEquals(left[k], right[k]) ? ConstantHelper.GetUInt16WithAllBitsSet() : 0); } return new Vector<T>(ptr3); } if (typeof(T) == typeof(short)) { short* ptr4