Decompiled source of Overtime v1.1.3
BepInEx/plugins/Overtime/Overtime.dll
Decompiled a month 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.Diagnostics; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using Fusion; using HLG.Runtime.Serialisation; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Reflection; using Microsoft.CodeAnalysis; using Obi; using Overtime.Config; using Overtime.Core; using Overtime.Features.Cap; using Overtime.Features.Chaos; using Overtime.Features.Consequences; using Overtime.Features.Console; using Overtime.Features.Content; using Overtime.Features.Content.Customers; using Overtime.Features.CutContent; using Overtime.Features.Doors; using Overtime.Features.Ender; using Overtime.Features.Endgame; using Overtime.Features.Events; using Overtime.Features.Fixes; using Overtime.Features.Integrity; using Overtime.Features.LateJoin; using Overtime.Features.LateJoin.Resync; using Overtime.Features.Mimic; using Overtime.Features.Night; using Overtime.Features.Polish; using Overtime.Features.Scares; using Overtime.Features.SetPieces; using Overtime.Features.StoreLife; using Overtime.Features.Story; using Overtime.Features.Surprises; using Overtime.Features.Tutorials; using Overtime.Features.Unpredict; using Overtime.Features.Veteran; using Overtime.Features.Voice; using Overtime.Features.Waiting; using Overtime.Integration; using Overtime.Logic; using Overtime.Net; using POpusCodec; using POpusCodec.Enums; using Pathfinding; using Photon.Voice; using Photon.Voice.Unity; using Steamworks; using TMPro; using UnityEngine; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Video; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Overtime { [BepInPlugin("Vippy.Overtime", "Overtime", "1.1.3")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BasePlugin { public const string Guid = "Vippy.Overtime"; public const string Version = "1.1.3"; private OvertimeConfig _config; private ModuleRegistry _registry; public ConfigFile DeveloperConfig => _config?.DeveloperFile; private static string PluginDirectory => Path.GetDirectoryName(typeof(Plugin).Assembly.Location); public override void Load() { _config = new OvertimeConfig(); _config.Bind(((BasePlugin)this).Config); Log.Attach(((BasePlugin)this).Log, () => _config.LogLevel); ModuleLog moduleLog = Log.For("Plugin"); DateTime now = DateTime.Now; CrashArchive.Filed filed = CrashArchive.Rotate(Paths.BepInExRootPath, now); if (_config.DiagnosticsFile) { Diagnostics.Start(Paths.BepInExRootPath, new string[2] { "Overtime 1.1.3, launched " + now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture), "log level is " + _config.LogLevel.ToString() + "; this file keeps every line regardless" }); moduleLog.Info("diagnostics go to " + Diagnostics.Path); foreach (string item in Inventory.AtLoad("1.1.3", ((BasePlugin)this).Config, _config.DeveloperFile)) { Diagnostics.Marker(item); } NativeCrashCatcher.Start(CrashArchive.CurrentFolder); JitMap.Start(CrashArchive.CurrentFolder); Watchdog.Start(); Inside.Start(); CrashArchive.ClosingNotes = Watchdog.SessionNote; } if (filed != null && filed.End == SessionEnd.Crashed) { moduleLog.Warning("the last session did not close cleanly; its logs are in BepInEx/Overtime-logs/" + filed.Folder); } CrashArchive.Listen(); if (_config.Migration.Outcome == MigrationOutcome.NewerThanBuild) { moduleLog.Warning("the settings file was written by Overtime " + _config.Migration.FromVersion + ", which is newer than this build. It has been left alone."); } else if (_config.Migration.StepsRun > 0) { moduleLog.Info("settings migrated from " + _config.Migration.FromVersion + " to " + _config.Migration.ToVersion); } foreach (string item2 in _config.Migration.Reset) { moduleLog.Warning("setting reset: " + item2); } if (_config.DeveloperFile != null) { moduleLog.Warning("hidden settings are being read from Vippy.Overtime.dev.cfg, delete it to go back to the defaults"); } if (_config.AllPatchesDisabled) { moduleLog.Warning("every patch is switched off in the settings, so the game runs as it shipped"); return; } List<string> list = InteropCheck.Blocked(); if (list.Count > 0) { string text = InteropBlock.Notice(list); moduleLog.Warning(text); Diagnostics.Marker(text); return; } ModSettingsMenuBridge.Register("Vippy.Overtime", "1.1.3"); ModSettingsMenuBridge.MarkHostRows(_config.IsHostOnly); SplashVideo.PluginDirectory = PluginDirectory; ContentModule contentModule = new ContentModule(_config, PluginDirectory); ChannelModule channelModule = new ChannelModule(_config, "1.1.3"); ConsoleModule consoleModule = new ConsoleModule(_config); _registry = new ModuleRegistry(Log.For); _registry.Register(channelModule); _registry.Register(new SettingsSyncModule(_config, channelModule)); _registry.Register(new LateJoinModule(_config)); _registry.Register(new JoinRequestModule()); _registry.Register(new LoneRpcModule()); _registry.Register(new LateJoinResyncModule(_config)); _registry.Register(contentModule); _registry.Register(new ReviewRangeModule(_config, contentModule.Rows)); _registry.Register(new NamedReviewsModule(_config)); StoryVariety.HostFinishedStory = SteamStory.HostFinishedStory; _registry.Register(new ChaosModule(_config)); _registry.Register(new NightPlanModule(_config)); _registry.Register(new ContentFallbackModule()); _registry.Register(new EventRollerModule(_config)); _registry.Register(new ScareModule(_config)); _registry.Register(new HarmlessTurnModule(_config)); _registry.Register(new StalkerModule(_config)); _registry.Register(new SurpriseModule(_config)); _registry.Register(new SpectateModule(_config)); _registry.Register(consoleModule); _registry.Register(new ChatModule(_config, channelModule, consoleModule.Runner)); _registry.Register(new PingModule(_config, channelModule)); _registry.Register(new SprayerModule(_config, channelModule)); _registry.Register(new PerformanceModule(_config)); _registry.Register(new VoiceModule(_config)); _registry.Register(new MimicModule(_config, PluginDirectory)); _registry.Register(new InboxCopiesModule()); _registry.Register(new EnderModule(_config)); _registry.Register(new FixesModule(_config)); _registry.Register(new CowForGuestsModule(_config)); _registry.Register(new WaitModule(_config, channelModule)); _registry.Register(new CapModule(_config)); _registry.Register(new IntegrityModule(_config)); _registry.Register(new StoryVarietyModule(_config)); _registry.Register(new PatienceModule(_config)); _registry.Register(new VeteranModule(_config)); _registry.Register(new ConsequencesModule(_config)); _registry.Register(new StoryArcsModule(_config)); _registry.Register(new EndgameModule(_config)); _registry.Register(new ExtraCustomerModule(_config)); _registry.Register(new CopyRevealModule(_config)); _registry.Register(new TutorialModule(_config, channelModule)); _registry.Register(new CutHintsModule(_config)); _registry.Register(new CutCustomersModule(_config)); _registry.Register(new CutCastModule(_config)); _registry.Register(new NorbertModule(_config)); _registry.Register(new ObjectiveLineModule()); _registry.Register(new PhoneCallModule(_config)); _registry.Register(new RoadsideModule(_config)); _registry.Register(new UnpredictNightModule(_config)); _registry.Register(new UnpredictHuntModule(_config)); _registry.Register(new SetPieceModule(_config)); _registry.Register(new DoorsModule(_config)); _registry.Register(new StoreUpgradesModule(_config)); _registry.Register(new StoreLifeModule(_config, channelModule)); _registry.Register(new BoardPapersModule()); _registry.LoadAll(); if (Inside.On) { Diagnostics.Marker("marked " + Inside.WrappedCount + " patch methods for the watchdog in " + Inside.WrapMilliseconds.ToString("0", CultureInfo.InvariantCulture) + " ms, " + Inside.SkippedCount + " left unmarked"); } foreach (IOvertimeModule module in _registry.Modules) { Diagnostics.Expect(module.Name); Diagnostics.Marker("module " + module.Name + ": " + _registry.Describe(module.Name)); } Diagnostics.Marker("settings: late join " + _config.LateJoinMode.ToString() + ", scares " + _config.GetChoice("00 Overtime", "Scares") + ", humour " + _config.GetChoice("00 Overtime", "Humour") + ", story variety " + _config.GetChoice("00 Overtime", "Story Variety") + ", new content " + _config.GetBool("00 Overtime", "New Content") + ", veteran moments " + _config.GetChoice("00 Overtime", "Veteran Moments") + ", mimic " + _config.GetChoice("00 Overtime", "Mimic")); moduleLog.Info("loaded, " + _registry.Modules.Count + " modules, late join is " + _config.LateJoinMode); } public override bool Unload() { _registry?.UnloadAll(); CrashArchive.Close(); Watchdog.Stop(); JitMap.Stop(); Diagnostics.Stop(); _config?.Release(); Log.Detach(); return true; } } } namespace Overtime.Net { internal sealed class ChannelModule : ModuleBase { [HarmonyPatch(typeof(FusionNetworkManager), "OnSceneLoadDone")] internal static class SessionPatch { private static void Postfix(NetworkRunner runner) { _live?.OnSessionReady(runner); } } [HarmonyPatch(typeof(FusionNetworkManager), "OnPlayerLeft")] internal static class LeavePatch { private static void Postfix(PlayerRef player) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) _live?.OnPlayerLeft(player); } } [HarmonyPatch(typeof(FusionNetworkManager), "OnShutdown")] internal static class ShutdownPatch { private static void Postfix() { _live?.OnSessionClosed(); } } private static ChannelModule _live; private readonly OvertimeConfig _config; private readonly ChannelCore _core; private ReliableChannel _transport; private Action _tick; private bool _saidSwitchedOff; protected override IEnumerable<Type> PatchTypes => new Type[4] { typeof(ReliableChannel.DeliveryPatch), typeof(SessionPatch), typeof(LeavePatch), typeof(ShutdownPatch) }; public static ChannelModule Live => _live; public ProbeResult Probe => _core.Probe; public ChannelKind Kind { get { if (_transport == null || !_transport.IsAttached) { return ChannelKind.None; } return ChannelKind.Reliable; } } public HashSet<int> MismatchedPeers => _core.MismatchedPeers; public HashSet<int> ContentMismatchedPeers => _core.ContentMismatchedPeers; public event Action<PlayerRef> GuestGreeted; public event Action HostGreeted; public event Action SessionClosed; public ChannelModule(OvertimeConfig config, string modVersion) : base("Channel") { _config = config; _core = new ChannelCore(modVersion, () => _config.Hash(), () => ContentStamp.From(ContentHealth.Current), Say, _config.SelfCheckOnLoad); _core.GuestGreeted += OnGuestGreeted; _core.HostGreeted += delegate { this.HostGreeted?.Invoke(); }; } public void Handle(WireMessageId id, Action<int, byte[]> handler) { _core.Handle(id, handler); } public void Forget(WireMessageId id) { _core.Forget(id); } public bool SendToPlayer(PlayerRef player, WireMessageId id, byte[] payload) { if (((PlayerRef)(ref player)).IsRealPlayer) { return _core.SendToPlayer(((PlayerRef)(ref player)).PlayerId, id, payload); } return false; } public static PlayerRef Peer(NetworkRunner runner, int playerId) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return PlayerRefFor(runner, playerId); } public bool SaidHello(int playerId) { return _core.GreetedPeers.Contains(playerId); } public bool SendToServer(WireMessageId id, byte[] payload) { return _core.SendToServer(id, payload); } public int Broadcast(WireMessageId id, byte[] payload) { return _core.Broadcast(id, payload); } public string WhyPackPeopleAreHeld() { List<int> list = Guests(); if (list != null) { return _core.WhyPackPeopleAreHeld(list, Gamertags.Of); } return null; } public bool EveryGuestHasOvertime() { List<int> list = Guests(); if (list != null) { return _core.WithoutOvertime(list) < 0; } return true; } public string PackHoldNote() { List<int> list = Guests(); PackHold packHold = ((list == null) ? null : _core.PackHoldOn(list)); if (packHold != null) { return PackPeopleGate.HostNote(packHold, Gamertags.Of(packHold.PlayerId)); } return null; } private static List<int> Guests() { //IL_002e: 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_003d: 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) NetworkRunner runner = GameRefs.Runner; if ((Object)(object)runner == (Object)null || !runner.IsServer) { return null; } List<int> list = new List<int>(); foreach (PlayerRef item in GameRefs.ActivePlayers(runner)) { PlayerRef current = item; if (((PlayerRef)(ref current)).IsRealPlayer && current != runner.LocalPlayer) { list.Add(((PlayerRef)(ref current)).PlayerId); } } return list; } protected override void Apply() { _transport = new ReliableChannel(_core.Deliver, base.Log); _tick = delegate { _core.Tick(Time.realtimeSinceStartup); }; OvertimeDriver.AddSlow(_tick); _live = this; } protected override void Revert() { if (_tick != null) { OvertimeDriver.RemoveSlow(_tick); _tick = null; } _transport?.Detach(); _transport = null; _core.OnSessionClosed(); this.GuestGreeted = null; this.HostGreeted = null; this.SessionClosed = null; _live = null; } private void OnSessionReady(NetworkRunner runner) { //IL_0091: 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) if ((Object)(object)runner == (Object)null || _transport == null) { return; } if (!_config.GetBool("90 Advanced", "Mod Channel")) { _transport.Detach(); _core.OnSessionClosed(); if (!_saidSwitchedOff) { _saidSwitchedOff = true; base.Log.Warning("the mod channel is switched off in the settings, so nothing of Overtime's crosses between machines"); } } else if (!_transport.Attach(runner)) { _core.Fail("the reliable path could not be wired to the runner"); } else { ChannelCore core = _core; ReliableChannel transport = _transport; bool isServer = runner.IsServer; PlayerRef localPlayer = runner.LocalPlayer; core.OnSessionReady(transport, isServer, ((PlayerRef)(ref localPlayer)).PlayerId, Time.realtimeSinceStartup); } } private void OnPlayerLeft(PlayerRef player) { if (((PlayerRef)(ref player)).IsRealPlayer) { _core.OnPlayerLeft(((PlayerRef)(ref player)).PlayerId); } } private void OnSessionClosed() { _transport?.Release(); _core.OnSessionClosed(); Gamertags.Clear(); this.SessionClosed?.Invoke(); } private void OnGuestGreeted(int playerId) { //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_0020: Unknown result type (might be due to invalid IL or missing references) PlayerRef obj = PlayerRefFor(GameRefs.Runner, playerId); if (((PlayerRef)(ref obj)).IsRealPlayer) { this.GuestGreeted?.Invoke(obj); } } private void Say(OvertimeLogLevel level, string message) { switch (level) { case OvertimeLogLevel.Error: base.Log.Error(message); break; case OvertimeLogLevel.Warning: base.Log.Warning(message); break; case OvertimeLogLevel.Info: base.Log.Info(message); break; default: base.Log.Verbose(message); break; } } private static PlayerRef PlayerRefFor(NetworkRunner runner, int playerId) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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) foreach (PlayerRef item in GameRefs.ActivePlayers(runner)) { PlayerRef current = item; if (((PlayerRef)(ref current)).PlayerId == playerId) { return current; } } return PlayerRef.None; } } internal sealed class ReliableChannel : IChannelTransport, IChannelTransportState { [HarmonyPatch(typeof(NetworkEvents), "Fusion_INetworkRunnerCallbacks_OnReliableDataReceived")] internal static class DeliveryPatch { private static bool Prefix(NetworkEvents __instance, PlayerRef player, ArraySegment<byte> data) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) ReliableChannel live = _live; if (live == null || (Object)(object)live._events == (Object)null || ((Il2CppObjectBase)__instance).Pointer != ((Il2CppObjectBase)live._events).Pointer) { return true; } live.Receive(player, data); return false; } } private const string SendToPlayerField = "NativeMethodInfoPtr_SendReliableDataToPlayer_Public_Void_PlayerRef_ReliableKey_Il2CppStructArray_1_Byte_0"; private const string SendToServerField = "NativeMethodInfoPtr_SendReliableDataToServer_Public_Void_ReliableKey_Il2CppStructArray_1_Byte_0"; private static ReliableChannel _live; private static IntPtr _sendToPlayer; private static IntPtr _sendToServer; private readonly Action<int, byte[], int, int> _deliver; private readonly ModuleLog _log; private NetworkRunner _runner; private NetworkEvents _events; private GameObject _holder; public bool IsAttached { get { if ((Object)(object)_runner != (Object)null) { return (Object)(object)_events != (Object)null; } return false; } } public string WhyNotLive { get { if (!IsAttached) { return "the channel is not attached to a runner"; } if (_runner.IsShutdown) { return "the runner is shut down"; } if (!_runner.IsRunning) { return "the runner is not running"; } return null; } } public ReliableChannel(Action<int, byte[], int, int> deliver, ModuleLog log) { _deliver = deliver; _log = log; } public bool Attach(NetworkRunner runner) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)runner == (Object)null) { return false; } if (IsAttached && ((Il2CppObjectBase)_runner).Pointer == ((Il2CppObjectBase)runner).Pointer) { return true; } if (!ResolveSends()) { return false; } Detach(); _holder = new GameObject("OvertimeChannel"); Object.DontDestroyOnLoad((Object)(object)_holder); _events = _holder.AddComponent<NetworkEvents>(); FillEmptyEvents(_events); INetworkRunnerCallbacks val = ((Il2CppObjectBase)_events).TryCast<INetworkRunnerCallbacks>(); if (val == null) { Detach(); return false; } runner.AddCallbacks(new Il2CppReferenceArray<INetworkRunnerCallbacks>((INetworkRunnerCallbacks[])(object)new INetworkRunnerCallbacks[1] { val })); _runner = runner; _live = this; if (runner.IsServer) { AllowClientToServer(runner); } ModuleLog log = _log; PlayerRef localPlayer = runner.LocalPlayer; log.Verbose("reliable channel attached to the runner as player " + ((PlayerRef)(ref localPlayer)).PlayerId); return true; } private bool ResolveSends() { if (_sendToPlayer != IntPtr.Zero && _sendToServer != IntPtr.Zero) { return true; } _sendToPlayer = MethodInfoOf("NativeMethodInfoPtr_SendReliableDataToPlayer_Public_Void_PlayerRef_ReliableKey_Il2CppStructArray_1_Byte_0", "SendReliableDataToPlayer", "Fusion.PlayerRef", "Fusion.Sockets.ReliableKey", "System.Byte[]"); _sendToServer = MethodInfoOf("NativeMethodInfoPtr_SendReliableDataToServer_Public_Void_ReliableKey_Il2CppStructArray_1_Byte_0", "SendReliableDataToServer", "Fusion.Sockets.ReliableKey", "System.Byte[]"); if (_sendToPlayer != IntPtr.Zero && _sendToServer != IntPtr.Zero) { return true; } _log.Warning("the runner's reliable send methods could not be found in this build of the game"); return false; } private static IntPtr MethodInfoOf(string fieldName, string methodName, params string[] argumentTypes) { FieldInfo field = typeof(NetworkRunner).GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && field.GetValue(null) is IntPtr intPtr && intPtr != IntPtr.Zero) { return intPtr; } return IL2CPP.GetIl2CppMethod(Il2CppClassPointerStore<NetworkRunner>.NativeClassPtr, false, methodName, "System.Void", argumentTypes); } private unsafe void AllowClientToServer(NetworkRunner runner) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_005a: Unknown result type (might be due to invalid IL or missing references) NetworkProjectConfig config = runner.Config; NetworkConfiguration val = ((config == null) ? null : config.Network); if (val == null) { _log.Warning("the runner has no network configuration to read, so the client to server reliable mode is whatever the game set"); return; } ReliableDataTransfers reliableDataTransferModes = val.ReliableDataTransferModes; if ((reliableDataTransferModes & 1) != 0) { _log.Verbose("reliable data transfer modes are " + ((object)(*(ReliableDataTransfers*)(&reliableDataTransferModes))/*cast due to .constrained prefix*/).ToString()); return; } val.ReliableDataTransferModes = (ReliableDataTransfers)(reliableDataTransferModes | 1); _log.Warning("the game's network config had client to server reliable data off (" + ((object)(*(ReliableDataTransfers*)(&reliableDataTransferModes))/*cast due to .constrained prefix*/).ToString() + "); switched on for this session, or a guest's first hello would get it disconnected"); } private void FillEmptyEvents(NetworkEvents events) { int num = 0; PropertyInfo[] properties = typeof(NetworkEvents).GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo propertyInfo in properties) { if (propertyInfo.CanRead && propertyInfo.CanWrite && typeof(UnityEventBase).IsAssignableFrom(propertyInfo.PropertyType) && propertyInfo.GetValue(events) == null && !(propertyInfo.PropertyType.GetConstructor(Type.EmptyTypes) == null)) { propertyInfo.SetValue(events, Activator.CreateInstance(propertyInfo.PropertyType)); num++; } } _log.Verbose("gave the callback forwarder " + num + " empty events"); } public void Detach() { if ((Object)(object)_events != (Object)null && (Object)(object)_runner != (Object)null) { _runner.RemoveCallbacks(new Il2CppReferenceArray<INetworkRunnerCallbacks>((INetworkRunnerCallbacks[])(object)new INetworkRunnerCallbacks[1] { ((Il2CppObjectBase)_events).TryCast<INetworkRunnerCallbacks>() })); } Release(); } public void Release() { if ((Object)(object)_holder != (Object)null) { Object.Destroy((Object)(object)_holder); } _holder = null; _events = null; _runner = null; if (_live == this) { _live = null; } } public bool SendToPlayer(int playerId, byte[] frame) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (!IsAttached) { return false; } PlayerRef player = PlayerFor(playerId); if (((PlayerRef)(ref player)).IsRealPlayer) { return Send(player, frame); } return false; } public unsafe bool SendToServer(byte[] frame) { if (!IsAttached) { return false; } Il2CppStructArray<byte> val = new Il2CppStructArray<byte>(frame); IntPtr* ptr = stackalloc IntPtr[2]; fixed (byte* overtime = ReliableKeyBytes.Overtime) { *ptr = (IntPtr)overtime; ptr[1] = IL2CPP.Il2CppObjectBaseToPtr((Il2CppObjectBase)(object)val); Invoke(_sendToServer, ptr, frame, "host"); } GC.KeepAlive(val); return true; } public int Broadcast(byte[] frame) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_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_0043: Unknown result type (might be due to invalid IL or missing references) if (!IsAttached) { return 0; } int num = 0; foreach (PlayerRef item in GameRefs.ActivePlayers(_runner)) { PlayerRef current = item; if (((PlayerRef)(ref current)).IsRealPlayer && !(current == _runner.LocalPlayer) && Send(current, frame)) { num++; } } return num; } private unsafe bool Send(PlayerRef player, byte[] frame) { Il2CppStructArray<byte> val = new Il2CppStructArray<byte>(frame); IntPtr* ptr = stackalloc IntPtr[3]; fixed (byte* overtime = ReliableKeyBytes.Overtime) { *ptr = (IntPtr)(&player); ptr[1] = (IntPtr)overtime; ptr[2] = IL2CPP.Il2CppObjectBaseToPtr((Il2CppObjectBase)(object)val); Invoke(_sendToPlayer, ptr, frame, ((PlayerRef)(ref player)).PlayerId.ToString(CultureInfo.InvariantCulture)); } GC.KeepAlive(val); return true; } private unsafe void Invoke(IntPtr method, IntPtr* args, byte[] frame, string to) { string text = "id=" + FrameId(frame) + " bytes=" + frame.Length + " to=" + to; Diagnostics.Marker("channel sending " + text); IntPtr zero = IntPtr.Zero; IL2CPP.il2cpp_runtime_invoke(method, IL2CPP.Il2CppObjectBaseToPtrNotNull((Il2CppObjectBase)(object)_runner), (void**)args, ref zero); Diagnostics.Marker("channel sent " + text + ((zero == IntPtr.Zero) ? string.Empty : " (threw)")); Il2CppException.RaiseExceptionIfNecessary(zero); } private static string FrameId(byte[] frame) { if (frame.Length <= 3) { return "?"; } WireMessageId wireMessageId = (WireMessageId)frame[3]; return wireMessageId.ToString(); } private PlayerRef PlayerFor(int playerId) { //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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) PlayerRef localPlayer = _runner.LocalPlayer; if (((PlayerRef)(ref localPlayer)).PlayerId == playerId) { return localPlayer; } foreach (PlayerRef item in GameRefs.ActivePlayers(_runner)) { PlayerRef current = item; if (((PlayerRef)(ref current)).PlayerId == playerId) { return current; } } return PlayerRef.None; } private void Receive(PlayerRef sender, ArraySegment<byte> data) { byte[] array = Copy(data); _deliver(((PlayerRef)(ref sender)).PlayerId, array, 0, array.Length); } private static byte[] Copy(ArraySegment<byte> segment) { Il2CppArrayBase<byte> array = segment.Array; if (array == null) { return Array.Empty<byte>(); } byte[] array2 = new byte[segment.Count]; for (int i = 0; i < array2.Length; i++) { array2[i] = array[segment.Offset + i]; } return array2; } } internal sealed class SettingsSyncModule : ModuleBase { private readonly OvertimeConfig _config; private readonly ChannelModule _channel; private readonly List<string> _watched = new List<string>(); private bool _noticed; protected override IEnumerable<Type> PatchTypes => Array.Empty<Type>(); public SettingsSyncModule(OvertimeConfig config, ChannelModule channel) : base("Settings") { _config = config; _channel = channel; } protected override void Apply() { _channel.Handle(WireMessageId.Settings, OnSettings); _channel.GuestGreeted += OnGuestGreeted; _channel.SessionClosed += OnSessionClosed; foreach (ConfigEntrySpec item in from spec in ConfigSchema.EntriesThrough(OvertimePhase.Polish) where spec.HostOnly select spec) { _watched.Add(item.ToString()); _config.Watch(item.Section, item.Key, OnHostSettingChanged); } } protected override void Revert() { _channel.GuestGreeted -= OnGuestGreeted; _channel.SessionClosed -= OnSessionClosed; foreach (string item in _watched) { string[] array = item.Split(new string[1] { " / " }, 2, StringSplitOptions.None); if (array.Length == 2) { _config.Unwatch(array[0], array[1], OnHostSettingChanged); } } _watched.Clear(); _config.HostOverrides.Clear(); } private void OnGuestGreeted(PlayerRef player) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (GameRefs.IsHost && _channel.SendToPlayer(player, WireMessageId.Settings, Block())) { base.Log.Verbose("sent the host settings to player " + ((PlayerRef)(ref player)).PlayerId); } } private void OnHostSettingChanged() { if (GameRefs.IsHost) { int num = _channel.Broadcast(WireMessageId.Settings, Block()); if (num > 0) { base.Log.Info("a host setting changed, " + num + " sent the new block"); } } } private void OnSettings(int senderPlayerId, byte[] payload) { if (GameRefs.IsHost) { return; } if (!SettingsBlock.TryDecode(payload, out var values)) { base.Log.Warning("dropped a malformed settings block from the host"); } else if (_config.HostOverrides.Apply(values)) { base.Log.Info("the host decides " + _config.HostOverrides.Count + " settings in this session: " + string.Join(", ", _config.HostOverrides.Entries.Select((KeyValuePair<string, string> pair) => pair.Key + " = " + pair.Value))); if (!_noticed) { _noticed = true; base.Log.Warning(HostSettingsNotice.Summary(HostSettingsNotice.Differences(_config.HostAuthoritativeValues(), values))); } } } private void OnSessionClosed() { _noticed = false; if (_config.HostOverrides.Clear()) { base.Log.Info("the session ended, your own settings are back"); } } private byte[] Block() { return SettingsBlock.Encode(_config.HostAuthoritativeValues()); } } } namespace Overtime.Logic { public sealed class ActionTrail { private readonly int _capacity; private readonly Queue<string> _lines = new Queue<string>(); public IReadOnlyList<string> Last => _lines.ToArray(); public ActionTrail(int capacity) { _capacity = ((capacity < 1) ? 1 : capacity); } public string Note(int night, string what) { string text = "doing (night " + night + "): " + what; if (_lines.Count == _capacity) { _lines.Dequeue(); } _lines.Enqueue(text); return text; } } public enum AdmissionOutcome { Vanilla, Admit, AdmitAsSpectator, Refuse } public enum AdmissionReason { ModeOff, SceneIsNotGame, LobbyFull, DayComplete, Cutscene, HuntInProgress, Clear } public readonly struct AdmissionDecision { public AdmissionOutcome Outcome { get; } public AdmissionReason Reason { get; } public NetworkErrorKey Error { get; } public AdmissionDecision(AdmissionOutcome outcome, AdmissionReason reason, NetworkErrorKey error) { Outcome = outcome; Reason = reason; Error = error; } } public enum NetworkErrorKey { None, GameInSession, LobbyFull } public readonly struct SessionSnapshot { public string ActiveSceneName { get; } public int PlayersAfterJoin { get; } public int MaxPlayers { get; } public bool DayCompleteAwaitingReport { get; } public bool InCutscene { get; } public bool HuntInProgress { get; } public SessionSnapshot(string activeSceneName, int playersAfterJoin, int maxPlayers, bool dayCompleteAwaitingReport, bool inCutscene, bool huntInProgress) { ActiveSceneName = activeSceneName; PlayersAfterJoin = playersAfterJoin; MaxPlayers = maxPlayers; DayCompleteAwaitingReport = dayCompleteAwaitingReport; InCutscene = inCutscene; HuntInProgress = huntInProgress; } } public readonly struct AdmissionSettings { public LateJoinMode Mode { get; } public bool AllowMidHunt { get; } public bool AllowDuringCutscene { get; } public bool AllowAfterDayComplete { get; } public AdmissionSettings(LateJoinMode mode, bool allowMidHunt, bool allowDuringCutscene, bool allowAfterDayComplete) { Mode = mode; AllowMidHunt = allowMidHunt; AllowDuringCutscene = allowDuringCutscene; AllowAfterDayComplete = allowAfterDayComplete; } } public static class AdmissionPolicy { public const string GameSceneName = "Game"; public const int HardCeiling = 7; public static int CountAfterJoin(int fusionCount, int lobbyMembers) { if (lobbyMembers <= 0 || lobbyMembers >= fusionCount) { return fusionCount; } return lobbyMembers; } public static AdmissionDecision Decide(SessionSnapshot session, AdmissionSettings settings) { if (settings.Mode == LateJoinMode.Off) { return new AdmissionDecision(AdmissionOutcome.Vanilla, AdmissionReason.ModeOff, NetworkErrorKey.None); } if (!string.Equals(session.ActiveSceneName, "Game", StringComparison.Ordinal)) { return new AdmissionDecision(AdmissionOutcome.Vanilla, AdmissionReason.SceneIsNotGame, NetworkErrorKey.None); } int num = ((session.MaxPlayers > 0) ? Math.Min(session.MaxPlayers, 7) : 7); if (session.PlayersAfterJoin > num) { return new AdmissionDecision(AdmissionOutcome.Refuse, AdmissionReason.LobbyFull, NetworkErrorKey.LobbyFull); } if (session.DayCompleteAwaitingReport && !settings.AllowAfterDayComplete) { return new AdmissionDecision(AdmissionOutcome.Refuse, AdmissionReason.DayComplete, NetworkErrorKey.GameInSession); } if (session.InCutscene && !settings.AllowDuringCutscene) { return new AdmissionDecision(AdmissionOutcome.Refuse, AdmissionReason.Cutscene, NetworkErrorKey.GameInSession); } if (session.HuntInProgress) { if (!settings.AllowMidHunt) { return new AdmissionDecision(AdmissionOutcome.Refuse, AdmissionReason.HuntInProgress, NetworkErrorKey.GameInSession); } return new AdmissionDecision(AdmissionOutcome.AdmitAsSpectator, AdmissionReason.HuntInProgress, NetworkErrorKey.None); } return new AdmissionDecision(AdmissionOutcome.Admit, AdmissionReason.Clear, NetworkErrorKey.None); } } public static class ArcGate { public static IReadOnlyList<CustomerSpec> Open(IEnumerable<CustomerSpec> candidates, int night, bool endless, Func<string, bool> happened) { List<CustomerSpec> list = new List<CustomerSpec>(); if (candidates == null) { return list; } foreach (CustomerSpec candidate in candidates) { if (candidate != null && IsOpen(candidate, night, endless, happened)) { list.Add(candidate); } } return list; } public static bool IsOpen(CustomerSpec spec, int night, bool endless, Func<string, bool> happened) { if (spec == null || night < spec.FromNight || (spec.LastNight > 0 && night > spec.LastNight)) { return false; } if (spec.IsArc && endless) { return false; } if (spec.Nights.Count > 0 && !Contains(spec.Nights, night)) { return false; } foreach (string afterId in spec.AfterIds) { if (!Happened(afterId, happened)) { return false; } } return true; } public static IReadOnlyList<CustomerSpec> Pinned(IEnumerable<CustomerSpec> open, int night) { List<CustomerSpec> list = new List<CustomerSpec>(); HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); if (open == null) { return list; } foreach (CustomerSpec item in open) { if (item != null && Contains(item.Nights, night) && hashSet.Add(item.Person)) { list.Add(item); } } return list; } public static bool Happened(string needed, Func<string, bool> happened) { if (string.IsNullOrEmpty(needed) || happened == null) { return false; } string[] array = needed.Split('|'); foreach (string text in array) { if (text.Length > 0 && happened(text)) { return true; } } return false; } public static IReadOnlyList<CustomerSpec> WithPinned(IReadOnlyList<CustomerSpec> chosen, IReadOnlyList<CustomerSpec> pinned, int wanted) { List<CustomerSpec> list = new List<CustomerSpec>(); if (pinned != null) { foreach (CustomerSpec item in pinned) { if (item != null && list.Count < wanted) { list.Add(item); } } } HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); HashSet<string> hashSet2 = new HashSet<string>(StringComparer.Ordinal); foreach (CustomerSpec item2 in list) { hashSet.Add(item2.Person); hashSet2.Add(item2.DonorDialogueId); } if (chosen != null) { foreach (CustomerSpec item3 in chosen) { if (item3 != null && list.Count < wanted && !hashSet.Contains(item3.Person) && !hashSet2.Contains(item3.DonorDialogueId)) { list.Add(item3); hashSet.Add(item3.Person); hashSet2.Add(item3.DonorDialogueId); } } } return list; } private static bool Contains(IReadOnlyList<int> nights, int night) { foreach (int night2 in nights) { if (night2 == night) { return true; } } return false; } } public sealed class ArcText { public string Id { get; } public ArcSurface Surface { get; } public string Category { get { if (Surface != ArcSurface.Email) { return "Diagetic Text"; } return "UI Text 5"; } } public string SenderKey { get; private set; } public string FromKey { get; private set; } public string SubjectKey { get; private set; } public string SubjectLineKey { get; private set; } public string BodyKey { get; private set; } public string TitleKey { get; private set; } public string BriefKey { get; private set; } public bool NamesTheDead { get; private set; } private ArcText(string id, ArcSurface surface) { Id = id; Surface = surface; } public IEnumerable<string> Keys() { string[] array = new string[7] { SenderKey, FromKey, SubjectKey, SubjectLineKey, TitleKey, BodyKey, BriefKey }; foreach (string text in array) { if (!string.IsNullOrEmpty(text)) { yield return text; } } } internal static ArcText Mail(string id, string sender, string from) { return new ArcText(id, ArcSurface.Email) { SenderKey = sender, FromKey = from, SubjectKey = id + " Subject", SubjectLineKey = id + " Subject Line", BodyKey = id + " Body" }; } internal static ArcText Paper(string id) { return new ArcText(id, ArcSurface.Paper) { TitleKey = id + " Title", BodyKey = id + " Paragraph", BriefKey = id + " Brief" }; } internal static ArcText Note(string id) { return new ArcText(id, ArcSurface.Note) { BodyKey = id }; } internal ArcText WithNames() { NamesTheDead = true; return this; } public override string ToString() { return Id; } } public static class ArcTexts { public const string MailCategory = "UI Text 5"; public const string PaperCategory = "Diagetic Text"; public const string NamesToken = "<NAMES>"; public const string ManagerSender = "Store Manager"; public const string ManagerFrom = "FROM: Store Manager"; public const string SheriffSender = "Arc Sender Sheriff"; public const string SheriffFrom = "Arc From Sheriff"; public const string FreightSender = "Arc Sender Freight"; public const string FreightFrom = "Arc From Freight"; public const string PowerSender = "Arc Sender Power"; public const string PowerFrom = "Arc From Power"; public const string QuietNoteKey = "Enjoy your shift!"; public static readonly IReadOnlyDictionary<string, PaperSlot> PaperSlots = new Dictionary<string, PaperSlot>(StringComparer.Ordinal) { ["Missing Person Paragraph"] = PaperSlot.Brief, ["ROADWORK DELAYS EXPECTED"] = PaperSlot.Headline, ["PARKSIDEPLAZA1"] = PaperSlot.Headline, ["PARKSIDEPLAZA2"] = PaperSlot.Paragraph }; public static readonly IReadOnlyList<ArcText> All = new ArcText[22] { ArcText.Mail("Arc Email Freight", "Arc Sender Freight", "Arc From Freight"), ArcText.Mail("Arc Email Rota", "Store Manager", "FROM: Store Manager"), ArcText.Mail("Arc Email Rota 2", "Store Manager", "FROM: Store Manager"), ArcText.Mail("Arc Email Ernie Back", "Store Manager", "FROM: Store Manager"), ArcText.Mail("Arc Email Ernie Buried", "Store Manager", "FROM: Store Manager"), ArcText.Mail("Arc Email Sheriff Notice", "Arc Sender Sheriff", "Arc From Sheriff"), ArcText.Mail("Arc Email Sheriff Notice 2", "Arc Sender Sheriff", "Arc From Sheriff"), ArcText.Mail("Arc Email Sheriff Missing", "Arc Sender Sheriff", "Arc From Sheriff").WithNames(), ArcText.Mail("Arc Email Sheriff Inquiry", "Arc Sender Sheriff", "Arc From Sheriff"), ArcText.Mail("Arc Email Sheriff Warrant", "Arc Sender Sheriff", "Arc From Sheriff").WithNames(), ArcText.Mail("Arc Email Power", "Arc Sender Power", "Arc From Power"), ArcText.Paper("Arc Paper Budd"), ArcText.Paper("Arc Paper Marsh"), ArcText.Paper("Arc Paper Ernie"), ArcText.Paper("Arc Paper Dobbs"), ArcText.Paper("Arc Paper Stray"), ArcText.Paper("Arc Paper Ambulance"), ArcText.Paper("Arc Paper Store"), ArcText.Paper("Arc Paper East"), ArcText.Note("Arc Note Keys"), ArcText.Note("Arc Note Keys 2"), ArcText.Note("Arc Note Deputy") }; public static readonly IReadOnlyList<string> SenderKeys = new string[6] { "Arc Sender Sheriff", "Arc From Sheriff", "Arc Sender Freight", "Arc From Freight", "Arc Sender Power", "Arc From Power" }; public static bool NeedsAQuietPage(string key) { if (!string.Equals(key, "PARKSIDEPLAZA1", StringComparison.Ordinal)) { return string.Equals(key, "PARKSIDEPLAZA2", StringComparison.Ordinal); } return true; } public static string KeyFor(ArcText text, PaperSlot slot) { if (text == null) { return null; } return slot switch { PaperSlot.Headline => text.TitleKey, PaperSlot.Paragraph => text.BodyKey, PaperSlot.Brief => text.BriefKey, _ => null, }; } public static ArcText Find(string id) { foreach (ArcText item in All) { if (string.Equals(item.Id, id, StringComparison.Ordinal)) { return item; } } return null; } public static string Fill(string words, IReadOnlyList<string> names) { if (string.IsNullOrEmpty(words) || words.IndexOf("<NAMES>", StringComparison.Ordinal) < 0) { return words; } string newValue = ((names == null || names.Count == 0) ? string.Empty : string.Join(", ", names)); return words.Replace("<NAMES>", newValue); } public static bool IsPaperSlot(string key, out PaperSlot slot) { slot = PaperSlot.Headline; if (key != null) { return PaperSlots.TryGetValue(key, out slot); } return false; } } public enum PaperSlot { Headline, Paragraph, Brief } public sealed class ArcShown { public string TextId { get; } public bool IsNew { get; } public IReadOnlyList<string> Names { get; } public ArcText Text => ArcTexts.Find(TextId); public ArcShown(string textId, bool isNew, IReadOnlyList<string> names) { TextId = textId ?? string.Empty; IsNew = isNew; Names = names ?? Array.Empty<string>(); } } public sealed class ArcTextPayload { public const int FormatVersion = 1; public const int MaxBytes = 4000; private const string Header = "arc text"; public int Night { get; } public List<ArcShown> Mail { get; } = new List<ArcShown>(); public ArcShown Paper { get; set; } public ArcShown Note { get; set; } public bool Any { get { if (Mail.Count <= 0 && Paper == null) { return Note != null; } return true; } } public ArcTextPayload(int night) { Night = night; } public byte[] Encode() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("arc text").Append('\t').Append(1.ToString(CultureInfo.InvariantCulture)) .Append('\n'); stringBuilder.Append("night\t").Append(Night.ToString(CultureInfo.InvariantCulture)).Append('\n'); foreach (ArcShown item in Mail) { Line(stringBuilder, "mail", item); } if (Paper != null) { Line(stringBuilder, "paper", Paper); } if (Note != null) { Line(stringBuilder, "note", Note); } byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString()); if (bytes.Length > 4000) { return Encoding.UTF8.GetBytes("arc text\t" + 1.ToString(CultureInfo.InvariantCulture) + "\nnight\t" + Night.ToString(CultureInfo.InvariantCulture) + "\n"); } return bytes; } public static bool TryDecode(byte[] bytes, out ArcTextPayload payload) { payload = null; if (bytes == null || bytes.Length == 0 || bytes.Length > 4000) { return false; } string text; try { text = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(bytes); } catch (ArgumentException) { return false; } string[] array = text.Split('\n'); if (array.Length < 2 || array[0] != "arc text\t" + 1.ToString(CultureInfo.InvariantCulture) || !array[1].StartsWith("night\t", StringComparison.Ordinal) || !int.TryParse(array[1].Substring(6), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return false; } ArcTextPayload arcTextPayload = new ArcTextPayload(result); for (int i = 2; i < array.Length; i++) { if (array[i].Length == 0) { continue; } string[] array2 = array[i].Split('\t'); if (array2.Length != 4 || (array2[2] != "0" && array2[2] != "1")) { return false; } ArcShown arcShown = new ArcShown(array2[1], array2[2] == "1", (array2[3].Length == 0) ? ((IReadOnlyList<string>)Array.Empty<string>()) : ((IReadOnlyList<string>)array2[3].Split(';'))); ArcText text2 = arcShown.Text; switch (array2[0]) { case "mail": if (text2 != null && text2.Surface == ArcSurface.Email) { arcTextPayload.Mail.Add(arcShown); continue; } break; case "paper": if (text2 != null && text2.Surface == ArcSurface.Paper && arcTextPayload.Paper == null) { arcTextPayload.Paper = arcShown; continue; } break; case "note": if (text2 != null && text2.Surface == ArcSurface.Note && arcTextPayload.Note == null) { arcTextPayload.Note = arcShown; continue; } break; } return false; } payload = arcTextPayload; return true; } private static void Line(StringBuilder text, string kind, ArcShown shown) { text.Append(kind).Append('\t').Append(Clean(shown.TextId)) .Append('\t') .Append(shown.IsNew ? '1' : '0') .Append('\t'); for (int i = 0; i < shown.Names.Count; i++) { text.Append((i == 0) ? string.Empty : ";").Append(Clean(shown.Names[i])); } text.Append('\n'); } private static string Clean(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(value.Length); foreach (char c in value) { stringBuilder.Append((char.IsControl(c) || c == ';') ? ' ' : c); } return stringBuilder.ToString().Trim(); } } public static class AutoAdvanceHold { public static bool GameHolds(bool lookingAtShelf, bool lookingAtComputer, bool paused) { return lookingAtShelf || lookingAtComputer || paused; } public static bool ShouldHold(bool dontAllowLockCursor, bool lookingAtShelf, bool lookingAtComputer, bool paused, bool customizablesMenuOpen, bool placingPoster) { return dontAllowLockCursor || GameHolds(lookingAtShelf, lookingAtComputer, paused) || customizablesMenuOpen || placingPoster; } public static bool StepIn(bool dontAllowLockCursor, bool lookingAtShelf, bool lookingAtComputer, bool paused, bool customizablesMenuOpen, bool placingPoster) { if (ShouldHold(dontAllowLockCursor, lookingAtShelf, lookingAtComputer, paused, customizablesMenuOpen, placingPoster)) { return !GameHolds(lookingAtShelf, lookingAtComputer, paused); } return false; } } public static class AwayInput { public const float DeadZone = 0.2f; public static bool Touched(bool anyKey, float mouseMoved, float leftStick, float rightStick, float triggers, bool anyPadButton) { if (!(anyKey || mouseMoved > 0f || anyPadButton) && !(leftStick > 0.2f) && !(rightStick > 0.2f)) { return triggers > 0.2f; } return true; } } public sealed class AwayWatch { private sealed class Pose { public float X; public float Y; public float Z; public float Yaw; public float Pitch; public double At; public double Still; public bool Away; } public const double DefaultAwaySeconds = 180.0; public const float MoveMetres = 0.05f; public const float LookDegrees = 1f; public const double LongestStep = 5.0; private readonly double _awaySeconds; private readonly Dictionary<int, Pose> _players = new Dictionary<int, Pose>(); public AwayWatch(double awaySeconds = 180.0) { _awaySeconds = awaySeconds; } public bool Sample(int playerId, double now, bool inShift, float x, float y, float z, float yaw, float pitch) { if (!_players.TryGetValue(playerId, out var value)) { _players[playerId] = new Pose { X = x, Y = y, Z = z, Yaw = yaw, Pitch = pitch, At = now }; return false; } double num = now - value.At; bool num2 = Math.Abs(x - value.X) > 0.05f || Math.Abs(y - value.Y) > 0.05f || Math.Abs(z - value.Z) > 0.05f || AngleApart(yaw, value.Yaw) > 1f || AngleApart(pitch, value.Pitch) > 1f; value.X = x; value.Y = y; value.Z = z; value.Yaw = yaw; value.Pitch = pitch; value.At = now; if (num2) { return Back(value); } if (inShift && num > 0.0 && num <= 5.0) { value.Still += num; } if (!value.Away && value.Still >= _awaySeconds) { value.Away = true; return true; } return false; } public bool Touch(int playerId, double now) { if (!_players.TryGetValue(playerId, out var value)) { return false; } return Back(value); } public void Forget(int playerId) { _players.Remove(playerId); } public bool IsAway(int playerId) { if (_players.TryGetValue(playerId, out var value)) { return value.Away; } return false; } public void Reset() { _players.Clear(); } private static bool Back(Pose pose) { bool away = pose.Away; pose.Still = 0.0; pose.Away = false; return away; } private static float AngleApart(float a, float b) { float num = Math.Abs(a - b) % 360f; if (!(num > 180f)) { return num; } return 360f - num; } } public enum BoardPaperKind { ManagerNote, FrontPage, EmotiScope } public enum BoardDealReason { GamesOwn, NeverSeen, Round, InsteadOfEmotiScope, ManagerHasSomethingToSay } public sealed class BoardNight { public IReadOnlyList<BoardPaperKind> Pool { get; init; } = Array.Empty<BoardPaperKind>(); public IReadOnlyList<int> SpawnedBefore { get; init; } = Array.Empty<int>(); public ulong SaveStream { get; init; } public bool EmotiScopeInTheStore { get; init; } public bool OrdersOnTheNote { get; init; } public bool ArcNoteDue { get; init; } } public sealed class BoardDeal { public int Index { get; } public BoardDealReason Reason { get; } public int DryNight { get; } public int Dealt { get; } public bool Untouched => Reason == BoardDealReason.GamesOwn; public static BoardDeal GamesOwn { get; } = new BoardDeal(-1, BoardDealReason.GamesOwn, -1, -1); public BoardDeal(int index, BoardDealReason reason, int dryNight, int dealt) { Index = index; Reason = reason; DryNight = dryNight; Dealt = dealt; } public override string ToString() { if (!Untouched) { return "day object " + Index.ToString(CultureInfo.InvariantCulture) + " (" + Reason.ToString() + ", dry night " + DryNight.ToString(CultureInfo.InvariantCulture) + ")"; } return "the game's own draw"; } } public static class BoardPapers { private sealed class Dealer { private readonly IReadOnlyList<BoardPaperKind> _pool; private readonly List<int> _order = new List<int>(); private readonly List<int> _instead = new List<int>(); private readonly ulong _stream; private readonly int _lastDrawn; private int _rounds; public int NeverSeenCount { get; } public Dealer(IReadOnlyList<BoardPaperKind> pool, IReadOnlyList<int> unseen, int lastDrawn, ulong saveStream) { _pool = pool; _lastDrawn = lastDrawn; _stream = StorySeed.Stream(saveStream, "board papers"); List<int> list = Shuffle(unseen.ToList(), StorySeed.Stream(_stream, "never seen")); _order.AddRange(list); NeverSeenCount = list.Count; } public int Base(int k) { while (_order.Count <= k + 1) { AddRound(); } return _order[k]; } private int Before(int k) { if (k != 0) { return _order[k - 1]; } return _lastDrawn; } public int Instead(int k) { for (int i = _instead.Count; i <= k; i++) { HashSet<int> avoid = new HashSet<int> { Before(i), Base(i), Base(i + 1) }; if (i > 0) { avoid.Add(_instead[i - 1]); } List<int> list = (from p in Enumerable.Range(0, _pool.Count) where _pool[p] == BoardPaperKind.FrontPage && !avoid.Contains(p) select p).ToList(); _instead.Add((list.Count == 0) ? Base(i) : list[(int)(StorySeed.Stream(_stream, "instead " + i.ToString(CultureInfo.InvariantCulture)) % (ulong)list.Count)]); } return _instead[k]; } private void AddRound() { List<int> list = Shuffle(Enumerable.Range(0, _pool.Count).ToList(), StorySeed.Stream(_stream, "round " + _rounds.ToString(CultureInfo.InvariantCulture))); _rounds++; int num = ((_order.Count == 0) ? _lastDrawn : _order[_order.Count - 1]); if (list.Count > 1 && list[0] == num) { int num2 = 1 + (int)(StorySeed.Stream(_stream, "swap " + _rounds.ToString(CultureInfo.InvariantCulture)) % (ulong)(list.Count - 1)); List<int> list2 = list; int index = num2; int value = list[num2]; int value2 = list[0]; list[0] = value; list2[index] = value2; } _order.AddRange(list); } private static List<int> Shuffle(List<int> items, ulong seed) { for (int num = items.Count - 1; num > 0; num--) { int num2 = (int)(StorySeed.Stream(seed, num.ToString(CultureInfo.InvariantCulture)) % (ulong)(num + 1)); int index = num; int index2 = num2; int value = items[num2]; int value2 = items[num]; items[index] = value; items[index2] = value2; } return items; } } public const int DryBelow = 3; public const int EmotiScopeItem = 11; public static readonly IReadOnlyList<int> GoneBetweenShifts = new int[11] { 2, 11, 42, 15, 45, 46, 47, 48, 49, 50, 55 }; public static BoardPaperKind KindOf(string name) { if (string.Equals(name, "ENJOY YOUR SHIFT", StringComparison.Ordinal)) { return BoardPaperKind.ManagerNote; } if (name == null || !name.StartsWith("EMOTISCOPE", StringComparison.Ordinal)) { return BoardPaperKind.FrontPage; } return BoardPaperKind.EmotiScope; } public static IReadOnlyList<int> Unseen(int poolSize, IReadOnlyList<int> spawnedBefore) { HashSet<int> seen = new HashSet<int>(spawnedBefore ?? Array.Empty<int>()); return (from i in Enumerable.Range(0, Math.Max(0, poolSize)) where !seen.Contains(i) select i).ToList(); } public static bool IsDry(int poolSize, IReadOnlyList<int> spawnedBefore) { if (poolSize >= 3) { return Unseen(poolSize, spawnedBefore).Count < 3; } return false; } public static (int DryNights, int LastDrawn) DryHistory(int poolSize, IReadOnlyList<int> spawnedBefore) { HashSet<int> hashSet = new HashSet<int>(); int num = 0; while (spawnedBefore != null && num < spawnedBefore.Count) { int num2 = spawnedBefore[num]; if (num2 >= 0 && num2 < poolSize) { hashSet.Add(num2); } if (poolSize - hashSet.Count < 3) { return (DryNights: spawnedBefore.Count - num - 1, LastDrawn: num2); } num++; } return (DryNights: -1, LastDrawn: -1); } public static BoardDeal Deal(BoardNight night) { if (night == null || !IsDry(night.Pool.Count, night.SpawnedBefore)) { return BoardDeal.GamesOwn; } (int DryNights, int LastDrawn) tuple = DryHistory(night.Pool.Count, night.SpawnedBefore); int item = tuple.DryNights; int item2 = tuple.LastDrawn; Dealer dealer = new Dealer(night.Pool, Unseen(night.Pool.Count, night.SpawnedBefore), item2, night.SaveStream); int num = dealer.Base(item); BoardDealReason reason = ((item < dealer.NeverSeenCount) ? BoardDealReason.NeverSeen : BoardDealReason.Round); int index = num; if (night.Pool[num] == BoardPaperKind.EmotiScope && night.EmotiScopeInTheStore) { index = dealer.Instead(item); reason = BoardDealReason.InsteadOfEmotiScope; } if (night.ArcNoteDue && night.Pool[index] != BoardPaperKind.ManagerNote) { int num2 = ManagerNoteIndex(night.Pool); if (num2 >= 0) { index = num2; reason = BoardDealReason.ManagerHasSomethingToSay; } } return new BoardDeal(index, reason, item, num); } public static bool EmotiScopeInTheStore(int taggedInTheWorld, IEnumerable<IEnumerable<int>> savedInventories, IReadOnlyCollection<int> goneBetweenShifts) { if (taggedInTheWorld > 0) { return true; } if ((goneBetweenShifts ?? GoneBetweenShifts).Contains(11)) { return false; } return (savedInventories ?? Enumerable.Empty<IEnumerable<int>>()).Any((IEnumerable<int> slots) => slots?.Contains(11) ?? false); } public static int ManagerNoteIndex(IReadOnlyList<BoardPaperKind> pool) { int num = 0; while (pool != null && num < pool.Count) { if (pool[num] == BoardPaperKind.ManagerNote) { return num; } num++; } return -1; } } public enum PaperGlow { Leave, Unlight, Light } public sealed class BoardReads { private sealed class Paper { public string Words; public bool Lit; public readonly HashSet<string> Read = new HashSet<string>(StringComparer.Ordinal); public readonly HashSet<string> Relit = new HashSet<string>(StringComparer.Ordinal); } private readonly Dictionary<string, Paper> _papers = new Dictionary<string, Paper>(StringComparer.Ordinal); public int Count => _papers.Count; public PaperGlow Observe(string paper, string words, bool lit) { if (paper == null) { return PaperGlow.Leave; } if (words == null) { words = string.Empty; } if (!_papers.TryGetValue(paper, out var value)) { value = new Paper { Words = words, Lit = lit }; if (!lit) { value.Read.Add(words); } _papers[paper] = value; return PaperGlow.Leave; } bool flag = !string.Equals(value.Words, words, StringComparison.Ordinal); PaperGlow paperGlow = PaperGlow.Leave; if (!flag && value.Lit && !lit) { value.Read.Add(words); } else if (lit && value.Read.Contains(words)) { paperGlow = PaperGlow.Unlight; } else if (!lit && flag && !value.Read.Contains(words) && value.Relit.Add(words)) { paperGlow = PaperGlow.Light; } value.Words = words; Paper paper2 = value; paper2.Lit = paperGlow switch { PaperGlow.Unlight => false, PaperGlow.Light => true, _ => lit, }; return paperGlow; } public bool AllRead() { if (_papers.Count == 0) { return false; } foreach (Paper value in _papers.Values) { if (!value.Read.Contains(value.Words)) { return false; } } return true; } public void Forget(string paper) { if (paper != null) { _papers.Remove(paper); } } public void Reset() { _papers.Clear(); } } public sealed class PaperVisitor { public string DialogueId { get; } public string Person { get; } public bool Copy { get; } public bool Car { get; } public PaperVisitor(string dialogueId, string person, bool copy, bool car) { DialogueId = dialogueId ?? string.Empty; Person = person ?? string.Empty; Copy = copy; Car = car; } public static PaperVisitor Of(string dialogueId, string prefabName) { string person = BodyOwners.Of(dialogueId) ?? prefabName; bool copy = prefabName != null && prefabName.IndexOf("Doppel", StringComparison.Ordinal) >= 0; return new PaperVisitor(dialogueId, person, copy, car: false); } public static PaperVisitor OfCar(string prefabName) { return new PaperVisitor(string.Empty, prefabName, copy: false, car: true); } public override string ToString() { if (!Car) { return (Copy ? (Person + "'s copy") : Person) + " (" + DialogueId + ")"; } return "the car " + Person; } } public sealed class VisitorHistory { public Func<string, bool> HumanDead { get; init; } = (string _) => false; public Func<string, bool> CopyShot { get; init; } = (string _) => false; public Func<string, bool> CopyThrough { get; init; } = (string _) => false; public Func<string, bool> FaceHeld { get; init; } = (string _) => false; public bool BookKept { get; init; } } public enum BoardVisit { Nobody, FirstTime, Again } public static class BoardVisitors { public const string NpcToken = "DAY OBJ NPC"; public const string CarToken = "DAY OBJ CAR"; public static (BoardVisit Visit, string Why) Decide(BoardDeal deal, bool paperNeverDrawn, PaperVisitor visitor, VisitorHistory history) { if (history == null) { history = new VisitorHistory(); } if (deal == null || deal.Untouched || deal.Index < 0) { return (Visit: BoardVisit.Nobody, Why: "the game drew tonight's paper itself"); } if (visitor == null) { return (Visit: BoardVisit.Nobody, Why: "the paper sends nobody"); } if (!visitor.Car && history.FaceHeld(visitor.Person)) { return (Visit: BoardVisit.Nobody, Why: visitor.Person + "'s face was somebody else's in this save"); } if (!visitor.Car && history.HumanDead(visitor.Person)) { return (Visit: BoardVisit.Nobody, Why: visitor.Person + " is dead"); } if (visitor.Copy && history.CopyShot(visitor.Person)) { return (Visit: BoardVisit.Nobody, Why: visitor.Person + "'s copy was shot"); } if (!visitor.Car && history.CopyThrough(visitor.Person)) { return (Visit: BoardVisit.Nobody, Why: visitor.Person + "'s copy got through, it came for good"); } if (paperNeverDrawn && deal.Reason == BoardDealReason.NeverSeen) { return (Visit: BoardVisit.FirstTime, Why: "the save never had this paper"); } if (visitor.Car) { return (Visit: BoardVisit.Nobody, Why: "the car came the first time round"); } if (visitor.Copy && !history.BookKept) { return (Visit: BoardVisit.Nobody, Why: "no book says how the copy's last visit ended"); } return (Visit: BoardVisit.Again, Why: visitor.Copy ? "the copy was turned away or never seen to, it tries again" : (visitor.Person + " is alive and can come in again")); } public static int Slot(IReadOnlyList<string> occurrences, int rolled) { int num = occurrences?.Count ?? 0; int val = num; for (int i = 0; i < num; i++) { if (string.Equals(occurrences[i], "END DAY", StringComparison.Ordinal)) { val = i; break; } } return Math.Max(0, Math.Min(rolled, val)); } } public static class BodyClaims { public static string Borrowed(CustomerSpec spec) { if (spec != null && GeneratedCast.TryRead(spec.DialogueId, out var body, out var _) && string.Equals(body, spec.DonorDialogueId, StringComparison.Ordinal)) { return null; } string text = ((spec == null) ? null : BodyOwners.Of(spec.DonorDialogueId)); if (text != null && !string.Equals(text, spec.Person, StringComparison.Ordinal)) { return text; } return null; } public static bool Free(CustomerSpec spec, Func<string, bool> personMet, Func<string, bool> ownerMet, IEnumerable<CustomerSpec> speakers) { string text = ((spec == null) ? null : BodyOwners.Of(spec.DonorDialogueId)); if (text == null) { return spec != null; } List<string> list = new List<string>(); foreach (CustomerSpec item in speakers ?? Array.Empty<CustomerSpec>()) { if (item != null && !string.Equals(item.Person, text, StringComparison.Ordinal) && string.Equals(BodyOwners.Of(item.DonorDialogueId), text, StringComparison.Ordinal) && !list.Contains(item.Person) && personMet != null && personMet(item.Person)) { list.Add(item.Person); } } if (list.Count > 0) { return list.Contains(spec.Person); } if ((ownerMet != null && ownerMet(text)) || (personMet != null && personMet(text))) { return string.Equals(spec.Person, text, StringComparison.Ordinal); } return true; } public static bool FaceTonight(CustomerSpec spec, ICollection<string> tonight) { if (spec == null || tonight == null) { return false; } if (tonight.Contains(spec.DonorDialogueId)) { return true; } string text = BodyOwners.Of(spec.DonorDialogueId); if (text == null) { return false; } foreach (string item in tonight) { if (string.Equals(BodyOwners.Of(item), text, StringComparison.Ordinal)) { return true; } } return false; } public static bool WornByAnother(string owner, Func<string, bool> personMet, IEnumerable<CustomerSpec> speakers) { if (owner == null || personMet == null) { return false; } foreach (CustomerSpec item in speakers ?? Array.Empty<CustomerSpec>()) { if (item != null && string.Equals(Borrowed(item), owner, StringComparison.Ordinal) && personMet(item.Person)) { return true; } } return false; } public static IReadOnlyList<string> KeepOut(IEnumerable<CustomerSpec> cameIn) { List<string> list = new List<string>(); foreach (CustomerSpec item in cameIn ?? Array.Empty<CustomerSpec>()) { string text = Borrowed(item); if (text != null && !list.Contains(text)) { list.Add(text); } } return list; } } public static class BodyOwners { private static readonly Dictionary<string, string> ByDialogueId = new Dictionary<string, string>(StringComparer.Ordinal) { ["0"] = "Clyde Dawson", ["1"] = "Julietta Granger", ["2"] = "Roger Conroy", ["3"] = "Bonnie McCree", ["4"] = "Tommy Delgado", ["5"] = "Tommy Delgado", ["6"] = "Kevin Larson", ["7"] = "Ryan Holt", ["8"] = "Ryan Holt", ["9"] = "Jade Sinclair", ["10"] = "Nathan Calloway", ["12"] = "Clyde Dawson", ["13"] = "Judith Calhoun", ["14"] = "Brandon Keller", ["15"] = "Howard Elkins", ["16"] = "Cara Hastings", ["17"] = "Judith Calhoun", ["18"] = "Ramona Delgado", ["20"] = "Esteban Morales", ["21"] = "Ricky Lawson", ["22"] = "Ricky Lawson", ["23"] = "Ricky Lawson", ["24"] = "Tofu", ["25"] = "Marjorie Cole", ["26"] = "Marjorie Cole", ["27"] = "Diana Volkov", ["28"] = "Diana Volkov", ["29"] = "Karen Whitfield", ["30"] = "Karen Whitfield", ["31"] = "Karen Whitfield", ["32"] = "Lena Rowe", ["33"] = "Martha Collins", ["34"] = "Martha Collins", ["35"] = "Linda Carver", ["36"] = "Linda Carver", ["37"] = "Anita Varma", ["38"] = "Anita Varma", ["44"] = "Daniel Flores", ["45"] = "Daniel Flores", ["46"] = "Beth Callahan", ["47"] = "Beth Callahan", ["48"] = "Amelia Kramer", ["49"] = "Amelia Kramer", ["50"] = "Doug Kramer", ["51"] = "Derrick Vaughn", ["52"] = "Derrick Vaughn", ["54"] = "Harold Brant", ["55"] = "Harold Brant", ["56"] = "Harold Brant", ["57"] = "Harold Brant", ["58"] = "Isaac Warren", ["59"] = "Isaac Warren", ["61"] = "Travis Dunn", ["62"] = "Travis Dunn", ["66"] = "Natasha Lin", ["67"] = "Natasha Lin", ["68"] = "Rudnick Wex", ["69"] = "Barry Aoki", ["70"] = "Barry Aoki", ["72"] = "David Kennedy", ["73"] = "Pan Yu", ["74"] = "Pan Yu", ["75"] = "Pan Yu", ["76"] = "Dmitri Volkov", ["77"] = "Dmitri Volkov", ["78"] = "Darla Groves", ["79"] = "Darla Groves", ["80"] = "Agnes Wells", ["81"] = "Ray Rowland", ["82"] = "Ray Rowland", ["83"] = "Ray Rowland", ["84"] = "Daniel Flores", ["85"] = "Mia Cannon", ["86"] = "Mia Cannon", ["87"] = "Elena Park", ["88"] = "Elena Park", ["89"] = "Lisa Cannon", ["90"] = "Lisa Cannon", ["91"] = "Richard McCree", ["92"] = "Richard McCree", ["93"] = "Raymond Kessler", ["94"] = "Maya Davila", ["95"] = "Rimple Urkel", ["96"] = "Dave Buster", ["97"] = "Grace Harper", ["98"] = "Evan Walker", ["99"] = "Mark Ellison", ["100"] = "Aria Romero", ["101"] = "Amiah Gutierrez", ["102"] = "Ethan Voss", ["103"] = "Tyler Brackett", ["104"] = "Tyler Brackett", ["105"] = "Bartholomew Kessler", ["106"] = "Morris Seagrave", ["107"] = "Emilia Carter", ["108"] = "Louisa Mari", ["109"] = "Louisa Mari", ["110"] = "Clyde Dawson", ["111"] = "Norbert", ["115"] = "Dilbert Hickman", ["116"] = "Aaliyah Johnson", ["117"] = "Elise Hart", ["118"] = "Keith Hargreaves", ["119"] = "Keith Hargreaves", ["120"] = "Clyde Dawson", ["121"] = "Baron Dean", ["122"] = "Net Pongsak", ["123"] = "Andal Khan", ["124"] = "Andal Khan", ["125"] = "Andal Khan", ["126"] = "Rolf Bush", ["127"] = "Diane Hays", ["128"] = "Victor Hale", ["129"] = "Victor Hale", ["130"] = "Colin Shirley", ["131"] = "Hao Chen", ["132"] = "Dylan Pike", ["133"] = "Vanessa McCree", ["146"] = "Victor Hale", ["147"] = "Clyde Dawson", ["148"] = "Randy Patel", ["149"] = "Amelia Kramer", ["150"] = "Andal Khan", ["151"] = "Aria Romero", ["152"] = "Diana Volkov", ["153"] = "Evan Walker", ["154"] = "Kevin Larson", ["155"] = "Vivien Marrow", ["156"] = "Herbert", ["157"] = "Wade Callahan", ["158"] = "Russell Crane", ["159"] = "Yasmin Carvalho", ["160"] = "Ren Takahashi", ["161"] = "Corey Bishop", ["162"] = "Corey Bishop", ["163"] = "Danielle Bennett", ["164"] = "Danielle Bennett", ["165"] = "Dimitri Markou", ["166"] = "Dimitri Markou", ["167"] = "Kelechi Okafor", ["168"] = "Margot Beaumont", ["169"] = "Mateo Benitez", ["170"] = "Mateo Benitez", ["171"] = "Oswald Snoot", ["172"] = "Toby Finch", ["173"] = "Toby Finch", ["174"] = "Youssef Morad", ["175"] = "Youssef Morad", ["176"] = "Bronte Phelps", ["177"] = "Dia Nuur", ["178"] = "Frank Park", ["179"] = "Frankie Bell", ["180"] = "Imani Green", ["181"] = "Jin Seo", ["182"] = "John Smith", ["183"] = "Labron Knight", ["184"] = "Misaki Ono", ["185"] = "Molly Foster", ["186"] = "Nico Sethi", ["187"] = "Nolan Sterling", ["188"] = "Odessa Moyo", ["189"] = "Samir Haddad", ["190"] = "Tiana King", ["191"] = "Tomas Vega", ["192"] = "Tony Marconi", ["193"] = "Trey Banks", ["194"] = "Troy Howes", ["195"] = "Yvonne Johnson", ["196"] = "Dia Nuur", ["197"] = "Odessa Moyo", ["198"] = "Tomas Vega", ["199"] = "Trey Banks", ["200"] = "Troy Howes", ["201"] = "Imani Green", ["202"] = "Bronte Phelps", ["203"] = "Frank Park", ["204"] = "Misaki Ono", ["205"] = "Tony Marconi" }; public static readonly IReadOnlyDictionary<string, string> Iconic = new Dictionary<string, string>(StringComparer.Ordinal) { ["Clyde Dawson"] = "the sheriff, nights 1, 4, 8, 9 and 13", ["Julietta Granger"] = "night 1", ["Bonnie McCree"] = "night 1, in her scrubs", ["Nathan Calloway"] = "night 1", ["Kevin Larson"] = "nights 1 and 13", ["Bartholomew Kessler"] = "night 1", ["Roger Conroy"] = "night 2", ["Norbert"] = "Pubert, night 2 and the lemonade stand", ["Ryan Holt"] = "the task force, nights 2 and 3", ["Tommy Delgado"] = "night 3, both of him", ["Colin Shirley"] = "the task force, night 3", ["Esteban Morales"] = "night 4", ["Victor Hale"] = "nights 7, 9 and 11", ["Aria Romero"] = "her double opens night 9", ["Vanessa McCree"] = "the task force, night 9", ["Vivien Marrow"] = "night 10", ["Randy Patel"] = "the escaped prisoner in the orange uniform", ["Pan Yu"] = "the dishwasher with the broken English, flagged in the 1.1.1 playtest", ["Odessa Moyo"] = "the singer who talks about herself in the third person, flagged in the 1.1.1 playtest", ["Daniel Flores"] = "the gym teacher, flagged in the 1.1.1 playtest", ["Keith Hargreaves"] = "the train conductor, flagged in the 1.1.1 playtest", ["Andal Khan"] = "the pizza chef, flagged in the 1.1.1 playtest" }; public static IReadOnlyDictionary<string, string> All => ByDialogueId; public static string Of(string dialogueId) { if (dialogueId == null || !ByDialogueId.TryGetValue(dialogueId, out var value)) { return null; } return value; } public static bool IsIconic(string owner) { if (owner != null) { return Iconic.ContainsKey(owner); } return false; } } public static class BorrowedBodies { public static IReadOnlyList<int> Strays(IReadOnlyList<string> spawnedBefore, int countBefore, IEnumerable<string> donorIds) { List<int> list = new List<int>(); if (spawnedBefore == null || donorIds == null || countBefore < 0 || countBefore >= spawnedBefore.Count) { return list; } foreach (string donorId in donorIds) { if (string.IsNullOrEmpty(donorId)) { continue; } for (int num = spawnedBefore.Count - 1; num >= countBefore; num--) { if (!list.Contains(num) && string.Equals(spawnedBefore[num], donorId, StringComparison.Ordinal)) { list.Add(num); break; } } } list.Sort((int a, int b) => b.CompareTo(a)); return list; } } public static class CardSignatures { public const int None = -1; private static readonly Lazy<HashSet<string>> Borrowed = new Lazy<HashSet<string>>(() => new HashSet<string>(DonorPortraits.ForRecords().Keys, StringComparer.Ordinal)); public static bool Signed(string record) { if (record != null) { return !Borrowed.Value.Contains(record); } return true; } public static int For(string record, int photo) { if (!Signed(record)) { return -1; } return photo; } } public interface IChannelTransport { bool SendToPlayer(int playerId, byte[] frame); bool SendToServer(byte[] frame); int Broadcast(byte[] frame); } public interface IChannelTransportState { string WhyNotLive { get; } } public sealed class ChannelCore { public const double HostSelfTestSeconds = 3.0; public const double GuestReplySeconds = 10.0; public const int MaxFrameBytes = 16384; private readonly string _modVersion; private readonly Func<uint> _configHash; private readonly Func<ContentStamp> _content; private readonly Action<OvertimeLogLevel, string> _log; private readonly bool _loudSelfCheck; private readonly Dictionary<WireMessageId, Action<int, byte[]>> _handlers = new Dictionary<WireMessageId, Action<int, byte[]>>(); private readonly HandshakeWatch _selfTest = new HandshakeWatch(3.0); private readonly HandshakeWatch _reply = new HandshakeWatch(10.0); private readonly HashSet<string> _saidThisSession = new HashSet<string>(StringComparer.Ordinal); private MessageRouter _router; private IChannelTransport _transport; private bool _sawFirstFrame; private int _gameThread = -1; public ProbeResult Probe { get; private set; } public bool IsHost { get; private set; } public int LocalPlayerId { get; private set; } = -1; public bool HostAnswered { get; private set; } public HashSet<int> GreetedPeers { get; } = new HashSet<int>(); public HashSet<int> MismatchedPeers { get; } = new HashSet<int>(); public HashSet<int> ContentMismatchedPeers { get; } = new HashSet<int>(); public event Action<int> GuestGreeted; public event Action HostGreeted; public ChannelCore(string modVersion, Func<uint> configHash, Func<ContentStamp> content, Action<OvertimeLogLevel, string> log, bool loudSelfCheck) { _modVersion = modVersion ?? string.Empty; _configHash = configHash ?? ((Func<uint>)(() => 0u)); _content = content ?? ((Func<ContentStamp>)(() => default(ContentStamp))); _log = log ?? ((Action<OvertimeLogLevel, string>)delegate { }); _loudSelfCheck = loudSelfCheck; } public void Handle(WireMessageId id, Action<int, byte[]> handler) { _handlers[id] = handler ?? throw new ArgumentNullException("handler"); if (_router != null) { RebuildRouter(); } } public void Forget(WireMessageId id) { if (_handlers.Remove(id) && _router != null) { RebuildRouter(); } } public void OnSessionReady(IChannelTransport transport, bool isHost, int localPlayerId, double now) { _transport = transport ?? throw new ArgumentNullException("transport"); IsHost = isHost; LocalPlayerId = localPlayerId; Probe = ProbeResult.Unknown; HostAnswered = false; _sawFirstFrame = false; _gameThread = Environment.CurrentManagedThreadId; RebuildRouter(); byte[] array = Wire.Encode(WireMessageId.Hello, MyHello().Encode()); if (isHost) { _selfTest.Sent(now); if (!MaySend(WireMessageId.Hello, array.Length) || !_transport.SendToPlayer(localPlayerId, array)) { _selfTest.Answered(); Fail("the hello to this host's own player could not be sent"); } } else { _reply.Sent(now); if (!MaySend(WireMessageId.Hello, array.Length) || !_transport.SendToServer(array)) { _reply.Answered(); Fail("the hello could not be sent"); } } } public void OnPlayerLeft(int playerId) { if (GreetedPeers.Remove(playerId) | MismatchedPeers.Remove(playerId) | ContentMismatchedPeers.Remove(playerId)) { _log(OvertimeLogLevel.Verbose, "player " + playerId + " left, so their hello no longer counts for that slot"); } } public void OnSessionClosed() { GreetedPeers.Clear(); MismatchedPeers.Clear(); ContentMismatchedPeers.Clear(); _saidThisSession.Clear(); _selfTest.Answered(); _reply.Answered(); Probe = ProbeResult.Unknown; HostAnswered = false; _sawFirstFrame = false; _gameThread = -1; _transport = null; _router = null; } public void Fail(string why) { if (Probe != ProbeResult.Failed) { Probe = ProbeResult.Failed; _log(OvertimeLogLevel.Warning, "self check: " + why); } } public void Deliver(int senderPlayerId, byte[] frame, int offset, int count) { if (!_sawFirstFrame) { _sawFirstFrame = true; _log(OvertimeLogLevel.Info, "first frame this session: from player " + senderPlayerId + ", " + count + " bytes, magic " + (Wire.IsOurs(frame, offset, count) ? "ok" : "missing")); } if (_router == null) { _log(OvertimeLogLevel.Warning, "a frame from player " + senderPlayerId + " arrived before the session was ready, dropped"); } else { _router.Dispatch(senderPlayerId, frame, offset, count); } } public void Tick(double now) { if (IsHost && _selfTest.Overdue(now)) { _log(OvertimeLogLevel.Warning, "self test: the hello this host sent to its own player did not come back within " + 3.0 + " s, so Fusion is not delivering on the reliable path; nothing of Overtime's will cross to a guest this session"); } if (!IsHost && _reply.Overdue(now)) { _log(OvertimeLogLevel.Warning, "no answer to our hello within " + 10.0 + " s: the host never answered on Overtime's channel; host settings (late join, story variety, skip tutorials, scares, new content and the rest marked [Host]) are the host's, whatever yours say. Either the host has no Overtime, or its channel is down (its log says which)"); } } public bool SendToPlayer(int playerId, WireMessageId id, byte[] payload) { if (MaySend(id, FrameLength(payload))) { return _transport.SendToPlayer(playerId, Wire.Encode(id, payload)); } return false; } public bool SendToServer(WireMessageId id, byte[] payload) { if (MaySend(id, FrameLength(payload))) { return _transport.SendToServer(Wire.Encode(id, payload)); } return false; } public int Broadcast(WireMessageId id, byte[] payload) { if (!MaySend(id, FrameLength(payload))) { return 0; } return _transport.Broadcast(Wire.Encode(id, payload)); } private static int FrameLength(byte[] payload) { return 6 + ((payload != null) ? payload.Length : 0); } private bool MaySend(WireMessageId id, int frameLength) { if (_transport == null) { return false; } string text = null; if (Environment.CurrentManagedThreadId != _gameThread) { text = "a send came from off the game's main thread"; } else if (_transport is IChannelTransportState { WhyNotLive: { } whyNotLive }) { text = whyNotLive; } else if (frameLength > 16384) { text = "a frame of " + frameLength + " bytes is over the " + 16384 + " byte cap"; } if (text == null) { return true; } if (_saidThisSession.Add("refused: " + ((frameLength > 16384) ? "size" : text))) { _log(OvertimeLogLevel.Warning, "channel send refused (" + id.ToString() + "): " + text + "; nothing was sent"); } return false; } public string WhyPackPeopleAreHeld(IEnumerable<int> activeGuestIds, Func<int, string> nameOf = null) { return PackPeopleGate.WhyHeld(activeGuestIds, GreetedPeers, MismatchedPeers, ContentMismatchedPeers, nameOf); } public int WithoutOvertime(IEnumerable<int> activeGuestIds) { return PackPeopleGate.WithoutOvertime(activeGuestIds, GreetedPeers, MismatchedPeers); } public PackHold PackHoldOn(IEnumerable<int> activeGuestIds) { return PackPeopleGate.Holding(activeGuestIds, GreetedPeers, MismatchedPeers, ContentMismatchedPeers); } private Hello MyHello() { return new Hello(_modVersion, _configHash(), IsHost, _content()); } private void RebuildRouter() { _router = new MessageRouter(IsHost, delegate(string message) { _log(OvertimeLogLevel.Warning, message); }); _router.Handle(WireMessageId.Hello, OnHello); foreach (KeyValuePair<WireMessageId, Action<int, byte[]>> handler in _handlers) { _router.Handle(handler.Key, handler.Value); } } private void OnHello(int senderPlayerId, byte[] payload) { if (!Hello.TryDecode(payload, out var hello)) { _log(OvertimeLogLevel.Warning, "dropped a malformed hello from player " + senderPlayerId); return; } if (hello.FromHost && IsHost) { _selfTest.Answered(); Pass(); return; } Pass(); Hello mine = MyHello(); HelloVerdict helloVerdict = HelloCheck.Compare(mine, hello); string text = (IsHost ? ("player " + senderPlayerId) : "the host"); switch (helloVerdict) { case HelloVerdict.VersionMismatch: ContentMismatchedPeers.Remove(senderPlayerId); if (MismatchedPeers.Add(senderPlayerId)) { _log(OvertimeLogLevel.Warning, text + " is on Overtime " + hello.ModVersion + " and this machine is on " + _modVersion + ", so the game runs as it shipped between us"); } break; case HelloVerdict.ContentMismatch: MismatchedPeers.Remove(senderPlayerId); if (ContentMismatchedPeers.Add(senderPlayerId)) { _log(OvertimeLogLevel.Warning, text + " carries content " + hello.Content.ToString() + " and this machine carries " + mine.Content.ToString() + (IsHost ? ", so the pack's people stay off the list while they are here" : ", so the host is not adding the pack's people tonight")); } break; case HelloVerdict.SettingsDiffer: MismatchedPeers.Remove(senderPlayerId); ContentMismatchedPeers.Remove(senderPlayerId); _log(OvertimeLogLevel.Verbose, text + " has different host settings, the host's values win"); break; default: MismatchedPeers.Remove(senderPlayerId); ContentMismatchedPeers.Remove(senderPlayerId); _log(OvertimeLogLevel.Verbose, text + " matches on version, content and settings"); break; } if (hello.FromHost) { HostAnswered = true; _reply.Answered(); if (helloVerdict != HelloVerdict.VersionMismatch) { this.HostGreeted?.Invoke(); } return; } if (!IsHost) { _log(OvertimeLogLevel.Warning, "a guest hello from player " + senderPlayerId + " reached this guest, which should not be possible in host mode; dropped"); return; } byte[] array = Wire.Encode(WireMessageId.Hello, mine.Encode()); if (!MaySend(WireMessageId.Hello, array.Length) || !_transport.SendToPlayer(senderPlayerId, array)) { _log(OvertimeLogLevel.Warning, "could not answer player " + senderPlayerId + "'s hello: the transport refused it, so they are not in this session's player list"); } else if (helloVerdict != HelloVerdict.VersionMismatch) { GreetedPeers.Add(senderPlayerId); this.GuestGreeted?.Invoke(senderPlayerId); } } private void Pass() { if (Probe != ProbeResult.Passed) { Probe = ProbeResult.Passed; if (_saidThisSession.Add("live")) { _log(OvertimeLogLevel.Warning, _loudSelfCheck ? "self check: the channel is live, a message went end to end" : "the channel is live"); } } } } public enum ChannelKind { None, Reliable, RpcPiggyback } public enum ProbeResult { Unknown, Passed, Failed } public static class ChannelSelector { public static ChannelKind Choose(ProbeResult reliable, bool piggybackAvailable) { switch (reliable) { case ProbeResult.Passed: return ChannelKind.Reliable; case ProbeResult.Failed: if (!piggybackAvailable) { return ChannelKind.None; } return ChannelKind.RpcPiggyback; default: return ChannelKind.Reliable; } } } public static class ChaosDial { public const int LeastHuntBonus = 4; public const int MostHuntBonus = 10; public const int MostHuntPoints = 60; public const double StrangerChance = 0.8; public const int SurpriseBudget = 4; public const int SurpriseGapSeconds = 60; public const int SurpriseWarmupSeconds = 60; public const int TroublemakerWave = 14; public const int MostStalkersANight = 3; public const double LatestStalkerShare = 0.9; public static int HuntBonus(int night) { return Math.Min(10, 4 + Math.Max(0, night - 1) / 3); } public static int HuntBudget(int night, int letThrough) { return Math.Min(60, EndlessHunt.Budget(night, letThrough) + HuntBonus(night)); } public static double StalkerChance(int night, bool endless, int firstHuntNight, int multiplierPercent) { double num = Stalkers.Chance(night, endless, firstHuntNight, multiplierPercent); if (num <= 0.0) { return 0.0; } double num2 = (double)Math.Min(multiplierPercent, 300) / 300.0; return Math.Max(num, 0.6 * num2); } public static double StalkerAgain(ulong nightSeed, int cameSoFar, double nowShare) { if (cameSoFar >= 3) { return -1.0; } double num = (double)new SeededRandom(StorySeed.Stream(nightSeed, "chaos stalker " + cameSoFar)).Next(1000000) / 1000000.0; double num2 = nowShare + 0.08 + 0.1 * num; if (!(num2 < 0.9)) { return -1.0; } return num2; } public static double TurnChance(int night, bool endless, int firstHuntNight, int multiplierPercent, int mostSightings) { return HarmlessTurns.Chance(night, endless, firstHuntNight, multiplierPercent); } public static IReadOnlyList<int> HideEmptyNuisances(IReadOnlyList<string> animations, IReadOnlyCollection<int> busy) { List<int> list = new List<int>(); if (animations == null) { return list; } int num = 0; for (int i = 0; i < animations.Count; i++) { bool flag = busy != null && Contains(busy, i); if (string.IsNullOrEmpty(animations[i])) { if (!flag) { list.Add(i); } } else if (!flag) { num++; } } if (num == 0) { list.Clear(); } return list; } public static int SafeNuisanceIndex(int current, int browsing, int nuisances) { if (((current + 1 < browsing) ? (current + 1) : 0) >= nuisances) { return -1; } return current; } private static bool Contains(IReadOnlyCollection<int> list, int value) { foreach (int item in list) { if (item == value) { return true; } } return false; } } public enum ChaosRule { Switch, Scale, ScaleDown, Ladder } public sealed class ChaosSettingRow { public string Section { get; } public string Key { get; } public ChaosRule Rule { get; } public string Default { get; } public string Chaos { get; } public bool Fun { get; } public string Why { get; } public IReadOnlyList<string> Ladder { get; } public ChaosSettingRow(string section, string key, ChaosRule rule, string byDefault, string chaos, bool fun, string why, IReadOnlyList<string> ladder = null) { Section = section; Key = key; Rule = rule; Default = byDefault; Chaos = chaos; Fun = fun; Why = why; Ladder = ladder; } } public static class ChaosSettings { private static readonly string[] ScareLadder = new string[4] { "Off", "Vanilla", "More", "Much More" }; private static readonly string[] RoadLadder = new string[3] { "Night 1 Only", "Sometimes", "Often" }; private static readonly string[] MimicLadder = new string[4] { "Off", "Rare", "Sometimes", "Often" }; public static readonly IReadOnlyList<ChaosSettingRow> Rows = new ChaosSettingRow[29] { new ChaosSettingRow("00 Overtime", "Scares", ChaosRule.Ladder, "More", "Much More", fun: false, "comfort: Off keeps the extra scares off, Vanilla goes to More", ScareLadder), new ChaosSettingRow("00 Overtime", "Mimic", ChaosRule.Ladder, "Sometimes", "Often", fun: false, "comfort: Off keeps the voices off, Rare goes to Sometimes", MimicLadder), new ChaosSettingRow("00 Overtime", "Story Variety", ChaosRule.Switch, "Auto", "Full", fun: true, "fun: every night reads Full, which the doors and the roadside car need in endless"), new ChaosSettingRow("40 Scares", "Night Scare Budget", ChaosRule.Scale, "2", "10", fun: false, "comfort: 0 keeps the extra scares off"), new ChaosSettingRow("40 Scares", "Minimum Gap Seconds", ChaosRule.ScaleDown, "120", "30", fun: false, "comfort: the gap between two scares, a longer one stays longer"), new ChaosSettingRow("40 Scares", "Scale Difficulty With Players", ChaosRule.Switch, "true", "true", fun: false, "comfort: bigger crews only get a bigger hunt when it is on"), new ChaosSettingRow("40 Scares", "Harmless Can Turn", ChaosRule.Switch, "true", "true", fun: false, "comfort: a real threat, Off keeps sightings harmless"), new ChaosSettingRow("40 Scares", "Harmless Turn Odds", ChaosRule.Scale, "100", "300", fun: false, "comfort: 0 never turns"), new ChaosSettingRow("40 Scares", "Stalkers", ChaosRule.Switch, "true", "true", fun: false, "comfort: a real threat, Off keeps the dentist away"), new ChaosSettingRow("40 Scares", "Stalker Odds", ChaosRule.Scale, "100", "300", fun: false, "comfort: 0 never stalks"), new ChaosSettingRow("45 Story Variety", "Set Pieces", ChaosRule.Switch, "true", "true", fun: true, "fun: the robbery and the inspection in endless"), new ChaosSettingRow("45 Story Variety", "Roadside Choices", ChaosRule.Switch, "true", "true", fun: true, "fun: the car is not always the trap"), new ChaosSettingRow("45 Story Variety", "Roadside Calls", ChaosRule.Ladder, "Sometimes", "Often", fun: true, "fun: Night 1 Only counts as off and goes to Often", RoadLadder), new ChaosSettingRow("45 Story Variety", "Open Doors", ChaosRule.Switch, "true", "true", fun: false, "comfort: an open door can let a real threat in"), new ChaosSettingRow("45 Story Variety", "Open Door Strength", ChaosRule.Scale, "100", "300", fun: false, "comfort: the door clock runs three times as fast at the top, a slower one stays slower"), new ChaosSettingRow("49 Endgame", "Endless Post Game", ChaosRule.Switch, "true", "true", fun: true, "fun: calls, returning people and milestones"), new ChaosSettingRow("49 Endgame", "Milestone Every", ChaosRule.ScaleDown, "5", "2", fun: true, "fun: a milestone in every two nights, 0 counts as off and goes to 2"), new ChaosSettingRow("49 Endgame", "Endless Escalation", ChaosRule.Switch, "true", "true", fun: true, "fun: stranger nights"), new ChaosSettingRow("48 Store Life", "Manager Orders", ChaosRule.Switch, "true", "true", fun: true, "fun: the boss's orders"), new ChaosSettingRow("48 Store Life", "Orders Per Night", ChaosRule.Scale, "2", "2", fun: true, "fun: two orders a night, 0 counts as off"), new ChaosSettingRow("48 Store Life", "Store Remembers", ChaosRule.Switch, "true", "true", fun: true, "fun: the store shows what happened"), new ChaosSettingRow("48 Store Life", "Store Changes Per Night", ChaosRule.Scale, "6", "10", fun: true, "fun: up to ten things put up a night"), new ChaosSettingRow("50 Humour", "Cow Behaviour", ChaosRule.Switch, "true", "true", fun: true, "fun: the cow"), new ChaosSettingRow("50 Humour", "Wandering Customers", ChaosRule.Switch, "true", "true", fun: true, "fun: customers who forget why they came in"), new ChaosSettingRow("50 Humour", "Odd Moments", ChaosRule.Switch, "true", "true", fun: true, "fun: the odd moments"), new ChaosSettingRow("50 Humour", "Spin Wheel Surprises", ChaosRule.Switch, "true", "true", fun: true, "fun: the wheel's second coin"), new ChaosSettingRow("60 Content", "Extra Customers", ChaosRule.Switch, "true", "true", fun: true, "fun: new people in the queue"), new ChaosSettingRow("60 Content", "Extra Customers Per Night", ChaosRule.Scale, "4", "8", fun: true, "fun: up to eight new people a night, 0 counts as off"), new ChaosSettingRow("60 Content", "Random Event Roller", ChaosRule.Switch, "true", "true", fun: true, "fun: the old beats come back") }; private static readonly Dictionary<string, ChaosSettingRow> ByName = Index(); public static string Adjust(string section, string key, string raw) { if (raw == null || !ByName.TryGetValue(section + " / " + key, out var value)) { return raw; } return value.Rule switch { ChaosRule.Switch => Switch(value, raw), ChaosRule.Scale => Scale(value, raw, lessIsMore: false), ChaosRule.ScaleDown => Scale(value, raw, lessIsMore: true), _ => Ladder(value, raw), }; } public static bool Names(string section, string key) { return ByName.ContainsKey(section + " / " + key); } private static Dictionary<string, ChaosSettingRow> Index() { Dictionary<string, ChaosSettingRow> dictionary = new Dictionary<string, ChaosSettingRow>(StringComparer.Ordinal); foreach (ChaosSettingRow row in Rows) { dictionary[row.Section + " / " + row.Key] = row; } return dictionary; } private static string Switch(ChaosSettingRow row, string raw) { if (bool.TryParse(raw, out var result)) { if (!result && !row.Fun) { return "false"; } return "true"; } if (!row.Fun) { return raw; } return row.Chaos; } private static string Scale(ChaosSettingRow row, string raw, bool lessIsMore) { if (!int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return raw; } ConfigEntrySpec configEntrySpec = ConfigSchema.Find(row.Section, row.Key); double? num = configEntrySpec?.Min; int num2; if (num.HasValue) { double valueOrDefault = num.GetValueOrDefault(); num2 = (int)valueOrDefault; } else { num2 = 0; } int val = num2; num = configEntrySpec?.Max; int num3; if (num.HasValue) { double valueOrDefault2 = num.GetValueOrDefault(); num3 = (int)valueOrDefault2; } else { num3 = int.MaxValue; } int val2 = num3; int num4 = int.Parse(row.Default, CultureInfo.InvariantCulture); int num5 = int.Parse(row.Chaos, CultureInfo.InvariantCulture); if (result == 0) { if (!row.Fun) { return raw; } return row.Chaos; } double num6 = (lessIsMore ? ((double)result / (double)num4) : Math.Min(1.0, (double)result / (double)num4)); if (lessIsMore) { num6 = Math.Max(1.0, num6); } int val3 = (int)Math.Round((double)num5 * num6, MidpointRounding.AwayFromZero); val3 = (lessIsMore ? Math.Min(result, val3) : Math.Max(result, val3)); return Math.Max(val, Math.Min(val2, val3)).ToString(CultureInfo.InvariantCulture); } private static string Ladder(ChaosSettingRow row, string raw) { int num = IndexOf(row.Ladder, raw); if (num < 0) { return raw; } int num2 = IndexOf(row.Ladder, row.Default); int num3 = IndexOf(row.Ladder, row.Chaos); if (num == 0) { if (!row.Fun) { return raw; } return row.Chaos; } int index = Math.Min(num3, Math.Max(1, num3 - Math.Max(0, num2 - num))); return row.Ladder[index]; } private static int IndexOf(IReadOnlyList<string> list, string value) { for (int i = 0; i < list.Count; i++) { if (string.Equals(list[i], value, StringComparison.OrdinalIgnoreCase)) { return i; } } return -1; } } public static class ChaosSlot { public const int EndlessMode = 1; public const int Marked = 1; public const string Suffix = "OvertimeChaos"; public const string SlotLabelKey = "Chaos Mode Slot"; public static string Key(int slot) { return slot.ToString(CultureInfo.InvariantCulture) + "OvertimeChaos"; } public static bool IsChaos(int gameMode, in