Decompiled source of ShiftSlip v1.0.1

BepInEx/plugins/ShiftSlip.dll

Decompiled 19 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CargoWick")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Local salvage receipts for R.E.P.O.")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ShiftSlip")]
[assembly: AssemblyTitle("ShiftSlip")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ShiftSlip
{
	internal static class GameHooks
	{
		private readonly struct LossState
		{
			internal Shift Shift { get; }

			internal ValuableObject Item { get; }

			internal int Value { get; }

			internal int Key { get; }

			internal string Label { get; }

			internal LossState(Shift shift, ValuableObject item)
			{
				Shift = shift;
				Item = item;
				Value = Dollars(dollarValue.Invoke(item));
				Key = ((Object)item).GetInstanceID();
				Label = ReceiptText.ItemName(((Object)item).name);
			}
		}

		private readonly struct BankState
		{
			internal Shift Shift { get; }

			internal int Before { get; }

			internal BankState(Shift shift, int before)
			{
				Shift = shift;
				Before = before;
			}
		}

		private static FieldRef<ValuableObject, float> dollarValue;

		private static FieldRef<ValuableObject, bool> committed;

		private static FieldRef<PlayerAvatar, bool> isDown;

		internal static void Install(Harmony harmony)
		{
			dollarValue = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueCurrent");
			committed = AccessTools.FieldRefAccess<ValuableObject, bool>("committedToExtraction");
			isDown = AccessTools.FieldRefAccess<PlayerAvatar, bool>("deadSet");
			Patch<PhysGrabObjectImpactDetector>(harmony, "BreakRPC", "DamageBefore", "DamageAfter");
			Patch<PhysGrabObjectImpactDetector>(harmony, "DestroyObjectRPC", "ShatterBefore", "ShatterAfter");
			Patch<PlayerAvatar>(harmony, "PlayerDeathRPC", "CrewBefore", "CrewAfter");
			Patch<PlayerAvatar>(harmony, "ReviveRPC", "CrewBefore", "CrewAfter");
			Patch<PunManager>(harmony, "SetRunStatSet", "BankBefore", "BankAfter");
			Patch<PunManager>(harmony, "SetRunStatRPC", "BankBefore", "BankAfter");
			Patch<RunManager>(harmony, "ChangeLevel", "LevelBefore", "LevelAfter");
			Patch<RunManager>(harmony, "UpdateLevel", "LevelBefore", "RemoteLevelAfter");
		}

		private static void Patch<T>(Harmony harmony, string target, string prefix, string postfix)
		{
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_005e: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(T), target, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new MissingMethodException(typeof(T).Name, target);
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GameHooks), prefix, (Type[])null), new HarmonyMethod(typeof(GameHooks), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static int Dollars(float value)
		{
			if (!float.IsNaN(value) && !(value <= 0f))
			{
				return (int)Math.Min(2147483647.0, value);
			}
			return 0;
		}

		private static LossState CaptureLoss(PhysGrabObjectImpactDetector detector)
		{
			Shift shift = Plugin.Instance?.Active;
			if (shift == null)
			{
				return default(LossState);
			}
			ValuableObject component = ((Component)detector).GetComponent<ValuableObject>();
			if (!Object.op_Implicit((Object)(object)component) || committed.Invoke(component))
			{
				return default(LossState);
			}
			return new LossState(shift, component);
		}

		private static void DamageBefore(PhysGrabObjectImpactDetector __instance, bool __3, out LossState __state)
		{
			__state = (__3 ? CaptureLoss(__instance) : default(LossState));
			if (__state.Shift != null)
			{
				PhysGrabObject component = ((Component)__instance).GetComponent<PhysGrabObject>();
				if (!Object.op_Implicit((Object)(object)component) || component.dead)
				{
					__state = default(LossState);
				}
			}
		}

		private static void DamageAfter(LossState __state)
		{
			if (__state.Shift != null)
			{
				int amount = __state.Value - Dollars(dollarValue.Invoke(__state.Item));
				__state.Shift.Loss(__state.Key, __state.Label, amount, shatter: false, Plugin.Now);
			}
		}

		private static void ShatterBefore(PhysGrabObjectImpactDetector __instance, PhotonMessageInfo __1, out LossState __state)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			bool flag = !SemiFunc.IsMultiplayer() || __1.Sender == PhotonNetwork.MasterClient;
			__state = (flag ? CaptureLoss(__instance) : default(LossState));
		}

		private static void ShatterAfter(PhysGrabObjectImpactDetector __instance, LossState __state)
		{
			if (__state.Shift != null)
			{
				PhysGrabObject component = ((Component)__instance).GetComponent<PhysGrabObject>();
				if (Object.op_Implicit((Object)(object)component) && component.dead)
				{
					__state.Shift.Loss(__state.Key, __state.Label, __state.Value, shatter: true, Plugin.Now);
				}
			}
		}

		private static void CrewBefore(PlayerAvatar __instance, out bool __state)
		{
			__state = isDown.Invoke(__instance);
		}

		private static void CrewAfter(PlayerAvatar __instance, bool __state)
		{
			Plugin.Instance?.Active?.Crew(((Object)__instance).GetInstanceID(), isDown.Invoke(__instance), __state, Plugin.Now);
		}

		private static void BankBefore(string __0, out BankState __state)
		{
			Shift shift = Plugin.Instance?.Active;
			__state = ((__0 == "totalHaul" && shift != null && Object.op_Implicit((Object)(object)StatsManager.instance)) ? new BankState(shift, SemiFunc.StatGetRunTotalHaul()) : default(BankState));
		}

		private static void BankAfter(BankState __state)
		{
			if (__state.Shift != null)
			{
				int amount = Shift.CreditDollars(__state.Before, SemiFunc.StatGetRunTotalHaul());
				__state.Shift.Bank(amount, Plugin.Now);
			}
		}

		private static void LevelBefore(out Shift __state)
		{
			__state = Plugin.Instance?.Active;
		}

		private static void LevelAfter(RunManager __instance, bool __0, bool __1, Shift __state)
		{
			Plugin instance = Plugin.Instance;
			if (__state != null && instance?.Active == __state && SemiFunc.IsMasterClientOrSingleplayer())
			{
				if (__1)
				{
					instance.Finish(ShiftEnd.Wiped);
				}
				else if (__instance.levelsCompleted >= __state.Floor && __0)
				{
					instance.Finish(ShiftEnd.Cleared);
				}
				else
				{
					instance.Finish(ShiftEnd.Interrupted);
				}
			}
		}

		private static void RemoteLevelAfter(RunManager __instance, int __1, bool __2, Shift __state)
		{
			Plugin instance = Plugin.Instance;
			if (__state != null && instance?.Active == __state)
			{
				bool enteredArena = SemiFunc.IsLevelArena(__instance.levelCurrent);
				instance.Finish(Shift.RemoteOutcome(__state.Floor, __1, __2, enteredArena));
			}
		}
	}
	[BepInPlugin("com.cargowick.shiftslip", "ShiftSlip", "1.0.1")]
	[BepInProcess("REPO.exe")]
	public sealed class Plugin : BaseUnityPlugin
	{
		internal const string Id = "com.cargowick.shiftslip";

		private readonly List<Shift> history = new List<Shift>();

		private Harmony harmony;

		private ConfigEntry<Key> toggleKey;

		private ConfigEntry<Key> copyKey;

		private ConfigEntry<Key> imageKey;

		private ConfigEntry<bool> autoOpen;

		private LevelGenerator lastGenerator;

		private Level activeLevel;

		private int receiptIndex;

		private bool visible;

		private string message;

		private double messageEnds;

		private Texture2D card;

		private Shift rendered;

		private int renderedRevision;

		private int renderedSeconds;

		private GUIStyle footer;

		internal static Plugin Instance { get; private set; }

		internal static double Now => Time.realtimeSinceStartupAsDouble;

		internal Shift Active { get; private set; }

		private void Awake()
		{
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			toggleKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "Toggle", (Key)101, "Show or hide the receipt.");
			copyKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "CopyText", (Key)102, "Copy the displayed receipt to the clipboard.");
			imageKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "SaveImage", (Key)103, "Save the displayed receipt as a PNG.");
			autoOpen = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "OpenAfterShift", false, "Show a receipt automatically after a cleared or failed floor.");
			Instance = this;
			harmony = new Harmony("com.cargowick.shiftslip");
			try
			{
				GameHooks.Install(harmony);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"ShiftSlip is ready.");
			}
			catch (Exception ex)
			{
				harmony.UnpatchSelf();
				Instance = null;
				((Behaviour)this).enabled = false;
				((BaseUnityPlugin)this).Logger.LogError((object)("ShiftSlip could not attach to this R.E.P.O. build. " + ex));
			}
		}

		private void Update()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			ObserveFloor();
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return;
			}
			if (Pressed(current, toggleKey.Value))
			{
				visible = !visible;
				receiptIndex = 0;
			}
			if (!visible)
			{
				return;
			}
			int val = Math.Max(0, history.Count - ((Active == null) ? 1 : 0));
			if (Pressed(current, (Key)67))
			{
				receiptIndex = Math.Min(val, receiptIndex + 1);
			}
			if (Pressed(current, (Key)66))
			{
				receiptIndex = Math.Max(0, receiptIndex - 1);
			}
			Shift shift = Selected();
			if (shift != null)
			{
				shift.Tick(Now);
				if (copyKey.Value != toggleKey.Value && Pressed(current, copyKey.Value))
				{
					GUIUtility.systemCopyBuffer = ReceiptText.Format(shift);
					Tell("Copied receipt text.");
				}
				if (imageKey.Value != toggleKey.Value && imageKey.Value != copyKey.Value && Pressed(current, imageKey.Value))
				{
					Save(shift);
				}
				if (rendered != shift || renderedRevision != shift.Revision || renderedSeconds != shift.Seconds)
				{
					Refresh(shift);
				}
			}
		}

		private static bool Pressed(Keyboard keyboard, Key key)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if ((int)key > 0 && (int)key < 110)
			{
				return ((ButtonControl)keyboard[key]).wasPressedThisFrame;
			}
			return false;
		}

		internal void ObserveFloor()
		{
			RunManager instance = RunManager.instance;
			LevelGenerator instance2 = LevelGenerator.Instance;
			if (Active != null && (!Object.op_Implicit((Object)(object)instance) || (Object)(object)instance.levelCurrent != (Object)(object)activeLevel || (Object.op_Implicit((Object)(object)instance2) && (Object)(object)instance2 != (Object)(object)lastGenerator)))
			{
				Finish(ShiftEnd.Interrupted);
			}
			if (Active == null && Object.op_Implicit((Object)(object)instance) && Object.op_Implicit((Object)(object)instance2) && instance2.Generated && !((Object)(object)instance2 == (Object)(object)lastGenerator))
			{
				Level levelCurrent = instance.levelCurrent;
				if (Object.op_Implicit((Object)(object)levelCurrent) && !((Object)(object)instance2.Level != (Object)(object)levelCurrent) && !((Object)(object)levelCurrent == (Object)(object)instance.levelRecording) && SemiFunc.RunIsLevel())
				{
					lastGenerator = instance2;
					activeLevel = levelCurrent;
					Active = new Shift(Math.Max(1, instance.levelsCompleted + 1), levelCurrent.NarrativeName, Now);
					receiptIndex = 0;
				}
			}
		}

		internal void Finish(ShiftEnd end)
		{
			if (Active != null)
			{
				Active.Close(end, Now);
				history.Insert(0, Active);
				if (history.Count > 8)
				{
					history.RemoveAt(history.Count - 1);
				}
				Active = null;
				activeLevel = null;
				receiptIndex = 0;
				if (autoOpen.Value && end != ShiftEnd.Interrupted)
				{
					visible = true;
				}
			}
		}

		private Shift Selected()
		{
			if (receiptIndex == 0 && Active != null)
			{
				return Active;
			}
			int num = receiptIndex - ((Active != null) ? 1 : 0);
			if (num < 0 || num >= history.Count)
			{
				return null;
			}
			return history[num];
		}

		private void Refresh(Shift shift)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			byte[] array = ReceiptArt.Draw(shift);
			int num = 2880;
			byte[] array2 = new byte[num];
			for (int i = 0; i < 352; i++)
			{
				int num2 = i * num;
				int num3 = (703 - i) * num;
				Buffer.BlockCopy(array, num2, array2, 0, num);
				Buffer.BlockCopy(array, num3, array, num2, num);
				Buffer.BlockCopy(array2, 0, array, num3, num);
			}
			if (!Object.op_Implicit((Object)(object)card))
			{
				card = new Texture2D(960, 704, (TextureFormat)3, false);
				((Texture)card).wrapMode = (TextureWrapMode)1;
				((Texture)card).filterMode = (FilterMode)1;
			}
			card.LoadRawTextureData(array);
			card.Apply(false, false);
			rendered = shift;
			renderedRevision = shift.Revision;
			renderedSeconds = shift.Seconds;
		}

		private void Save(Shift shift)
		{
			try
			{
				string text = Path.Combine(Paths.BepInExRootPath, "ShiftSlip");
				Directory.CreateDirectory(text);
				string path = $"shift-{shift.Floor:00}-{Guid.NewGuid():N}.png";
				byte[] array = ReceiptArt.Png(ReceiptArt.Draw(shift), 960, 704);
				using (FileStream fileStream = new FileStream(Path.Combine(text, path), FileMode.CreateNew, FileAccess.Write))
				{
					fileStream.Write(array, 0, array.Length);
				}
				Tell("Saved to BepInEx/ShiftSlip/");
			}
			catch (IOException)
			{
				Tell("Could not save the receipt.");
			}
			catch (UnauthorizedAccessException)
			{
				Tell("The receipt folder is read-only.");
			}
		}

		private void Tell(string text)
		{
			message = text;
			messageEnds = Now + 3.5;
		}

		private void OnGUI()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Invalid comparison between Unknown and I4
			//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_0035: 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_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Unknown result type (might be due to invalid IL or missing references)
			if (!visible || (int)Event.current.type != 7)
			{
				return;
			}
			if (footer == null)
			{
				GUIStyle val = new GUIStyle(GUI.skin.box)
				{
					alignment = (TextAnchor)4,
					fontSize = 15
				};
				val.normal.textColor = Color.white;
				val.wordWrap = true;
				footer = val;
			}
			float num = Mathf.Min((float)Screen.width * 0.92f / 960f, (float)Screen.height * 0.84f / 754f);
			float num2 = 960f * num;
			float num3 = 704f * num;
			float num4 = ((float)Screen.width - num2) / 2f;
			float num5 = ((float)Screen.height - num3 - 48f) / 2f;
			Shift shift = Selected();
			if (shift == null)
			{
				GUI.Box(new Rect(num4, num5 + num3 / 2f, num2, 52f), $"No shift recorded yet. Start a salvage floor. [{toggleKey.Value} to close]", footer);
				return;
			}
			if (Object.op_Implicit((Object)(object)card) && rendered == shift)
			{
				GUI.DrawTexture(new Rect(num4, num5, num2, num3), (Texture)(object)card);
			}
			string text = $"[{toggleKey.Value}] Close    [{copyKey.Value}] Copy text    [{imageKey.Value}] Save PNG";
			if (history.Count > 1 || (history.Count > 0 && Active != null))
			{
				text += "    [PgUp / PgDn] History";
			}
			string text2 = ((Now < messageEnds) ? message : text);
			GUI.Box(new Rect(num4, num5 + num3 + 5f, num2, 43f), text2, footer);
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			if (Object.op_Implicit((Object)(object)card))
			{
				Object.Destroy((Object)(object)card);
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}
	}
	internal static class ReceiptArt
	{
		private sealed class Canvas
		{
			private readonly int width;

			internal byte[] Pixels { get; }

			internal Canvas(int width, int height)
			{
				this.width = width;
				Pixels = new byte[width * height * 3];
			}

			internal void Box(int x, int y, int w, int h, int color)
			{
				for (int i = y; i < y + h; i++)
				{
					int num = (i * width + x) * 3;
					for (int j = 0; j < w; j++)
					{
						Pixels[num++] = (byte)(color >> 16);
						Pixels[num++] = (byte)(color >> 8);
						Pixels[num++] = (byte)color;
					}
				}
			}

			internal void Center(int x, int y, string value, int scale, int color)
			{
				Text(x - (value.Length * 6 - 1) * scale / 2, y, value, scale, color);
			}

			internal void Text(int x, int y, string value, int scale, int color, int max = 100, bool right = false)
			{
				StringBuilder stringBuilder = new StringBuilder(value.Length);
				string text = value.Normalize(NormalizationForm.FormD).ToUpperInvariant();
				foreach (char c in text)
				{
					if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
					{
						stringBuilder.Append((c == ' ' || Glyphs.ContainsKey(c)) ? c : '?');
					}
				}
				if (stringBuilder.Length > max)
				{
					stringBuilder.Length = max - 3;
					stringBuilder.Append("...");
				}
				if (right)
				{
					x -= (stringBuilder.Length * 6 - 1) * scale;
				}
				text = stringBuilder.ToString();
				foreach (char key in text)
				{
					if (Glyphs.TryGetValue(key, out var value2))
					{
						for (int j = 0; j < 7; j++)
						{
							for (int k = 0; k < 5; k++)
							{
								if ((value2[j] & (1 << 4 - k)) != 0)
								{
									Box(x + k * scale, y + j * scale, scale, scale, color);
								}
							}
						}
					}
					x += 6 * scale;
				}
			}
		}

		internal const int Width = 960;

		internal const int Height = 704;

		private const int Ink = 1320226;

		private const int Paper = 15722705;

		private const int Muted = 5464667;

		private const int Rule = 13485485;

		private const int Moss = 1139273;

		private const int Rust = 10435106;

		private const int Signal = 15967324;

		private static readonly uint[] CrcTable = MakeCrcTable();

		private static readonly Dictionary<char, byte[]> Glyphs = ReadGlyphs();

		internal static byte[] Draw(Shift shift)
		{
			Canvas canvas = new Canvas(960, 704);
			canvas.Box(0, 0, 960, 704, 1055771);
			for (int i = 19; i < 960; i += 24)
			{
				for (int j = 18; j < 704; j += 24)
				{
					canvas.Box(i, j, 2, 2, 2899256);
				}
			}
			canvas.Box(55, 40, 858, 630, 660242);
			canvas.Box(48, 34, 858, 630, 15722705);
			for (int k = 48; k < 906; k += 12)
			{
				canvas.Box(k, 662, 6, 5, 15722705);
			}
			canvas.Box(48, 34, 858, 122, 1320226);
			canvas.Box(48, 34, 858, 5, 15967324);
			Mark(canvas, 74, 63, 2, 15967324, 1320226);
			canvas.Text(132, 59, "SHIFTSLIP", 7, 15722705);
			canvas.Text(134, 122, "SALVAGE INCIDENT RECEIPT", 2, 12175803);
			canvas.Box(702, 65, 178, 34, 15967324);
			canvas.Center(791, 75, ReceiptText.Status(shift.End), 2, 1320226);
			canvas.Text(880, 120, "SHIFT " + shift.Floor.ToString("00", CultureInfo.InvariantCulture) + " / " + ReceiptText.Clock(shift.Seconds), 2, 15722705, 100, right: true);
			canvas.Text(76, 178, shift.Site, 3, 1320226, 44);
			canvas.Box(76, 213, 804, 2, 13485485);
			Metric(canvas, 76, "VALUE BANKED", ReceiptText.Money(shift.Banked), 1139273);
			Metric(canvas, 283, "VALUE LOST", ReceiptText.Money(shift.Lost), 10435106);
			Metric(canvas, 490, "SHATTERED", Count(shift.Shattered), 1320226);
			Metric(canvas, 697, "DOWN / REVIVED", Count(shift.Downs) + " / " + Count(shift.Revivals), 1320226);
			canvas.Box(76, 305, 804, 42, 14997947);
			canvas.Box(76, 305, 5, 42, 10435106);
			canvas.Text(93, 319, "BIGGEST LOSS", 2, 10435106);
			if (shift.BiggestLoss == null)
			{
				canvas.Text(279, 319, "NO VALUE LOST", 2, 5464667);
			}
			else
			{
				canvas.Text(279, 319, shift.BiggestLoss.Label, 2, 1320226, 35);
				canvas.Text(863, 319, ReceiptText.Delta(shift.BiggestLoss), 2, 10435106, 100, right: true);
			}
			canvas.Text(76, 368, "INCIDENTS", 2, 5464667);
			canvas.Text(880, 368, Count(shift.IncidentCount) + " RECORDED", 2, 5464667, 100, right: true);
			canvas.Box(76, 391, 804, 2, 1320226);
			int num = Math.Max(0, shift.Incidents.Count - 7);
			int num2 = shift.IncidentCount - (shift.Incidents.Count - num);
			if (shift.Incidents.Count == 0)
			{
				canvas.Center(478, 461, "NO INCIDENTS RECORDED", 2, 5464667);
			}
			for (int l = num; l < shift.Incidents.Count; l++)
			{
				Incident incident = shift.Incidents[l];
				int num3 = 398 + (l - num) * 30;
				int color = ((incident.Kind == IncidentKind.Deposit || incident.Kind == IncidentKind.Revival) ? 1139273 : 10435106);
				if ((l - num) % 2 == 0)
				{
					canvas.Box(76, num3, 804, 29, 15261639);
				}
				canvas.Text(89, num3 + 7, ReceiptText.Clock((int)incident.Stamp), 2, 5464667);
				canvas.Box(182, num3 + 8, 8, 13, color);
				canvas.Text(203, num3 + 7, ReceiptText.Verb(incident.Kind), 2, color);
				canvas.Text(341, num3 + 7, incident.Label, 2, 1320226, 32);
				canvas.Text(863, num3 + 7, ReceiptText.Delta(incident), 2, color, 100, right: true);
			}
			for (int m = 76; m < 880; m += 12)
			{
				canvas.Box(m, 625, 7, 2, 13485485);
			}
			canvas.Text(76, 640, "CARGOWICK / R.E.P.O.", 2, 5464667);
			canvas.Text(880, 640, (num2 > 0) ? ("+" + Count(num2) + " EARLIER INCIDENTS") : "LOCAL CREW LOG", 2, 5464667, 100, right: true);
			return canvas.Pixels;
		}

		internal static byte[] Icon()
		{
			Canvas canvas = new Canvas(256, 256);
			canvas.Box(0, 0, 256, 256, 1320226);
			for (int i = 13; i < 256; i += 15)
			{
				for (int j = 13; j < 256; j += 15)
				{
					canvas.Box(i, j, 2, 2, 3820099);
				}
			}
			canvas.Box(14, 14, 228, 2, 6652021);
			canvas.Box(14, 240, 228, 2, 6652021);
			canvas.Box(14, 14, 2, 228, 6652021);
			canvas.Box(240, 14, 2, 228, 6652021);
			canvas.Box(69, 44, 130, 161, 726548);
			Mark(canvas, 63, 37, 6, 15722705, 1320226);
			canvas.Box(63, 37, 126, 12, 15967324);
			canvas.Box(88, 69, 75, 7, 1139273);
			canvas.Box(88, 86, 57, 6, 1139273);
			canvas.Box(92, 113, 57, 54, 10435106);
			canvas.Text(108, 125, "$", 4, 15722705);
			canvas.Box(143, 150, 34, 30, 15967324);
			canvas.Box(152, 163, 16, 4, 1320226);
			return canvas.Pixels;
		}

		private static void Metric(Canvas image, int x, string label, string amount, int color)
		{
			image.Box(x, 232, 183, 58, 15064516);
			image.Text(x + 10, 239, label, 2, 5464667);
			image.Text(x + 10, 262, amount, (amount.Length > 9) ? 2 : 3, color);
		}

		private static void Mark(Canvas image, int x, int y, int scale, int fill, int cut)
		{
			image.Box(x, y, 21 * scale, 24 * scale, fill);
			for (int i = 0; i < 7; i++)
			{
				image.Box(x + i * 3 * scale, y + 24 * scale, 2 * scale, 2 * scale, fill);
			}
			image.Box(x + 4 * scale, y + 6 * scale, 13 * scale, 2 * scale, cut);
			image.Box(x + 4 * scale, y + 10 * scale, 9 * scale, 2 * scale, cut);
			image.Box(x + 4 * scale, y + 16 * scale, 13 * scale, 2 * scale, cut);
		}

		private static string Count(int value)
		{
			return value.ToString(CultureInfo.InvariantCulture);
		}

		internal static byte[] Png(byte[] pixels, int width, int height)
		{
			using MemoryStream memoryStream = new MemoryStream();
			memoryStream.Write(new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }, 0, 8);
			using MemoryStream memoryStream2 = new MemoryStream();
			Word(memoryStream2, (uint)width);
			Word(memoryStream2, (uint)height);
			memoryStream2.Write(new byte[5] { 8, 2, 0, 0, 0 }, 0, 5);
			Chunk(memoryStream, "IHDR", memoryStream2.ToArray());
			using MemoryStream memoryStream3 = new MemoryStream();
			memoryStream3.WriteByte(120);
			memoryStream3.WriteByte(156);
			uint num = 1u;
			uint num2 = 0u;
			using (DeflateStream deflateStream = new DeflateStream(memoryStream3, CompressionLevel.Optimal, leaveOpen: true))
			{
				int num3 = width * 3;
				for (int i = 0; i < height; i++)
				{
					deflateStream.WriteByte(0);
					int num4 = i * num3;
					deflateStream.Write(pixels, num4, num3);
					num2 = (num2 + num) % 65521;
					for (int j = num4; j < num4 + num3; j++)
					{
						num = (num + pixels[j]) % 65521;
						num2 = (num2 + num) % 65521;
					}
				}
			}
			Word(memoryStream3, (num2 << 16) | num);
			Chunk(memoryStream, "IDAT", memoryStream3.ToArray());
			Chunk(memoryStream, "IEND", Array.Empty<byte>());
			return memoryStream.ToArray();
		}

		private static void Chunk(Stream output, string tag, byte[] bytes)
		{
			byte[] bytes2 = Encoding.ASCII.GetBytes(tag);
			Word(output, (uint)bytes.Length);
			output.Write(bytes2, 0, bytes2.Length);
			output.Write(bytes, 0, bytes.Length);
			uint num = uint.MaxValue;
			byte[] array = bytes2;
			foreach (byte b in array)
			{
				num = CrcTable[(num ^ b) & 0xFF] ^ (num >> 8);
			}
			array = bytes;
			foreach (byte b2 in array)
			{
				num = CrcTable[(num ^ b2) & 0xFF] ^ (num >> 8);
			}
			Word(output, ~num);
		}

		private static void Word(Stream output, uint number)
		{
			output.WriteByte((byte)(number >> 24));
			output.WriteByte((byte)(number >> 16));
			output.WriteByte((byte)(number >> 8));
			output.WriteByte((byte)number);
		}

		private static uint[] MakeCrcTable()
		{
			uint[] array = new uint[256];
			for (uint num = 0u; num < array.Length; num++)
			{
				uint num2 = num;
				for (int i = 0; i < 8; i++)
				{
					num2 = (num2 >> 1) ^ (uint)(((num2 & 1) != 0) ? (-306674912) : 0);
				}
				array[num] = num2;
			}
			return array;
		}

		private static Dictionary<char, byte[]> ReadGlyphs()
		{
			string[] array = "\nA 0E11111F111111 B 1E11111E11111E C 0E11101010110E D 1E11111111111E\nE 1F10101E10101F F 1F10101E101010 G 0E11101711110F H 1111111F111111\nI 0E04040404040E J 0702020212120C K 11121418141211 L 1010101010101F\nM 111B1515111111 N 11191513111111 O 0E11111111110E P 1E11111E101010\nQ 0E11111115120D R 1E11111E141211 S 0F10100E01011E T 1F040404040404\nU 1111111111110E V 11111111110A04 W 11111115151B11 X 11110A040A1111\nY 11110A04040404 Z 1F01020408101F\n0 0E11131519110E 1 040C040404040E 2 0E11010204081F 3 1E01010601011E\n4 02060A121F0202 5 1F10101E01011E 6 0E10101E11110E 7 1F010204080808\n8 0E11110E11110E 9 0E11110F01010E\n- 0000001F000000 + 0004041F040400 $ 040F140E051E04 / 01010204081010\n: 000C0C000C0C00 . 00000000000C0C , 000000000C0C08 ? 0E110102040004\n( 02040808080402 ) 08040202020408 & 0C12140C15120D ' 04040800000000\n! 04040404040004 # 0A0A1F0A1F0A0A _ 0000000000001F".Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries);
			Dictionary<char, byte[]> dictionary = new Dictionary<char, byte[]>();
			for (int i = 0; i < array.Length; i += 2)
			{
				byte[] array2 = new byte[7];
				for (int j = 0; j < array2.Length; j++)
				{
					array2[j] = byte.Parse(array[i + 1].Substring(j * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
				}
				dictionary.Add(array[i][0], array2);
			}
			return dictionary;
		}
	}
	internal enum IncidentKind
	{
		Damage,
		Shatter,
		Down,
		Revival,
		Deposit
	}
	internal enum ShiftEnd
	{
		InProgress,
		Cleared,
		Wiped,
		Interrupted
	}
	internal sealed class Incident
	{
		internal IncidentKind Kind { get; set; }

		internal string Label { get; }

		internal int Amount { get; set; }

		internal int Target { get; }

		internal double Stamp { get; }

		internal Incident(IncidentKind kind, string label, int amount, int target, double stamp)
		{
			Kind = kind;
			Label = label;
			Amount = amount;
			Target = target;
			Stamp = stamp;
		}
	}
	internal sealed class Shift
	{
		private readonly List<Incident> incidents = new List<Incident>();

		private readonly Dictionary<int, string> crewLabels = new Dictionary<int, string>();

		private readonly Dictionary<int, Incident> shatters = new Dictionary<int, Incident>();

		private readonly double started;

		private readonly int capacity;

		internal int Floor { get; }

		internal string Site { get; }

		internal ShiftEnd End { get; private set; }

		internal int Seconds { get; private set; }

		internal long Lost { get; private set; }

		internal long Banked { get; private set; }

		internal int Downs { get; private set; }

		internal int Revivals { get; private set; }

		internal int Shattered { get; private set; }

		internal int Deposits { get; private set; }

		internal int IncidentCount { get; private set; }

		internal int Revision { get; private set; }

		internal Incident BiggestLoss { get; private set; }

		internal IReadOnlyList<Incident> Incidents => incidents;

		internal Shift(int floor, string site, double started, int capacity = 180)
		{
			Floor = floor;
			Site = ReceiptText.Clean(site, "Field Site");
			this.started = started;
			this.capacity = capacity;
		}

		internal static int CreditDollars(int before, int after)
		{
			long num = Math.Max(0L, (long)after - (long)before);
			return (int)Math.Min(2147483647L, num * 1000);
		}

		internal static ShiftEnd RemoteOutcome(int floor, int completed, bool gameOver, bool enteredArena)
		{
			if (gameOver || enteredArena)
			{
				return ShiftEnd.Wiped;
			}
			if (completed < floor)
			{
				return ShiftEnd.Interrupted;
			}
			return ShiftEnd.Cleared;
		}

		internal void Tick(double now)
		{
			if (End == ShiftEnd.InProgress)
			{
				Seconds = Math.Max(Seconds, (int)Math.Max(0.0, now - started));
			}
		}

		internal void Close(ShiftEnd end, double now)
		{
			if (End == ShiftEnd.InProgress)
			{
				Tick(now);
				End = end;
				Revision++;
			}
		}

		internal void Loss(int target, string label, int amount, bool shatter, double now)
		{
			if (End != ShiftEnd.InProgress || amount < 0 || (!shatter && amount == 0))
			{
				return;
			}
			shatters.TryGetValue(target, out var value);
			if (!shatter || value == null)
			{
				Lost += amount;
				Incident incident = (shatter ? RecentDamage(target, now) : value);
				if (incident == null)
				{
					incident = Add(shatter ? IncidentKind.Shatter : IncidentKind.Damage, label, amount, target, now);
				}
				else
				{
					incident.Kind = IncidentKind.Shatter;
					incident.Amount = (int)Math.Min(2147483647L, (long)incident.Amount + (long)amount);
					Revision++;
				}
				if (shatter)
				{
					Shattered++;
					shatters.Add(target, incident);
				}
				if (BiggestLoss == null || incident.Amount > BiggestLoss.Amount)
				{
					BiggestLoss = incident;
				}
			}
		}

		private Incident RecentDamage(int target, double now)
		{
			if (incidents.Count == 0)
			{
				return null;
			}
			Incident incident = incidents[incidents.Count - 1];
			if (incident.Kind != IncidentKind.Damage || incident.Target != target || !(now - started - incident.Stamp <= 0.25))
			{
				return null;
			}
			return incident;
		}

		internal void Crew(int target, bool down, bool wasDown, double now)
		{
			if (End == ShiftEnd.InProgress && down != wasDown)
			{
				if (!crewLabels.TryGetValue(target, out var value))
				{
					value = "Crew " + (crewLabels.Count + 1).ToString("00", CultureInfo.InvariantCulture);
					crewLabels.Add(target, value);
				}
				if (down)
				{
					Downs++;
				}
				else
				{
					Revivals++;
				}
				Add(down ? IncidentKind.Down : IncidentKind.Revival, value, 0, target, now);
			}
		}

		internal void Bank(int amount, double now)
		{
			if (End == ShiftEnd.InProgress && amount > 0)
			{
				Banked += amount;
				Deposits++;
				Add(IncidentKind.Deposit, "Extraction credit", amount, 0, now);
			}
		}

		private Incident Add(IncidentKind kind, string label, int amount, int target, double now)
		{
			Tick(now);
			Incident incident = new Incident(kind, label, amount, target, Math.Max(Seconds, now - started));
			if (incidents.Count == capacity)
			{
				incidents.RemoveAt(0);
			}
			incidents.Add(incident);
			IncidentCount++;
			Revision++;
			return incident;
		}
	}
	internal static class ReceiptText
	{
		private static readonly CultureInfo Dollars = CultureInfo.GetCultureInfo("en-US");

		internal static string Money(long value)
		{
			return "$" + value.ToString("N0", Dollars);
		}

		internal static string Clock(int seconds)
		{
			return string.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", seconds / 60, seconds % 60);
		}

		internal static string Status(ShiftEnd end)
		{
			return end switch
			{
				ShiftEnd.Cleared => "Cleared", 
				ShiftEnd.Wiped => "Crew lost", 
				ShiftEnd.Interrupted => "Interrupted", 
				_ => "In progress", 
			};
		}

		internal static string Verb(IncidentKind kind)
		{
			return kind switch
			{
				IncidentKind.Damage => "Damaged", 
				IncidentKind.Shatter => "Shattered", 
				IncidentKind.Down => "Down", 
				IncidentKind.Revival => "Revived", 
				_ => "Banked", 
			};
		}

		internal static string Delta(Incident entry)
		{
			if (entry.Kind == IncidentKind.Deposit)
			{
				return "+" + Money(entry.Amount);
			}
			if (entry.Kind == IncidentKind.Damage || entry.Kind == IncidentKind.Shatter)
			{
				return "-" + Money(entry.Amount);
			}
			return "";
		}

		internal static string ItemName(string value)
		{
			string text = Clean(value, "Valuable");
			while (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				text = text.Substring(0, text.Length - "(Clone)".Length).TrimEnd();
			}
			if (text.StartsWith("Valuable ", StringComparison.OrdinalIgnoreCase))
			{
				text = text.Substring("Valuable ".Length);
			}
			if (text.Length != 0)
			{
				return text;
			}
			return "Valuable";
		}

		internal static string Clean(string value, string fallback)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return fallback;
			}
			StringBuilder stringBuilder = new StringBuilder(Math.Min(value.Length, 100));
			foreach (char c in value)
			{
				if (stringBuilder.Length == 100)
				{
					break;
				}
				if (char.IsControl(c) || char.IsWhiteSpace(c))
				{
					if (stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] != ' ')
					{
						stringBuilder.Append(' ');
					}
				}
				else if (!char.IsSurrogate(c) && c != '<' && c != '>')
				{
					stringBuilder.Append(c);
				}
			}
			string text = stringBuilder.ToString().Trim();
			if (text.Length <= 0)
			{
				return fallback;
			}
			return text;
		}

		internal static string Format(Shift shift)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"ShiftSlip | Floor {shift.Floor} | {shift.Site}");
			stringBuilder.AppendLine(Status(shift.End) + " in " + Clock(shift.Seconds));
			stringBuilder.AppendLine($"{Money(shift.Banked)} banked | {Money(shift.Lost)} damaged | {shift.Shattered} shattered");
			stringBuilder.AppendLine($"{shift.Downs} downs | {shift.Revivals} revivals | {shift.Deposits} credits");
			if (shift.BiggestLoss != null)
			{
				stringBuilder.AppendLine("Biggest loss: " + shift.BiggestLoss.Label + " (" + Delta(shift.BiggestLoss) + ")");
			}
			int num = Math.Max(0, shift.Incidents.Count - 18);
			int num2 = shift.IncidentCount - (shift.Incidents.Count - num);
			if (num2 > 0)
			{
				stringBuilder.AppendLine($"… {num2} earlier incidents");
			}
			for (int i = num; i < shift.Incidents.Count; i++)
			{
				Incident incident = shift.Incidents[i];
				stringBuilder.AppendLine((Clock((int)incident.Stamp) + "  " + Verb(incident.Kind) + "  " + incident.Label + "  " + Delta(incident)).TrimEnd());
			}
			return stringBuilder.ToString().TrimEnd();
		}
	}
}