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 TimeDilation v1.1.0
TimeDilation.dll
Decompiled 4 hours agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Unity.Collections; using Unity.Netcode; 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("TimeDilation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("1.1.0")] [assembly: AssemblyProduct("TimeDilation")] [assembly: AssemblyTitle("TimeDilation")] [assembly: AssemblyMetadata("AI_Assisted_Creation", "Code generated with Anthropic Claude (Claude Opus 5.5 and other Claude models, via Claude Code); designed and tested by the author")] [assembly: AssemblyMetadata("AI_Model_Vendor", "Anthropic")] [assembly: AssemblyVersion("1.1.0.0")] namespace TimeDilation; internal sealed class ClientDay { public bool HasOpen; public DayKey Open; public bool Applied; public bool HasClosed; public DayKey Closed; public DayMessage Pending; public bool HostAnswered; public int Requests; public float OpenedAt; public bool OpenDay(DayKey k, float now) { if (HasOpen && Open.Equals(k)) { return false; } HasOpen = true; Open = k; Applied = false; Requests = 0; OpenedAt = now; return true; } public void CloseDay() { if (HasOpen) { HasClosed = true; Closed = Open; } HasOpen = false; Applied = false; Requests = 0; } public bool ShouldOpenLate(DayKey k) { if (HasOpen) { return false; } if (HasClosed) { return !Closed.Equals(k); } return true; } public bool Receive(DayMessage m) { HostAnswered = true; if (m == null || !m.Active) { return false; } if (Pending != null && Pending.Key.Equals(m.Key) && HasOpen && Applied && Open.Equals(m.Key)) { return false; } Pending = m; return Ready(); } public bool Ready() { if (HasOpen && !Applied && Pending != null) { return Pending.Key.Equals(Open); } return false; } public DayMessage Take() { if (!Ready()) { return null; } Applied = true; return Pending; } public bool ShouldRequest(float now) { if (!HasOpen || Applied || Requests >= 3) { return false; } return now - OpenedAt >= 4f * (float)(Requests + 1); } public bool HostSilent(float now) { if (HasOpen && !HostAnswered) { return now - OpenedAt >= 10f; } return false; } public void Reset() { HasOpen = false; Applied = false; HasClosed = false; Pending = null; HostAnswered = false; Requests = 0; OpenedAt = 0f; } } public static class DilationState { public static int Kind; public static int DayPercent; public static float Speed = 1f; public static string Planet; public static string Lore; } internal static class Dilation { private static TimeOfDay _appliedTo; private static float _applied = 1f; internal static bool RevealPending; private static readonly string[] SlowLore = new string[3] { "Close orbital pass with the parent giant. Local time is running slow.", "Deep in the star's gravity well. Local clocks are dragging.", "Strong gravitational field on this pass. Local time is running slow." }; private static readonly string[] FastLore = new string[2] { "Moon is at apoapsis, far from its parent. Local time is running fast.", "Weak gravity field out here. Local clocks are running ahead." }; private static MethodInfo _chat; internal static DayMessage HostDay = new DayMessage(); internal static bool Dilated { get { if (_applied != 1f && (Object)(object)_appliedTo != (Object)null) { return (Object)(object)_appliedTo == (Object)(object)TimeOfDay.Instance; } return false; } } internal static bool IsCompany(SelectableLevel l) { if ((Object)(object)l != (Object)null) { if (l.levelID != 3) { return string.Equals(l.sceneName, "CompanyBuilding", StringComparison.OrdinalIgnoreCase); } return true; } return false; } private static bool IsExcluded(SelectableLevel l) { if (IsCompany(l)) { return true; } string value = Plugin.Excluded.Value; if (string.IsNullOrWhiteSpace(value)) { return false; } string text = l.PlanetName ?? ""; string[] array = value.Split(','); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.Length != 0 && (text.Equals(text2, StringComparison.OrdinalIgnoreCase) || text.EndsWith(" " + text2, StringComparison.OrdinalIgnoreCase))) { return true; } } return false; } internal static void ResetDay() { Undo(); DilationState.Kind = 0; DilationState.DayPercent = 0; DilationState.Speed = 1f; DilationState.Lore = null; DilationState.Planet = null; RevealPending = false; } internal static void Roll() { ResetDay(); StartOfRound instance = StartOfRound.Instance; TimeOfDay instance2 = TimeOfDay.Instance; SelectableLevel val = (((Object)(object)instance != (Object)null) ? instance.currentLevel : null); DayMessage dayMessage = (HostDay = new DayMessage { Active = true, Seed = (((Object)(object)instance != (Object)null) ? instance.randomMapSeed : 0), LevelId = (((Object)(object)val != (Object)null) ? val.levelID : (-1)) }); if (!Plugin.Enabled.Value || (Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || (Object)(object)val == (Object)null) { return; } DilationState.Planet = val.PlanetName; dayMessage.HasPlanet = true; if (IsExcluded(val) || !val.planetHasTime) { Plugin.Log.LogInfo((object)("Normal day on " + val.PlanetName + " (excluded or no day clock)")); return; } RollConfig c = new RollConfig { SlowChance = Plugin.SlowChance.Value, FastChance = Plugin.FastChance.Value, SlowMin = Plugin.SlowMin.Value, SlowMax = Plugin.SlowMax.Value, FastMin = Plugin.FastMin.Value, FastMax = Plugin.FastMax.Value }; RollResult rollResult = RollMath.Roll(instance.randomMapSeed, val.levelID, c, SlowLore.Length, FastLore.Length); if (rollResult.Kind == 0) { Plugin.Log.LogInfo((object)("Normal day on " + val.PlanetName)); return; } string lore = ((rollResult.Kind == 1) ? SlowLore[rollResult.LoreIndex] : FastLore[rollResult.LoreIndex]); dayMessage.Kind = rollResult.Kind; dayMessage.DayPercent = rollResult.DayPercent; dayMessage.Speed = rollResult.Speed; dayMessage.Lore = lore; Apply(instance2, rollResult.Kind, rollResult.DayPercent, rollResult.Speed, lore); Plugin.Log.LogInfo((object)(((DilationState.Kind == 1) ? "Long" : "Short") + " day on " + val.PlanetName + ": " + DilationState.DayPercent + "% " + ((DilationState.Kind == 1) ? "longer" : "shorter") + " (time speed x" + DilationState.Speed.ToString("0.###") + ", now " + instance2.globalTimeSpeedMultiplier.ToString("0.###") + ")")); } private static void Apply(TimeOfDay tod, int kind, int dayPercent, float speed, string lore) { DilationState.Kind = kind; DilationState.DayPercent = dayPercent; DilationState.Speed = speed; DilationState.Lore = lore; tod.globalTimeSpeedMultiplier *= speed; _appliedTo = tod; _applied = speed; RevealPending = Plugin.ShowInGame.Value; } internal static bool ApplyFromHost(DayMessage m) { StartOfRound instance = StartOfRound.Instance; TimeOfDay instance2 = TimeOfDay.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null) { return false; } ResetDay(); SelectableLevel currentLevel = instance.currentLevel; if (m.HasPlanet) { DilationState.Planet = (((Object)(object)currentLevel != (Object)null) ? currentLevel.PlanetName : null); } if (m.Kind != 0) { Apply(instance2, m.Kind, m.DayPercent, m.Speed, m.Lore); } string text = (((Object)(object)currentLevel != (Object)null) ? currentLevel.PlanetName : ("level " + m.LevelId)); if (m.Kind == 0) { Plugin.Log.LogInfo((object)("Normal day on " + text + " (host's roll)")); } else { Plugin.Log.LogInfo((object)(((m.Kind == 1) ? "Long" : "Short") + " day on " + text + " (host's roll): " + m.DayPercent + "% " + ((m.Kind == 1) ? "longer" : "shorter") + " (time speed x" + m.Speed.ToString("0.###") + ", now " + instance2.globalTimeSpeedMultiplier.ToString("0.###") + ")")); } return true; } internal static string Mult(float speed) { return speed.ToString("0.###", CultureInfo.InvariantCulture); } internal static void Undo() { RevealPending = false; if (_applied == 1f) { return; } try { if ((Object)(object)_appliedTo != (Object)null && (Object)(object)_appliedTo == (Object)(object)TimeOfDay.Instance) { TimeOfDay appliedTo = _appliedTo; appliedTo.globalTimeSpeedMultiplier /= _applied; } } catch { } _appliedTo = null; _applied = 1f; } internal static void DayEnded() { Undo(); DilationState.Kind = 0; DilationState.DayPercent = 0; DilationState.Speed = 1f; DilationState.Lore = null; DilationState.Planet = null; HostDay = new DayMessage(); } internal static void Reveal() { RevealPending = false; if (DilationState.Kind == 0 || DilationState.Lore == null) { return; } string text = "<color=#8fd3ff>" + DilationState.Lore + " The day is about " + DilationState.DayPercent + "% " + ((DilationState.Kind == 1) ? "longer" : "shorter") + ".</color>"; try { HUDManager instance = HUDManager.Instance; if (!((Object)(object)instance == (Object)null)) { if (_chat == null) { _chat = AccessTools.Method(typeof(HUDManager), "AddChatMessage", (Type[])null, (Type[])null); } _chat.Invoke(instance, new object[4] { text, "", -1, false }); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("Couldn't show the time dilation line in chat: " + ex.Message)); } } } internal static class Net { internal const string DayMsg = "jacob.timedilation.day"; internal const string HelloMsg = "jacob.timedilation.hello"; private static CustomMessagingManager _registeredOn; private static bool _helloSent; private static int _bad; private static bool _warnedProtocol; internal static readonly HashSet<ulong> Modded = new HashSet<ulong>(); internal static readonly ClientDay Client = new ClientDay(); internal static bool IsClientOnly { get { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null && singleton.IsListening) { return !singleton.IsServer; } return false; } } internal static bool IsHost { get { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null && singleton.IsListening) { return singleton.IsServer; } return false; } } internal static void EnsureRegistered() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsListening && singleton.CustomMessagingManager != null) { if (_registeredOn != singleton.CustomMessagingManager) { _registeredOn = singleton.CustomMessagingManager; _registeredOn.RegisterNamedMessageHandler("jacob.timedilation.day", new HandleNamedMessageDelegate(OnDay)); _registeredOn.RegisterNamedMessageHandler("jacob.timedilation.hello", new HandleNamedMessageDelegate(OnHello)); _helloSent = false; Modded.Clear(); Client.Reset(); } if (!_helloSent && !singleton.IsServer && singleton.IsConnectedClient) { _helloSent = true; SendHello(); } } } internal static void SendHello() { try { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsListening && !singleton.IsServer && singleton.IsConnectedClient && singleton.CustomMessagingManager != null) { Send(singleton, "jacob.timedilation.hello", 0uL, Wire.EncodeHello("1.1.0")); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("TimeDilation: couldn't ask the host for the day: " + ex.Message)); } } private static void OnDay(ulong sender, FastBufferReader reader) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) try { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && !singleton.IsServer && sender == 0L) { if (!ReadBlob(reader, out var data)) { Bad("bad length"); } else { HandleDay(data); } } } catch (Exception ex) { Bad(ex.GetType().Name); } } internal static bool HandleDay(byte[] data) { if (!Wire.TryDecodeDay(data, out var m, out var error)) { if (error != null && error.StartsWith("protocol")) { Client.HostAnswered = true; if (!_warnedProtocol) { _warnedProtocol = true; Plugin.Log.LogWarning((object)("TimeDilation: the host runs a different TimeDilation version (" + error + "); keeping the normal day speed here. Use the same version on both PCs.")); } return false; } Bad(error); return false; } if (!Client.Receive(m)) { return false; } Hooks.ApplyPendingFromHost(); return Client.Applied; } private static void Bad(string why) { _bad++; if (_bad <= 3) { Plugin.Log.LogWarning((object)("TimeDilation: dropped a malformed day message from the host (" + why + ")")); } } private static void OnHello(ulong sender, FastBufferReader reader) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) try { NetworkManager singleton = NetworkManager.Singleton; if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && sender != 0L && ReadBlob(reader, out var data) && HandleHello(sender, data)) { SendDay(singleton, sender); } } catch (Exception ex) { Plugin.Log.LogWarning((object)("TimeDilation: hello from client " + sender + " failed: " + ex.Message)); } } internal static bool HandleHello(ulong sender, byte[] data) { if (!Wire.TryDecodeHello(data, out var _, out var modVersion)) { return false; } if (Modded.Add(sender)) { Plugin.Log.LogInfo((object)("TimeDilation: client " + sender + " has TimeDilation " + modVersion + "; it gets the host's day")); } return true; } internal static byte[] DayPayload() { return Wire.EncodeDay(Dilation.HostDay); } internal static void BroadcastDay() { try { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening || !singleton.IsServer || singleton.CustomMessagingManager == null) { return; } EnsureRegistered(); IReadOnlyList<ulong> connectedClientsIds = singleton.ConnectedClientsIds; for (int i = 0; i < connectedClientsIds.Count; i++) { if (connectedClientsIds[i] != 0L) { SendDay(singleton, connectedClientsIds[i]); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("TimeDilation: couldn't send the day to clients: " + ex.Message)); } } private static void SendDay(NetworkManager nm, ulong clientId) { Send(nm, "jacob.timedilation.day", clientId, DayPayload()); } internal static bool AnyClientWithoutMod() { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening || !singleton.IsServer) { return false; } IReadOnlyList<ulong> ids = singleton.ConnectedClientsIds; bool result = false; for (int i = 0; i < ids.Count; i++) { if (ids[i] != 0L && !Modded.Contains(ids[i])) { result = true; } } if (Modded.Count > 0) { Modded.RemoveWhere((ulong id) => !Contains(ids, id)); } return result; } private static bool Contains(IReadOnlyList<ulong> ids, ulong id) { for (int i = 0; i < ids.Count; i++) { if (ids[i] == id) { return true; } } return false; } private unsafe static void Send(NetworkManager nm, string name, ulong clientId, byte[] payload) { //IL_0018: 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_0038: Unknown result type (might be due to invalid IL or missing references) FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(payload.Length + 8, (Allocator)2, -1); try { int num = payload.Length; ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteBytesSafe(payload, payload.Length, 0); nm.CustomMessagingManager.SendNamedMessage(name, clientId, val, (NetworkDelivery)4); } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } } private static bool ReadBlob(FastBufferReader reader, out byte[] data) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) data = null; int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); if (num < 1 || num > 1024) { return false; } data = new byte[num]; ((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0); return true; } } [BepInPlugin("jacob.timedilation", "TimeDilation", "1.1.0")] public class Plugin : BaseUnityPlugin { public const string Guid = "jacob.timedilation"; public const string Name = "TimeDilation"; public const string Version = "1.1.0"; internal static ManualLogSource Log; internal static ConfigEntry<bool> Enabled; internal static ConfigEntry<bool> ShowInGame; internal static ConfigEntry<int> SlowChance; internal static ConfigEntry<int> FastChance; internal static ConfigEntry<int> SlowMin; internal static ConfigEntry<int> SlowMax; internal static ConfigEntry<int> FastMin; internal static ConfigEntry<int> FastMax; internal static ConfigEntry<string> Excluded; internal static ConfigEntry<bool> ResyncClock; private const string HostOnly = " Only the host's setting matters: the host rolls the day and sends it to everyone."; private void Awake() { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Expected O, but got Unknown //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Expected O, but got Unknown //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Expected O, but got Unknown //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Roll a longer or shorter day on landings. Only the host's setting matters: the host rolls the day and sends it to everyone. Clients follow the host whatever this says."); Excluded = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExcludedMoons", "", "Comma-separated moon names that always have a normal day, e.g. \"Vow, March\". The Company is always excluded. Only the host's setting matters: the host rolls the day and sends it to everyone."); SlowChance = ((BaseUnityPlugin)this).Config.Bind<int>("Odds", "LongDayChance", 15, new ConfigDescription("Percent of landings with a longer day (time running slow). Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); FastChance = ((BaseUnityPlugin)this).Config.Bind<int>("Odds", "ShortDayChance", 5, new ConfigDescription("Percent of landings with a shorter day (time running fast). Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); SlowMin = ((BaseUnityPlugin)this).Config.Bind<int>("Range", "LongDayMinPercent", 10, new ConfigDescription("Smallest increase in day length on a long day. Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 200), Array.Empty<object>())); SlowMax = ((BaseUnityPlugin)this).Config.Bind<int>("Range", "LongDayMaxPercent", 35, new ConfigDescription("Largest increase in day length on a long day. Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 200), Array.Empty<object>())); FastMin = ((BaseUnityPlugin)this).Config.Bind<int>("Range", "ShortDayMinPercent", 10, new ConfigDescription("Smallest cut in day length on a short day. Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 80), Array.Empty<object>())); FastMax = ((BaseUnityPlugin)this).Config.Bind<int>("Range", "ShortDayMaxPercent", 30, new ConfigDescription("Largest cut in day length on a short day. Only the host's setting matters: the host rolls the day and sends it to everyone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 80), Array.Empty<object>())); ShowInGame = ((BaseUnityPlugin)this).Config.Bind<bool>("Reveal", "ShowInGame", true, "After landing on a long or short day, show one line in your chat with the reason (only on your screen). Off: nothing in game says so, but PerfWatcher's Day Info panel (I) still shows it. Each player's own setting."); ResyncClock = ((BaseUnityPlugin)this).Config.Bind<bool>("Network", "ResyncClockForPlayersWithoutMod", true, "Host only. On a long or short day, if a connected player doesn't have TimeDilation 1.1 or newer, resend the game clock to everyone every " + 2f + " seconds so their clock stays within about a minute of yours instead of drifting and snapping back. Does nothing when every player has the mod."); Harmony h = new Harmony("jacob.timedilation"); Patch(h, AccessTools.Method(typeof(RoundManager), "GenerateNewFloor", (Type[])null, (Type[])null), "BeforeGenerate"); Patch(h, AccessTools.Method(typeof(StartOfRound), "EndOfGame", (Type[])null, (Type[])null), "DayEnded"); Patch(h, AccessTools.Method(typeof(StartOfRound), "OnDestroy", (Type[])null, (Type[])null), "DayEnded"); GameObject val = new GameObject("TimeDilationRunner") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); val.AddComponent<Runner>(); ((BaseUnityPlugin)this).Logger.LogInfo((object)("TimeDilation 1.1.0 loaded (host-driven). Long day " + SlowChance.Value + "% (" + SlowMin.Value + "–" + SlowMax.Value + "% longer), short day " + FastChance.Value + "% (" + FastMin.Value + "–" + FastMax.Value + "% shorter), ShowInGame=" + ShowInGame.Value + ", ResyncClockForPlayersWithoutMod=" + ResyncClock.Value + ". Odds and ranges are used only when this PC hosts.")); } private void Patch(Harmony h, MethodInfo target, string prefix) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown if (target == null) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Hook target missing (" + prefix + ")")); return; } try { h.Patch((MethodBase)target, new HarmonyMethod(typeof(Hooks), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Couldn't hook " + target.DeclaringType?.ToString() + "." + target.Name + ": " + ex.Message)); } } } internal static class Hooks { internal static void BeforeGenerate() { try { if (Net.IsClientOnly) { ClientGenerate(); return; } Dilation.Roll(); Plugin.Log.LogInfo((object)("TimeDilation: day x" + Dilation.Mult(Dilation.HostDay.Speed) + " (host)")); ClockAssist.NewDay(); Net.BroadcastDay(); } catch (Exception ex) { Plugin.Log.LogError((object)("Roll failed: " + ex)); } } private static void ClientGenerate() { Net.EnsureRegistered(); StartOfRound instance = StartOfRound.Instance; ClientOpen(new DayKey(((Object)(object)instance != (Object)null) ? instance.randomMapSeed : 0, ((Object)(object)instance != (Object)null && (Object)(object)instance.currentLevel != (Object)null) ? instance.currentLevel.levelID : (-1)), Time.realtimeSinceStartup); } internal static void ClientOpen(DayKey key, float now) { if (Net.Client.OpenDay(key, now)) { Dilation.ResetDay(); } ApplyPendingFromHost(); } internal static bool ClientLateOpen(DayKey key, float now) { if (!Net.Client.ShouldOpenLate(key)) { return false; } Net.Client.OpenDay(key, now); Dilation.ResetDay(); Plugin.Log.LogInfo((object)"TimeDilation: joined during a landing; asking the host for the day"); return true; } internal static void ApplyPendingFromHost() { if (Net.Client.Ready()) { DayMessage pending = Net.Client.Pending; if (Dilation.ApplyFromHost(pending)) { Net.Client.Take(); Plugin.Log.LogInfo((object)("TimeDilation: day x" + Dilation.Mult(pending.Speed) + " (from host)")); } } } internal static void DayEnded() { try { Dilation.DayEnded(); Net.Client.CloseDay(); } catch { } } } internal static class ClockAssist { internal const float Interval = 2f; private static float _next; private static bool _loggedToday; private static bool _failed; internal static void NewDay() { _loggedToday = false; _next = 0f; } internal static void Tick() { if (_failed || !Plugin.ResyncClock.Value || !Dilation.Dilated) { return; } StartOfRound instance = StartOfRound.Instance; TimeOfDay instance2 = TimeOfDay.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null || instance.inShipPhase || !instance2.currentDayTimeStarted || !Net.AnyClientWithoutMod()) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (realtimeSinceStartup < _next) { return; } _next = realtimeSinceStartup + 2f; float timeUntilDeadline = instance2.timeUntilDeadline; try { instance2.SyncTimeClientRpc(instance2.globalTime, (int)instance2.timeUntilDeadline); } catch (Exception ex) { _failed = true; Plugin.Log.LogWarning((object)("TimeDilation: couldn't resend the clock (turned off until restart): " + ex.Message)); } finally { instance2.timeUntilDeadline = timeUntilDeadline; } if (!_loggedToday) { _loggedToday = true; Plugin.Log.LogInfo((object)("TimeDilation: a player without TimeDilation 1.1+ is connected; resending the clock every " + 2f + " s today so theirs keeps up")); } } } internal sealed class Runner : MonoBehaviour { private float _landedAt = -1f; private float _nextTick; private int _errors; private bool _warnedSilent; private DayKey _warnedNoDay; private bool _hasWarnedNoDay; private void Update() { Reveal(); if (_errors >= 10 || Time.unscaledTime < _nextTick) { return; } _nextTick = Time.unscaledTime + 0.25f; try { Tick(); } catch (Exception ex) { _errors++; Plugin.Log.LogWarning((object)("TimeDilation runner error " + _errors + "/10: " + ex.Message)); } } private void Reveal() { if (!Dilation.RevealPending) { _landedAt = -1f; return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || instance.inShipPhase) { Dilation.RevealPending = false; } else if (instance.shipHasLanded) { if (_landedAt < 0f) { _landedAt = Time.realtimeSinceStartup; } if (Time.realtimeSinceStartup - _landedAt >= 3f) { Dilation.Reveal(); _landedAt = -1f; } } } private void Tick() { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsListening) { _warnedSilent = false; return; } Net.EnsureRegistered(); if (singleton.IsServer) { ClockAssist.Tick(); } else { ClientTick(); } } private void ClientTick() { ClientDay client = Net.Client; StartOfRound instance = StartOfRound.Instance; TimeOfDay instance2 = TimeOfDay.Instance; float realtimeSinceStartup = Time.realtimeSinceStartup; if ((Object)(object)instance != (Object)null && (Object)(object)instance2 != (Object)null && (Object)(object)instance.currentLevel != (Object)null && !instance.inShipPhase && instance.shipHasLanded && instance2.currentDayTimeStarted && Hooks.ClientLateOpen(new DayKey(instance.randomMapSeed, instance.currentLevel.levelID), realtimeSinceStartup) && !client.Ready()) { Net.SendHello(); } if (client.Ready()) { Hooks.ApplyPendingFromHost(); } if (client.ShouldRequest(realtimeSinceStartup)) { client.Requests++; Net.SendHello(); } if (!_warnedSilent && client.HostSilent(realtimeSinceStartup)) { _warnedSilent = true; Plugin.Log.LogWarning((object)"TimeDilation: no day info from the host. The host doesn't run TimeDilation 1.1 or newer, so this PC keeps the normal day speed (the host's mod decides the day)."); } else if (client.HostAnswered && client.HasOpen && !client.Applied && client.Requests >= 3 && realtimeSinceStartup - client.OpenedAt >= 16f && (!_hasWarnedNoDay || !_warnedNoDay.Equals(client.Open))) { _hasWarnedNoDay = true; _warnedNoDay = client.Open; ManualLogSource log = Plugin.Log; DayKey open = client.Open; log.LogWarning((object)("TimeDilation: the host didn't send the day for this landing (" + open.ToString() + "); keeping the normal day speed.")); } } } internal struct RollConfig { public int SlowChance; public int FastChance; public int SlowMin; public int SlowMax; public int FastMin; public int FastMax; } internal struct RollResult { public int Kind; public int DayPercent; public float Speed; public int LoreIndex; } internal static class RollMath { internal static int Seed(int randomMapSeed, int levelId) { return randomMapSeed * 31 + levelId * 7919 + 1301; } internal static RollResult Roll(int randomMapSeed, int levelId, RollConfig c, int slowLoreCount, int fastLoreCount) { RollResult result = new RollResult { Kind = 0, DayPercent = 0, Speed = 1f, LoreIndex = -1 }; Random random = new Random(Seed(randomMapSeed, levelId)); double num = random.NextDouble() * 100.0; int num2 = Clamp(c.FastChance, 0, 100); int num3 = Clamp(c.SlowChance, 0, 100 - num2); if (num < (double)num2) { int num4 = Math.Min(c.FastMin, c.FastMax); int num5 = Math.Max(c.FastMin, c.FastMax); int value = num4 + (int)Math.Round(random.NextDouble() * (double)(num5 - num4)); value = Clamp(value, 1, 80); result.Kind = 2; result.DayPercent = value; result.Speed = 1f / (1f - (float)value / 100f); result.LoreIndex = random.Next(fastLoreCount); } else if (num < (double)(num2 + num3)) { int num6 = Math.Min(c.SlowMin, c.SlowMax); int num7 = Math.Max(c.SlowMin, c.SlowMax); int value2 = num6 + (int)Math.Round(random.NextDouble() * (double)(num7 - num6)); value2 = Clamp(value2, 1, 200); result.Kind = 1; result.DayPercent = value2; result.Speed = 1f / (1f + (float)value2 / 100f); result.LoreIndex = random.Next(slowLoreCount); } return result; } internal static int Clamp(int value, int min, int max) { if (value < min) { value = min; } else if (value > max) { value = max; } return value; } } internal struct DayKey : IEquatable<DayKey> { public readonly int Seed; public readonly int LevelId; public DayKey(int seed, int levelId) { Seed = seed; LevelId = levelId; } public bool Equals(DayKey o) { if (Seed == o.Seed) { return LevelId == o.LevelId; } return false; } public override bool Equals(object o) { if (o is DayKey) { return Equals((DayKey)o); } return false; } public override int GetHashCode() { return (Seed * 397) ^ LevelId; } public override string ToString() { return "seed " + Seed + ", level " + LevelId; } } internal sealed class DayMessage { public bool Active; public int Seed; public int LevelId; public bool HasPlanet; public int Kind; public int DayPercent; public float Speed = 1f; public string Lore; public DayKey Key => new DayKey(Seed, LevelId); public DayMessage Clone() { return (DayMessage)MemberwiseClone(); } } internal static class Wire { internal const byte Protocol = 1; internal const int MaxLore = 300; internal const int MaxBlob = 1024; internal static byte[] EncodeDay(DayMessage m) { using MemoryStream memoryStream = new MemoryStream(64); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8); binaryWriter.Write((byte)1); binaryWriter.Write(m.Active); binaryWriter.Write(m.Seed); binaryWriter.Write(m.LevelId); binaryWriter.Write(m.HasPlanet); binaryWriter.Write((byte)m.Kind); binaryWriter.Write((short)m.DayPercent); binaryWriter.Write(m.Speed); string text = m.Lore ?? ""; if (text.Length > 300) { text = text.Substring(0, 300); } binaryWriter.Write(text); binaryWriter.Flush(); return memoryStream.ToArray(); } internal static bool TryDecodeDay(byte[] data, out DayMessage m, out string error) { m = null; error = null; if (data == null || data.Length < 1) { error = "empty"; return false; } if (data.Length > 1024) { error = "too long"; return false; } if (data[0] != 1) { error = "protocol " + data[0]; return false; } try { using MemoryStream input = new MemoryStream(data, writable: false); using BinaryReader binaryReader = new BinaryReader(input, Encoding.UTF8); binaryReader.ReadByte(); DayMessage dayMessage = new DayMessage(); dayMessage.Active = binaryReader.ReadBoolean(); dayMessage.Seed = binaryReader.ReadInt32(); dayMessage.LevelId = binaryReader.ReadInt32(); dayMessage.HasPlanet = binaryReader.ReadBoolean(); dayMessage.Kind = binaryReader.ReadByte(); dayMessage.DayPercent = binaryReader.ReadInt16(); dayMessage.Speed = binaryReader.ReadSingle(); string text = binaryReader.ReadString(); dayMessage.Lore = ((text.Length == 0) ? null : ((text.Length > 300) ? text.Substring(0, 300) : text)); if (!Valid(dayMessage, out error)) { return false; } m = dayMessage; return true; } catch (EndOfStreamException) { error = "truncated"; return false; } catch (Exception ex2) { error = ex2.GetType().Name; return false; } } internal static bool Valid(DayMessage d, out string error) { error = null; if (float.IsNaN(d.Speed) || float.IsInfinity(d.Speed)) { error = "speed not finite"; return false; } switch (d.Kind) { case 0: if (d.Speed != 1f || d.DayPercent != 0) { error = "normal day with a speed"; return false; } return true; case 1: if (d.DayPercent < 1 || d.DayPercent > 200 || d.Speed <= 0.3f || d.Speed >= 1f) { error = "long day out of range"; return false; } return true; case 2: if (d.DayPercent < 1 || d.DayPercent > 80 || d.Speed <= 1f || d.Speed > 5.001f) { error = "short day out of range"; return false; } return true; default: error = "kind " + d.Kind; return false; } } internal static byte[] EncodeHello(string modVersion) { using MemoryStream memoryStream = new MemoryStream(32); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8); binaryWriter.Write((byte)1); binaryWriter.Write(modVersion ?? ""); binaryWriter.Flush(); return memoryStream.ToArray(); } internal static bool TryDecodeHello(byte[] data, out int protocol, out string modVersion) { protocol = 0; modVersion = ""; if (data == null || data.Length < 1 || data.Length > 1024) { return false; } protocol = data[0]; try { using MemoryStream input = new MemoryStream(data, writable: false); using BinaryReader binaryReader = new BinaryReader(input, Encoding.UTF8); binaryReader.ReadByte(); modVersion = binaryReader.ReadString(); if (modVersion.Length > 32) { modVersion = modVersion.Substring(0, 32); } } catch { modVersion = "?"; } return true; } }