Decompiled source of AnotherSalmonRunMod v1.0.0

AnotherSalmonRunMod.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using AnotherSalmonRunMod.Cutscene;
using AnotherSalmonRunMod.Cutscene.Utils;
using AnotherSalmonRunMod.NetcodePatcher;
using AnotherSalmonRunMod.UnityScripts;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Dissonance.Integrations.Unity_NFGO;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ModelReplacement;
using ModelReplacement.AvatarBodyUpdater;
using TMPro;
using TooManyEmotes;
using TooManyEmotes.Props;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Animations.Rigging;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("")]
[assembly: AssemblyCompany("AnotherSalmonRunMod")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+a06d7e3c2b884e000529dd94cb1e5061ee9ccf23")]
[assembly: AssemblyProduct("AnotherSalmonRunMod")]
[assembly: AssemblyTitle("AnotherSalmonRunMod")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AnotherSalmonRunMod
{
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInPlugin("AnotherSalmonRunMod", "AnotherSalmonRunMod", "1.0.0")]
	public class AnotherSalmonRunMod : BaseUnityPlugin
	{
		public GameObject? sceneGameObject;

		public bool isGameObjectLoaded;

		public bool isCutscenePlaying;

		public List<string> scrapComments = new List<string>();

		public List<string> companyMonologues = new List<string>();

		public Sprite backgroundSprite;

		public static AnotherSalmonRunMod Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		internal static AnotherSalmonRunModConfig AnotherSalmonConfig { get; private set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Patch();
			Logger.LogInfo((object)"AnotherSalmonRunMod v1.0.0 has loaded!");
			LoadBundle();
			LoadConfig();
			LoadImageBackground();
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
		}

		private void LoadBundle()
		{
			try
			{
				AssetBundle val = AssetBundle.LoadFromFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/salmonruninlc");
				if ((Object)(object)val == (Object)null)
				{
					Logger.LogError((object)"Couldn't find 'salmonruninlc' asset bundle");
					return;
				}
				sceneGameObject = val.LoadAsset<GameObject>("SalmonGameObject");
				if ((Object)(object)sceneGameObject == (Object)null)
				{
					Logger.LogError((object)"Couldn't load 'salmonruninlc' asset bundle");
					return;
				}
				sceneGameObject.AddComponent<CutsceneManager>();
				Logger.LogInfo((object)"'salmonruninlc' asset bundle successfully loaded");
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Couldn't load 'salmonruninlc' asset bundle : {arg}");
			}
		}

		private void LoadImageBackground()
		{
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if ((Object)(object)sceneGameObject != (Object)null && (Object)(object)sceneGameObject.GetComponent<CutsceneManager>() == (Object)null)
				{
					Logger.LogError((object)"CutsceneManager can't be used, skipping background loading");
					return;
				}
				string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
				string text = directoryName + "/salmonruncustombg.png";
				string text2 = directoryName + "/salmonruncustombg.jpg";
				if (!File.Exists(text) && !File.Exists(text2))
				{
					Logger.LogInfo((object)"No custom background image will be used, file not fond");
					return;
				}
				byte[] array = File.ReadAllBytes(File.Exists(text) ? text : text2);
				Texture2D val = new Texture2D(1280, 720);
				ImageConversion.LoadImage(val, array);
				backgroundSprite = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
				Logger.LogInfo((object)"Custom background image successfully loaded");
			}
			catch (Exception arg)
			{
				Logger.LogError((object)$"Couldn't load custom background image : {arg}");
			}
		}

		private void LoadConfig()
		{
			AnotherSalmonConfig = new AnotherSalmonRunModConfig(((BaseUnityPlugin)this).Config);
			if (!Utility.IsNullOrWhiteSpace(AnotherSalmonConfig.ConfigScrapComments.Value))
			{
				scrapComments = AnotherSalmonConfig.ConfigScrapComments.Value.Split("|").ToList();
			}
			if (!Utility.IsNullOrWhiteSpace(AnotherSalmonConfig.ConfigCompanyMonologues.Value))
			{
				companyMonologues = AnotherSalmonConfig.ConfigCompanyMonologues.Value.Split("|").ToList();
			}
		}

		private static void Patch()
		{
			//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_0017: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("AnotherSalmonRunMod");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching SalmonRun !");
		}

		private static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	public class AnotherSalmonRunModConfig
	{
		public readonly ConfigEntry<string> ConfigScrapComments;

		public readonly ConfigEntry<string> ConfigCompanyMonologues;

		public AnotherSalmonRunModConfig(ConfigFile config)
		{
			config.SaveOnConfigSet = false;
			ConfigScrapComments = config.Bind<string>("CutsceneConfig", "scrapComments", "Come to papa, little scraps... NOW BRING US MORE!|Let's see... You harvested {0} scraps this time. Nice haul.|We gotta say - you might be the best employees we've ever had. A true professional team.|Time to clock out! Is it just us, or is the workday too short? Anyway, nice job on the quota. You got {0} scraps!|NO WAY! You cleared this quota?! You're as lethal as the space itself!", "Comments uses during the first screen of the cutscene. This is a list of comments and 1 will be randomly selected each time you reach a new quota.Use pipe (the | character) to split your different quotes.");
			ConfigCompanyMonologues = config.Bind<string>("CutsceneConfig", "companyMonologue", "Now THAT'S the type of performance we're looking for. You have a bright future here, dear employees. Take this bonus.|Never had a doubt! Great work. Now go to the next moon. Fuel isn't free.|Great work on that quota. It's like we always say : \"Trust the space and profits will follow!\" Yes, we always say that.|We can feel it... The next quota approaches! Collect scrap until you surpass it!|Way to show the galaxy what's the boss! It's the company. The company is the boss.", "Comments uses during the second screen of the cutscene. This is a list of comments and 1 will be randomly selected each time you reach a new quota.Use pipe (the | character) to split your different quotes.");
			ClearOrphanedEntries(config);
			config.Save();
			config.SaveOnConfigSet = true;
		}

		private void ClearOrphanedEntries(ConfigFile cfg)
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ConfigFile), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)propertyInfo.GetValue(cfg);
			dictionary.Clear();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "AnotherSalmonRunMod";

		public const string PLUGIN_NAME = "AnotherSalmonRunMod";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace AnotherSalmonRunMod.UnityScripts
{
	public class AnimatedUiGameObjectScript : MonoBehaviour
	{
		private Animator _animator;

		public void PlayAnimation(string animationName)
		{
			_animator = ((Component)this).gameObject.GetComponent<Animator>();
			try
			{
				_animator.Play(animationName);
			}
			catch (Exception arg)
			{
				AnotherSalmonRunMod.Logger.LogError((object)$"Error while playing the animation {animationName} : {arg}");
			}
		}
	}
	public class PlayerModelScript : MonoBehaviour
	{
		private GameObject? _playerObject;

		private EmoteController? _emoteController;

		private string _playerName;

		public string GetPlayerName()
		{
			return _playerName;
		}

		public void InitPlayerModel(PlayerControllerB playerController)
		{
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_01c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cc: Expected O, but got Unknown
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023b: Expected O, but got Unknown
			_playerObject = Object.Instantiate<GameObject>(((Component)playerController).gameObject, ((Component)this).transform, true);
			_playerObject.transform.SetPositionAndRotation(((Component)this).transform.position, ((Component)this).transform.rotation);
			_playerObject.transform.localEulerAngles = new Vector3(0f, 180f, 0f);
			_playerName = playerController.playerUsername;
			GameObject gameObject = ((Component)_playerObject.transform.Find("ScavengerModel")).gameObject;
			GameObject gameObject2 = ((Component)gameObject.transform.Find("metarig")).gameObject;
			PlayerControllerB componentInChildren = _playerObject.GetComponentInChildren<PlayerControllerB>();
			((Renderer)componentInChildren.thisPlayerModel).shadowCastingMode = (ShadowCastingMode)1;
			((Behaviour)componentInChildren).enabled = false;
			BodyReplacementBase val = default(BodyReplacementBase);
			bool playerModelReplacement = ModelReplacementAPI.GetPlayerModelReplacement(componentInChildren, ref val);
			string value = string.Empty;
			if (playerModelReplacement && (Object)(object)val != (Object)null && ((object)val).GetType().FullName != null)
			{
				value = ((object)val).GetType().FullName;
				((Component)gameObject.transform.Find("LOD1")).gameObject.SetActive(false);
			}
			Object.Destroy((Object)(object)gameObject.GetComponentInChildren<LODGroup>());
			Object.Destroy((Object)(object)gameObject2.GetComponentInChildren<RigBuilder>());
			Object.Destroy((Object)(object)gameObject2.GetComponentInChildren<GraphicRaycaster>());
			Object.Destroy((Object)(object)gameObject2.GetComponentInChildren<TMP_Text>());
			Object.Destroy((Object)(object)_playerObject.GetComponent<NfgoPlayer>());
			foreach (Transform item in _playerObject.transform)
			{
				Transform val2 = item;
				if (((Object)val2).name != "ScavengerModel")
				{
					Object.Destroy((Object)(object)((Component)val2).gameObject);
				}
			}
			foreach (Transform item2 in gameObject.transform)
			{
				Transform val3 = item2;
				if (((Object)val3).name != "LOD1" && ((Object)val3).name != "metarig")
				{
					Object.Destroy((Object)(object)((Component)val3).gameObject);
				}
			}
			foreach (Transform item3 in gameObject2.transform)
			{
				Transform val4 = item3;
				if (((Object)val4).name != "spine" && ((Object)val4).name != "ScavengerModelArmsOnly")
				{
					Object.Destroy((Object)(object)((Component)val4).gameObject);
				}
			}
			HDAdditionalLightData[] componentsInChildren = _playerObject.GetComponentsInChildren<HDAdditionalLightData>();
			foreach (HDAdditionalLightData val5 in componentsInChildren)
			{
				Object.Destroy((Object)(object)val5);
			}
			Component[] componentsInChildren2 = _playerObject.GetComponentsInChildren<Component>();
			foreach (Component val6 in componentsInChildren2)
			{
				if (!(val6 is Transform) && !(val6 is SkinnedMeshRenderer) && !(val6 is MeshFilter) && !(val6 is Animator) && !((object)val6).GetType().FullName.Equals(value))
				{
					Object.Destroy((Object)(object)val6);
				}
			}
			_emoteController = _playerObject.AddComponent<EmoteController>();
			_emoteController.Initialize("metarig");
			_emoteController.CreateBoneMap(EmoteControllerPlayer.sourceBoneNames, (List<string>)null);
			_emoteController.smoothTransitionToEmote = false;
			SetObjectLayerRecursive(_playerObject, ((Component)this).gameObject.layer);
		}

		private static void SetObjectLayerRecursive(GameObject obj, int layer)
		{
			if (Object.op_Implicit((Object)(object)obj))
			{
				obj.layer = layer;
				for (int i = 0; i < obj.transform.childCount; i++)
				{
					SetObjectLayerRecursive(((Component)obj.transform.GetChild(i)).gameObject, layer);
				}
			}
		}

		public void PlayEmote(UnlockableEmote emoteToPlay)
		{
			try
			{
				_emoteController.PerformEmote(emoteToPlay, -1, false);
				if (_emoteController.emotingProps == null)
				{
					return;
				}
				foreach (PropObject emotingProp in _emoteController.emotingProps)
				{
					emotingProp.SetPropLayer(((Component)this).gameObject.layer);
				}
			}
			catch (Exception arg)
			{
				AnotherSalmonRunMod.Logger.LogError((object)$"No Emote controller found for player {_playerName} : {arg}");
			}
		}
	}
	public class TextBoxScript : MonoBehaviour
	{
		private List<string> _defaultScrapComments = new List<string>(5) { "Come to papa, little scraps... NOW BRING US MORE!", "Let's see... You harvested {0} scraps this time. Nice haul.", "We gotta say - you might be the best employees we've ever had. A true professional team.", "Time to clock out! Is it just us, or is the workday too short? Anyway, nice job on the quota. You got {0} scraps!", "NO WAY! You cleared this quota?! You're as lethal as the space itself!" };

		private List<string> _companyMonologues = new List<string>(5) { "Now THAT'S the type of performance we're looking for. You have a bright future here, dear employees. Take this bonus.", "Never had a doubt! Great work. Now go to the next moon. Fuel isn't free.", "Great work on that quota. It's like we always say : \"Trust the space and profits will follow!\" Yes, we always say that.", "We can feel it... The next quota approaches! Collect scrap until you surpass it!", "Way to show the galaxy what's the boss! It's the company. The company is the boss." };

		private int _selectedLine;

		private string _selectedQuote = string.Empty;

		[SerializeField]
		private TMP_Text? quotesText;

		[SerializeField]
		private TMP_Text? speakerText;

		private AudioSource? _radioSound;

		private readonly Color32 _defaultSpeakerColor = new Color32(byte.MaxValue, (byte)106, (byte)0, byte.MaxValue);

		private readonly Color32 _quoteColor = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue);

		private readonly WaitForSeconds _textUpdateDelay = new WaitForSeconds(0.03f);

		private void Start()
		{
			if (AnotherSalmonRunMod.Instance.scrapComments.Any())
			{
				_defaultScrapComments = AnotherSalmonRunMod.Instance.scrapComments;
			}
			if (AnotherSalmonRunMod.Instance.companyMonologues.Any())
			{
				_companyMonologues = AnotherSalmonRunMod.Instance.companyMonologues;
			}
		}

		public void InitText(int nbScraps, bool isFirstScreen, AudioSource audioSource)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			_selectedLine = nbScraps;
			((Graphic)quotesText).color = Color32.op_Implicit(_quoteColor);
			quotesText.text = string.Empty;
			((Graphic)speakerText).color = Color32.op_Implicit(_defaultSpeakerColor);
			speakerText.text = "The company";
			_radioSound = audioSource;
			_selectedQuote = (isFirstScreen ? _defaultScrapComments[Random.Range(0, _defaultScrapComments.Count)] : _companyMonologues[Random.Range(0, _companyMonologues.Count)]);
		}

		public IEnumerator DisplayScrapMonologue()
		{
			_radioSound.Play();
			string text = string.Format(_selectedQuote, _selectedLine);
			string text2 = text;
			foreach (char c in text2)
			{
				TMP_Text? obj = quotesText;
				obj.text += c;
				yield return _textUpdateDelay;
			}
			_radioSound.Stop();
		}
	}
	public class UICounter : MonoBehaviour
	{
		[SerializeField]
		private TMP_Text? counterText;

		public void set_text(string value)
		{
			counterText.text = value;
		}
	}
}
namespace AnotherSalmonRunMod.Patches
{
	[HarmonyPatch(typeof(EmoteController))]
	internal class EmoteControllerPatch
	{
		[HarmonyPatch("StopPerformingEmote")]
		[HarmonyPrefix]
		private static bool StopPerformingEmote_Patch()
		{
			return !AnotherSalmonRunMod.Instance.isCutscenePlaying;
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class GameNetworkManagerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameNetworkManager), "Start")]
		private static void GameNetworkManager_Start_Patch()
		{
			NetworkManager.Singleton.AddNetworkPrefab(AnotherSalmonRunMod.Instance.sceneGameObject);
		}
	}
	[HarmonyPatch(typeof(HUDManager))]
	internal class HUDManagerPatch
	{
		[HarmonyPatch("DisplayNewDeadline")]
		[HarmonyPrefix]
		private static bool HUDManager_DisplayNewDeadline_Patch(HUDManager __instance)
		{
			if (AnotherSalmonRunMod.Instance.isGameObjectLoaded)
			{
				try
				{
					CutsceneManager.Instance.RunCutscene();
				}
				catch (Exception arg)
				{
					AnotherSalmonRunMod.Logger.LogError((object)$"Error while playing the Salmon Run cutscene : {arg}");
				}
			}
			return true;
		}

		[HarmonyPatch("FillEndGameStats")]
		[HarmonyPostfix]
		private static void FillEndGameStats_Patch()
		{
			if (AnotherSalmonRunMod.Instance.isGameObjectLoaded)
			{
				try
				{
					CutsceneManager.Instance.scrapCollectedByRound.Add(RoundManager.Instance.scrapDroppedInShip.Count);
					CutsceneManager.Instance.totalScrapCollected += RoundManager.Instance.scrapDroppedInShip.Count;
				}
				catch (Exception arg)
				{
					AnotherSalmonRunMod.Logger.LogError((object)$"FillEndGameStats_Patch error : {arg}");
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePostfix()
		{
			if (AnotherSalmonRunMod.Instance.isGameObjectLoaded)
			{
				return;
			}
			try
			{
				Object.Instantiate<GameObject>(AnotherSalmonRunMod.Instance.sceneGameObject);
				AnotherSalmonRunMod.Instance.isGameObjectLoaded = true;
				AnotherSalmonRunMod.Logger.LogInfo((object)"Successfully loaded SalmonRun in the game!");
			}
			catch (Exception arg)
			{
				AnotherSalmonRunMod.Logger.LogError((object)$"Error while loading SalmonRun in the game : {arg}");
			}
		}
	}
}
namespace AnotherSalmonRunMod.Cutscene
{
	public class CutsceneManager : MonoBehaviour
	{
		public bool readyToPlay;

		public List<int> scrapCollectedByRound;

		public int totalScrapCollected;

		private UnlockableEmote? _myEmoteToLaunch;

		private List<PlayerControllerB> _playerWithEmotes;

		public readonly Dictionary<string, string> CutscenePlayersEmotes = new Dictionary<string, string>();

		private NetworkSender _sender;

		private AudioSource? _music;

		private AudioSource? _radio;

		private GameObject? _scrapCounter;

		private GameObject? _moneyCounter;

		private GameObject? _playerCardsRoot;

		private Transform? _dayCardsRootTransform;

		private GameObject[] _dayCards;

		private List<GameObject> _playerCards;

		private GameObject? _textBox;

		private readonly string _dayCardsEntryAnimationName = "Day{0}CardEntryAnim";

		private readonly string _dayCardsExitAnimationName = "DayCardsExitAnim";

		private readonly string _playerCardsEntryAnimationName = "PlayerCardsEntryAnim";

		private readonly WaitForSecondsRealtime _shortTimer = new WaitForSecondsRealtime(1f);

		private readonly WaitForSecondsRealtime _mediumTimer = new WaitForSecondsRealtime(2f);

		private readonly WaitForSecondsRealtime _largeTimer = new WaitForSecondsRealtime(3f);

		public static CutsceneManager Instance { get; private set; }

		private void Start()
		{
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			try
			{
				AudioSource[] components = ((Component)((Component)this).transform.Find("AudioSources")).gameObject.GetComponents<AudioSource>();
				_music = components[0];
				_radio = components[1];
				Transform val = ((Component)this).transform.Find("Canvas");
				GameObject gameObject = ((Component)((Component)val).transform.Find("Background")).gameObject;
				Image component = gameObject.GetComponent<Image>();
				if ((Object)(object)AnotherSalmonRunMod.Instance.backgroundSprite != (Object)null && (Object)(object)component != (Object)null)
				{
					component.sprite = AnotherSalmonRunMod.Instance.backgroundSprite;
				}
				_scrapCounter = ((Component)((Component)val).transform.Find("ScrapCollected")).gameObject;
				_moneyCounter = ((Component)((Component)val).transform.Find("CreditGained")).gameObject;
				_dayCardsRootTransform = ((Component)val).transform.Find("DayCards");
				_dayCards = (GameObject[])(object)new GameObject[3];
				for (int i = 0; i < _dayCardsRootTransform.childCount; i++)
				{
					_dayCards[i] = ((Component)_dayCardsRootTransform.GetChild(i)).gameObject;
				}
				_textBox = ((Component)((Component)val).transform.Find("TextBox")).gameObject;
				_playerCardsRoot = ((Component)((Component)val).transform.Find("PlayerCards")).gameObject;
				_playerCards = new List<GameObject>();
				for (int j = 0; j < _playerCardsRoot.transform.childCount; j++)
				{
					_playerCards.Add(((Component)_playerCardsRoot.transform.GetChild(j)).gameObject);
				}
				_sender = ((Component)this).gameObject.GetComponent<NetworkSender>();
				((Component)this).gameObject.SetActive(false);
				readyToPlay = true;
			}
			catch (Exception arg)
			{
				AnotherSalmonRunMod.Logger.LogError((object)$"Failed to setup CutsceneManager object: {arg}");
				((Component)this).gameObject.SetActive(false);
			}
		}

		public void RunCutscene(bool debug = false)
		{
			if (readyToPlay)
			{
				AnotherSalmonRunMod.Logger.LogInfo((object)"Cutscene initializing...");
				if (InitEmotes() && InitUI(debug))
				{
					((MonoBehaviour)StartOfRound.Instance).StartCoroutine(PlayCutscene(debug));
				}
			}
		}

		private IEnumerator PlayCutscene(bool debug)
		{
			_music.Play();
			GameNetworkManager.Instance.localPlayerController.inSpecialInteractAnimation = true;
			HUDManager.Instance.HideHUD(true);
			AnotherSalmonRunMod.Instance.isCutscenePlaying = true;
			yield return ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(PlayFirstScreen(debug));
			yield return ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(PlaySecondScreen(debug));
			yield return _largeTimer;
			CleanScreen();
			((Component)this).gameObject.SetActive(false);
		}

		private bool InitEmotes()
		{
			_myEmoteToLaunch = EmotesUtils.GetRandomEmote();
			string playerUsername = GameNetworkManager.Instance.localPlayerController.playerUsername;
			_sender.PrepareSendEmote(playerUsername, _myEmoteToLaunch.emoteName);
			_playerWithEmotes = (from dictPcbEcp in EmoteControllerPlayer.allPlayerEmoteControllers
				where dictPcbEcp.Key.isPlayerControlled
				select dictPcbEcp.Key).ToList();
			if (!_playerWithEmotes.Any())
			{
				AnotherSalmonRunMod.Logger.LogError((object)"No players with Emote controller found.");
				return false;
			}
			foreach (KeyValuePair<PlayerControllerB, EmoteControllerPlayer> allPlayerEmoteController in EmoteControllerPlayer.allPlayerEmoteControllers)
			{
				if (((EmoteController)allPlayerEmoteController.Value).isPerformingEmote)
				{
					((EmoteController)allPlayerEmoteController.Value).StopPerformingEmote();
				}
			}
			AnotherSalmonRunMod.Logger.LogInfo((object)"Cutscene initialized !");
			return true;
		}

		private bool InitUI(bool debug)
		{
			AnotherSalmonRunMod.Logger.LogInfo((object)"Initializing UI...");
			try
			{
				UICounter component = _scrapCounter.GetComponent<UICounter>();
				component.set_text("x " + (debug ? Random.RandomRangeInt(0, 10000) : totalScrapCollected));
				Terminal val = Object.FindObjectOfType<Terminal>();
				UICounter component2 = _moneyCounter.GetComponent<UICounter>();
				component2.set_text(((Object)(object)val == (Object)null) ? "x 0" : ("x " + (debug ? Random.RandomRangeInt(0, 10000) : val.groupCredits)));
				for (int num = _dayCards.Length; num > 0; num--)
				{
					UICounter component3 = _dayCards[num - 1].GetComponent<UICounter>();
					try
					{
						if (scrapCollectedByRound.Count > 0)
						{
							List<int> list = scrapCollectedByRound;
							component3.set_text(list[list.Count - 1].ToString());
							scrapCollectedByRound.RemoveAt(scrapCollectedByRound.Count - 1);
						}
						else
						{
							component3.set_text("X");
						}
					}
					catch (Exception arg)
					{
						if (debug)
						{
							component3.set_text(Random.Range(0, 100).ToString());
							AnotherSalmonRunMod.Logger.LogInfo((object)"So you skip days, did you ?");
						}
						else
						{
							component3.set_text("?");
							AnotherSalmonRunMod.Logger.LogError((object)$"Error while setting the day cards values : {arg}");
						}
					}
				}
				if (_playerCards.Count < _playerWithEmotes.Count)
				{
					PlayerUtils.ShufflePlayerControllerList(_playerWithEmotes);
				}
				for (int i = 0; i < _playerCards.Count && i < _playerWithEmotes.Count; i++)
				{
					((Component)_playerCards[i].transform.Find("PlayerModel")).GetComponent<PlayerModelScript>().InitPlayerModel(_playerWithEmotes[i]);
				}
				AnotherSalmonRunMod.Logger.LogInfo((object)"UI initialized !");
				((Component)this).gameObject.SetActive(true);
				return true;
			}
			catch (Exception arg2)
			{
				AnotherSalmonRunMod.Logger.LogError((object)$"Error while initializing UI : {arg2}");
				return false;
			}
		}

		private IEnumerator PlayFirstScreen(bool debug)
		{
			AnimatedUiGameObjectScript[] pointCardScripts = new AnimatedUiGameObjectScript[_dayCards.Length];
			for (int i = 0; i < pointCardScripts.Length; i++)
			{
				pointCardScripts[i] = _dayCards[i].GetComponent<AnimatedUiGameObjectScript>();
			}
			TextBoxScript boxScript = _textBox.GetComponent<TextBoxScript>();
			for (int j = 0; j < pointCardScripts.Length; j++)
			{
				_dayCards[j].SetActive(true);
				pointCardScripts[j].PlayAnimation(string.Format(_dayCardsEntryAnimationName, j + 1));
				yield return _shortTimer;
			}
			yield return _shortTimer;
			_textBox.SetActive(true);
			boxScript.InitText(debug ? Random.Range(0, 100) : totalScrapCollected, isFirstScreen: true, _radio);
			yield return ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(boxScript.DisplayScrapMonologue());
			yield return _shortTimer;
			((Component)_dayCardsRootTransform).GetComponent<AnimatedUiGameObjectScript>().PlayAnimation(_dayCardsExitAnimationName);
		}

		private IEnumerator PlaySecondScreen(bool debug)
		{
			PlayerUtils.ActivateViewModel(activate: false);
			AnimatedUiGameObjectScript component = ((Component)_playerCardsRoot.transform).GetComponent<AnimatedUiGameObjectScript>();
			component.PlayAnimation(_playerCardsEntryAnimationName);
			for (int i = 0; i < _playerCards.Count; i++)
			{
				if (i >= _playerWithEmotes.Count)
				{
					_playerCards[i].gameObject.SetActive(false);
					continue;
				}
				PlayerModelScript playerModelScriptComponent = ((Component)_playerCards[i].transform.Find("PlayerModel")).GetComponent<PlayerModelScript>();
				PlayerControllerB val = _playerWithEmotes.First((PlayerControllerB pcb) => pcb.playerUsername == playerModelScriptComponent.GetPlayerName());
				EmotesManager.allUnlockableEmotesDict.TryGetValue(CutscenePlayersEmotes[val.playerUsername], out var value);
				if (value != null)
				{
					((Component)_playerCards[i].transform.Find("PlayerModel")).GetComponent<PlayerModelScript>().PlayEmote(value);
				}
				else
				{
					AnotherSalmonRunMod.Logger.LogError((object)("Emote not found for player " + val.playerUsername));
				}
				((Component)_playerCards[i].transform.Find("Name").Find("NameTextBox")).GetComponent<TMP_Text>().text = val.playerUsername;
				((Component)_playerCards[i].transform.Find("Level").Find("LevelTextBox")).GetComponent<TMP_Text>().text = HUDManager.Instance.playerLevels[val.playerLevelNumber].levelName;
				_playerCards[i].gameObject.SetActive(true);
			}
			yield return _mediumTimer;
			TextBoxScript component2 = _textBox.GetComponent<TextBoxScript>();
			component2.InitText(debug ? Random.Range(0, 100) : totalScrapCollected, isFirstScreen: false, _radio);
			yield return ((MonoBehaviour)StartOfRound.Instance).StartCoroutine(component2.DisplayScrapMonologue());
		}

		private void CleanScreen()
		{
			//IL_001a: 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_0043: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			_playerCardsRoot.transform.SetLocalPositionAndRotation(new Vector3(1200f, 70f, 0f), Quaternion.identity);
			_playerCardsRoot.transform.localScale = new Vector3(0.8f, 0.8f, 1f);
			((Component)_dayCardsRootTransform).transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity);
			GameObject[] dayCards = _dayCards;
			foreach (GameObject val in dayCards)
			{
				val.SetActive(false);
			}
			_textBox.SetActive(false);
			CutscenePlayersEmotes.Clear();
			scrapCollectedByRound = new List<int>();
			totalScrapCollected = 0;
			PlayerUtils.ActivateViewModel(activate: true);
			for (int j = 0; j < _playerCards.Count; j++)
			{
				GameObject gameObject = ((Component)_playerCards[j].transform.Find("PlayerModel")).gameObject;
				foreach (Transform item in gameObject.transform)
				{
					Transform val2 = item;
					Object.Destroy((Object)(object)((Component)val2).gameObject);
				}
			}
			HUDManager.Instance.HideHUD(false);
			GameNetworkManager.Instance.localPlayerController.inSpecialInteractAnimation = false;
			AnotherSalmonRunMod.Instance.isCutscenePlaying = false;
		}
	}
	public class NetworkSender : NetworkBehaviour
	{
		public void PrepareSendEmote(string playerName, string emoteName)
		{
			SendEmoteToAllPlayersRpc(playerName, emoteName);
		}

		[Rpc(/*Could not decode attribute arguments.*/)]
		private void SendEmoteToAllPlayersRpc(string playerName, string emoteName)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Invalid comparison between Unknown and I4
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 1)
			{
				RpcAttributeParams val = default(RpcAttributeParams);
				RpcParams val3 = default(RpcParams);
				FastBufferWriter val2 = ((NetworkBehaviour)this).__beginSendRpc(3124045366u, val3, val, (SendTo)6, (RpcDelivery)0);
				bool flag = playerName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(playerName, false);
				}
				bool flag2 = emoteName != null;
				((FastBufferWriter)(ref val2)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val2)).WriteValueSafe(emoteName, false);
				}
				((NetworkBehaviour)this).__endSendRpc(ref val2, 3124045366u, val3, val, (SendTo)6, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage == 1)
			{
				base.__rpc_exec_stage = (__RpcExecStage)0;
				CutsceneManager.Instance.CutscenePlayersEmotes.TryAdd(playerName, emoteName);
				AnotherSalmonRunMod.Logger.LogInfo((object)("Send emote " + emoteName + " from player " + playerName + " to other players"));
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		protected override void __initializeRpcs()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Expected O, but got Unknown
			((NetworkBehaviour)this).__registerRpc(3124045366u, new RpcReceiveHandler(__rpc_handler_3124045366), "SendEmoteToAllPlayersRpc");
			((NetworkBehaviour)this).__initializeRpcs();
		}

		private static void __rpc_handler_3124045366(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: 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_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string playerName = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref playerName, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				string emoteName = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref emoteName, false);
				}
				target.__rpc_exec_stage = (__RpcExecStage)1;
				((NetworkSender)(object)target).SendEmoteToAllPlayersRpc(playerName, emoteName);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "NetworkSender";
		}
	}
}
namespace AnotherSalmonRunMod.Cutscene.Utils
{
	public static class EmotesUtils
	{
		public static UnlockableEmote GetRandomEmote()
		{
			if (SessionManager.unlockedEmotes.Count <= 0)
			{
				return EmotesManager.complementaryEmotes[Random.Range(0, EmotesManager.complementaryEmotes.Count)];
			}
			return SessionManager.unlockedEmotes[Random.Range(0, SessionManager.unlockedEmotes.Count)];
		}
	}
	public static class PlayerUtils
	{
		public static void ShufflePlayerControllerList(List<PlayerControllerB> playerControllers)
		{
			Random random = new Random();
			int count = playerControllers.Count;
			for (int num = count - 1; num > 0; num--)
			{
				int num2 = random.Next(0, num + 1);
				int index = num;
				int index2 = num2;
				PlayerControllerB value = playerControllers[num2];
				PlayerControllerB value2 = playerControllers[num];
				playerControllers[index] = value;
				playerControllers[index2] = value2;
			}
		}

		public static void ActivateViewModel(bool activate)
		{
			OffsetBuilder[] array = Object.FindObjectsOfType<OffsetBuilder>(true);
			foreach (OffsetBuilder val in array)
			{
				if (((Object)val).name.Contains("(ViewModel)"))
				{
					((Component)val).gameObject.SetActive(activate);
				}
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace __GEN
{
	internal class NetworkVariableSerializationHelper
	{
		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeSerialization()
		{
		}
	}
}
namespace AnotherSalmonRunMod.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}