Decompiled source of DBZProperSaveCompatibility v1.1.0

DbzProperSave.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using BepInEx;
using NS_KingItems;
using NS_KingModUtilities;
using ProperSave;
using RoR2;
using UnityEngine;
using UnityEngine.Networking;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace DbzProperSave;

[BepInDependency("com.Kingpinush.KingModUtilities", "1.9.5")]
[BepInDependency("com.Kingpinush.KingItems", "1.5.2")]
[BepInDependency("com.KingEnderBrine.ProperSave", "3.1.4")]
[BepInPlugin("local.dbz.propersavecompat", "DBZ ProperSave Compatibility", "1.1.0")]
public sealed class Plugin : BaseUnityPlugin
{
	public sealed class ProgressMessage : MessageBase
	{
		public uint runId;

		public bool restored;

		public string payload;

		public override void Serialize(NetworkWriter writer)
		{
			writer.Write(runId);
			writer.Write(restored);
			writer.Write(payload);
		}

		public override void Deserialize(NetworkReader reader)
		{
			runId = reader.ReadUInt32();
			restored = reader.ReadBoolean();
			payload = reader.ReadString();
			if (payload == null || payload.Length > 12000)
			{
				throw new InvalidDataException("Invalid DBZ progress payload length.");
			}
		}
	}

	[DataContract]
	private sealed class Snapshot
	{
		[DataMember]
		public string body;

		[DataMember]
		public int training;

		[DataMember]
		public List<Form> forms = new List<Form>();
	}

	[DataContract]
	private sealed class Form
	{
		[DataMember]
		public string name;

		[DataMember]
		public int level;

		[DataMember]
		public float experience;

		[DataMember]
		public bool used;

		[DataMember]
		public bool available;
	}

	private const string PluginId = "local.dbz.propersavecompat";

	private const string SaveKey = "local.dbz.propersavecompat.v1";

	private const string MultiplayerKey = "local.dbz.propersavecompat.players.v1";

	private const short ProgressMessageId = 28531;

	private const int MaxPayloadLength = 12000;

	private const string TrainingKey = "TrainingWeight_TrainingValue";

	private readonly Dictionary<string, Snapshot> remoteProgress = new Dictionary<string, Snapshot>();

	private readonly Dictionary<string, Snapshot> remoteRestore = new Dictionary<string, Snapshot>();

	private NetworkClient registeredClient;

	private bool serverRegistered;

	private bool receivedRestore;

	private bool restoreAcknowledged;

	private float nextUpload;

	private MethodInfo recalculateExperience;

	private MethodInfo applyTrainingBuffs;

	private Snapshot pending;

	private Run restoringRun;

	private bool masteryRestored;

	private bool trainingRestored;

	private bool subscribed;

	private void Awake()
	{
		recalculateExperience = typeof(RuntimeTransformationValues).GetMethod("CalculateExpReqForNextLevel", BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
		applyTrainingBuffs = typeof(TrainingWeight).GetMethod("UpdateTrainingBuffs", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[2]
		{
			typeof(BonusStatHandler),
			typeof(int)
		}, null);
		if (recalculateExperience == null || applyTrainingBuffs == null)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)"The installed King mods do not have the expected mastery and Training Weight methods.");
			return;
		}
		SaveFile.OnGatherSaveData += Gather;
		Loading.OnLoadingStarted += QueueRestore;
		Run.onRunStartGlobal += StartRun;
		Run.onRunDestroyGlobal += EndRun;
		subscribed = true;
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Registered ProperSave support for DBZ runs.");
	}

	private void OnDestroy()
	{
		if (subscribed)
		{
			SaveFile.OnGatherSaveData -= Gather;
			Loading.OnLoadingStarted -= QueueRestore;
			Run.onRunStartGlobal -= StartRun;
			Run.onRunDestroyGlobal -= EndRun;
			if (registeredClient != null)
			{
				registeredClient.UnregisterHandler((short)28531);
			}
			if (serverRegistered && NetworkServer.active)
			{
				NetworkServer.UnregisterHandler((short)28531);
			}
		}
	}

	private static NetworkUser LocalPlayer()
	{
		ReadOnlyCollection<NetworkUser> readOnlyLocalPlayersList = NetworkUser.readOnlyLocalPlayersList;
		if (readOnlyLocalPlayersList.Count != 1)
		{
			return null;
		}
		return readOnlyLocalPlayersList[0];
	}

	private static string PlayerKey(NetworkUser user)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		NetworkUserId id = user.id;
		return (string.IsNullOrEmpty(id.strValue) ? ("steam:" + id.value) : ("egs:" + id.strValue)) + ":" + id.subId;
	}

	private static CharacterMaster LocalMaster()
	{
		NetworkUser val = LocalPlayer();
		if (!Object.op_Implicit((Object)(object)val))
		{
			return null;
		}
		return val.master;
	}

	private void Gather(Dictionary<string, object> data)
	{
		Dictionary<string, Snapshot> dictionary = new Dictionary<string, Snapshot>();
		NetworkUser val = LocalPlayer();
		foreach (NetworkUser readOnlyInstances in NetworkUser.readOnlyInstancesList)
		{
			CharacterMaster master = readOnlyInstances.master;
			if (!Object.op_Implicit((Object)(object)master) || !Object.op_Implicit((Object)(object)master.bodyPrefab))
			{
				continue;
			}
			string key = PlayerKey(readOnlyInstances);
			Snapshot value;
			if ((Object)(object)readOnlyInstances == (Object)(object)val)
			{
				value = CaptureLocal(master, includeTraining: true);
			}
			else
			{
				if (remoteRestore.TryGetValue(key, out value))
				{
					dictionary[key] = value;
					continue;
				}
				remoteProgress.TryGetValue(key, out var value2);
				CustomDataHandler component = ((Component)master).GetComponent<CustomDataHandler>();
				Snapshot snapshot = new Snapshot();
				snapshot.body = ((Object)master.bodyPrefab).name;
				snapshot.training = (Object.op_Implicit((Object)(object)component) ? component.Get<int>("TrainingWeight_TrainingValue", 0) : 0);
				snapshot.forms = ((value2 != null && value2.body == ((Object)master.bodyPrefab).name) ? value2.forms : new List<Form>());
				value = snapshot;
			}
			if (value.forms.Count != 0 || value.training > 0)
			{
				dictionary[key] = value;
			}
		}
		if (dictionary.Count != 0)
		{
			data["local.dbz.propersavecompat.players.v1"] = Serialize(dictionary);
			if (NetworkUser.readOnlyInstancesList.Count == 1 && Object.op_Implicit((Object)(object)val) && dictionary.ContainsKey(PlayerKey(val)))
			{
				data["local.dbz.propersavecompat.v1"] = Serialize(dictionary[PlayerKey(val)]);
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Saved DBZ progress for " + dictionary.Count + " player(s)."));
		}
	}

	private Snapshot CaptureLocal(CharacterMaster master, bool includeTraining)
	{
		Snapshot snapshot = new Snapshot();
		snapshot.body = ((Object)master.bodyPrefab).name;
		bool flag = pending != null && (Object)(object)restoringRun == (Object)(object)Run.instance && pending.body == snapshot.body;
		CustomDataHandler component = ((Component)master).GetComponent<CustomDataHandler>();
		snapshot.training = (includeTraining ? ((flag && !trainingRestored) ? pending.training : (Object.op_Implicit((Object)(object)component) ? component.Get<int>("TrainingWeight_TrainingValue", 0) : 0)) : 0);
		if (flag && !masteryRestored)
		{
			snapshot.forms = pending.forms;
		}
		else
		{
			for (int i = 0; i < TransformationBank.GetRuntimeTransformationsCount(); i++)
			{
				TransformationState runtimeTransformationState = TransformationBank.GetRuntimeTransformationState(i);
				if (runtimeTransformationState != null && ((RuntimeTransformationValues)(ref runtimeTransformationState.RuntimeValues)).GetCurrentLevel() >= 1)
				{
					snapshot.forms.Add(new Form
					{
						name = runtimeTransformationState.GetName(),
						level = ((RuntimeTransformationValues)(ref runtimeTransformationState.RuntimeValues)).GetCurrentLevel(),
						experience = ((RuntimeTransformationValues)(ref runtimeTransformationState.RuntimeValues)).GetCurrentExp(),
						used = runtimeTransformationState.RuntimeValues.HasBeenUsed,
						available = runtimeTransformationState.RuntimeValues.IsAvailable
					});
				}
			}
		}
		return snapshot;
	}

	private void QueueRestore(SaveFile save)
	{
		ClearRestore();
		if (save == null)
		{
			return;
		}
		try
		{
			string text = save.TryGetModdedData<string>("local.dbz.propersavecompat.players.v1");
			if (!string.IsNullOrEmpty(text))
			{
				Dictionary<string, Snapshot> dictionary = Deserialize<Dictionary<string, Snapshot>>(text);
				foreach (KeyValuePair<string, Snapshot> item in dictionary)
				{
					if (ValidSnapshot(item.Value))
					{
						remoteRestore[item.Key] = item.Value;
					}
				}
			}
			string text2 = save.TryGetModdedData<string>("local.dbz.propersavecompat.v1");
			if (!string.IsNullOrEmpty(text2))
			{
				pending = Deserialize<Snapshot>(text2);
			}
			if (pending != null && !ValidSnapshot(pending))
			{
				pending = null;
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Couldn't read DBZ progress from this save. " + ex.Message));
		}
	}

	private static bool ValidSnapshot(Snapshot snapshot)
	{
		if (snapshot != null && !string.IsNullOrEmpty(snapshot.body) && snapshot.forms != null && snapshot.forms.Count <= 128)
		{
			return snapshot.training >= 0;
		}
		return false;
	}

	private void StartRun(Run run)
	{
		remoteProgress.Clear();
		receivedRestore = false;
		restoreAcknowledged = false;
		nextUpload = 0f;
		if (!NetworkServer.active || !Loading.IsLoading)
		{
			remoteRestore.Clear();
			ClearRestore();
			return;
		}
		NetworkUser val = LocalPlayer();
		if (Object.op_Implicit((Object)(object)val) && remoteRestore.TryGetValue(PlayerKey(val), out var value))
		{
			pending = value;
			remoteRestore.Remove(PlayerKey(val));
		}
		restoringRun = run;
	}

	private void EndRun(Run run)
	{
		ClearRestore();
		remoteRestore.Clear();
		remoteProgress.Clear();
		receivedRestore = false;
		restoreAcknowledged = false;
	}

	private void LateUpdate()
	{
		//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		UpdateNetworkHandlers();
		if (pending != null && Object.op_Implicit((Object)(object)restoringRun) && (Object)(object)restoringRun == (Object)(object)Run.instance && !Loading.IsLoading)
		{
			TryRestore();
		}
		if (!NetworkServer.active && registeredClient != null && registeredClient.isConnected && Object.op_Implicit((Object)(object)Run.instance) && !(Time.unscaledTime < nextUpload))
		{
			CharacterMaster val = LocalMaster();
			if (Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)val.bodyPrefab))
			{
				nextUpload = Time.unscaledTime + 0.5f;
				NetworkClient obj = registeredClient;
				ProgressMessage progressMessage = new ProgressMessage();
				NetworkInstanceId netId = ((NetworkBehaviour)Run.instance).netId;
				progressMessage.runId = ((NetworkInstanceId)(ref netId)).Value;
				progressMessage.restored = restoreAcknowledged;
				progressMessage.payload = Serialize(CaptureLocal(val, includeTraining: false));
				obj.Send((short)28531, (MessageBase)(object)progressMessage);
			}
		}
	}

	private void UpdateNetworkHandlers()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Expected O, but got Unknown
		if (NetworkServer.active && !serverRegistered)
		{
			NetworkServer.RegisterHandler((short)28531, new NetworkMessageDelegate(ReceiveFromClient));
		}
		serverRegistered = NetworkServer.active;
		NetworkManager singleton = NetworkManager.singleton;
		NetworkClient val = (Object.op_Implicit((Object)(object)singleton) ? singleton.client : null);
		if (val != registeredClient)
		{
			if (registeredClient != null)
			{
				registeredClient.UnregisterHandler((short)28531);
			}
			registeredClient = val;
			if (val != null)
			{
				val.RegisterHandler((short)28531, new NetworkMessageDelegate(ReceiveFromHost));
			}
		}
	}

	private void ReceiveFromClient(NetworkMessage message)
	{
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		if (!NetworkServer.active || !Object.op_Implicit((Object)(object)Run.instance) || Loading.IsLoading)
		{
			return;
		}
		NetworkUser val = null;
		foreach (NetworkUser readOnlyInstances in NetworkUser.readOnlyInstancesList)
		{
			if (!((NetworkBehaviour)readOnlyInstances).isLocalPlayer && ((NetworkBehaviour)readOnlyInstances).connectionToClient == message.conn)
			{
				if (Object.op_Implicit((Object)(object)val))
				{
					return;
				}
				val = readOnlyInstances;
			}
		}
		if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.master) || !Object.op_Implicit((Object)(object)val.master.bodyPrefab))
		{
			return;
		}
		try
		{
			ProgressMessage progressMessage = message.ReadMessage<ProgressMessage>();
			uint runId = progressMessage.runId;
			NetworkInstanceId netId = ((NetworkBehaviour)Run.instance).netId;
			if (runId != ((NetworkInstanceId)(ref netId)).Value)
			{
				return;
			}
			string key = PlayerKey(val);
			if (remoteRestore.TryGetValue(key, out var value) && !progressMessage.restored)
			{
				if (!(value.body != ((Object)val.master.bodyPrefab).name))
				{
					CustomDataHandler component = ((Component)val.master).GetComponent<CustomDataHandler>();
					if (Object.op_Implicit((Object)(object)component) && component.Get<int>("TrainingWeight_TrainingValue", 0) != value.training)
					{
						component.SetIntValue("TrainingWeight_TrainingValue", value.training);
					}
					message.conn.Send((short)28531, (MessageBase)(object)new ProgressMessage
					{
						runId = progressMessage.runId,
						payload = Serialize(value)
					});
				}
			}
			else
			{
				Snapshot snapshot = Deserialize<Snapshot>(progressMessage.payload);
				if (ValidSnapshot(snapshot) && snapshot.body == ((Object)val.master.bodyPrefab).name)
				{
					remoteRestore.Remove(key);
					remoteProgress[key] = snapshot;
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogDebug((object)("Ignored invalid DBZ progress message. " + ex.Message));
		}
	}

	private void ReceiveFromHost(NetworkMessage message)
	{
		//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)
		if (NetworkServer.active || !Object.op_Implicit((Object)(object)Run.instance) || receivedRestore)
		{
			return;
		}
		try
		{
			ProgressMessage progressMessage = message.ReadMessage<ProgressMessage>();
			uint runId = progressMessage.runId;
			NetworkInstanceId netId = ((NetworkBehaviour)Run.instance).netId;
			if (runId == ((NetworkInstanceId)(ref netId)).Value)
			{
				Snapshot snapshot = Deserialize<Snapshot>(progressMessage.payload);
				if (ValidSnapshot(snapshot))
				{
					pending = snapshot;
					restoringRun = Run.instance;
					receivedRestore = true;
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogDebug((object)("Ignored invalid DBZ restore message. " + ex.Message));
		}
	}

	private void TryRestore()
	{
		try
		{
			CharacterMaster val = LocalMaster();
			if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val.bodyPrefab))
			{
				return;
			}
			if (!string.Equals(pending.body, ((Object)val.bodyPrefab).name, StringComparison.Ordinal))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"The loaded survivor differs from the DBZ progress in the save.");
				ClearRestore();
				return;
			}
			if (!masteryRestored)
			{
				RestoreMastery();
			}
			if (!trainingRestored)
			{
				RestoreTraining(val);
			}
			if (masteryRestored && trainingRestored)
			{
				restoreAcknowledged = receivedRestore;
				ClearRestore();
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Couldn't restore DBZ progress. " + ex));
			ClearRestore();
		}
	}

	private void RestoreMastery()
	{
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Unknown result type (might be due to invalid IL or missing references)
		//IL_013a: Unknown result type (might be due to invalid IL or missing references)
		//IL_013f: Unknown result type (might be due to invalid IL or missing references)
		if (pending.forms == null || pending.forms.Count == 0)
		{
			masteryRestored = true;
		}
		else
		{
			if (TransformationBank.GetRuntimeTransformationsCount() == 0)
			{
				return;
			}
			int num = 0;
			long num2 = 0L;
			foreach (Form form in pending.forms)
			{
				if (form == null || string.IsNullOrEmpty(form.name) || form.level < 1 || form.experience < 0f || float.IsNaN(form.experience) || float.IsInfinity(form.experience))
				{
					continue;
				}
				int num3 = TransformationBank.FindRuntimeTransformationIndex(form.name);
				if (num3 >= 0)
				{
					TransformationState runtimeTransformationState = TransformationBank.GetRuntimeTransformationState(num3);
					RuntimeTransformationValues runtimeValues = runtimeTransformationState.RuntimeValues;
					if (runtimeTransformationState is MainTransformationState)
					{
						num2 += Math.Max(0, form.level - ((RuntimeTransformationValues)(ref runtimeValues)).GetCurrentLevel());
					}
					((RuntimeTransformationValues)(ref runtimeValues)).SetCurrentLevel(form.level);
					((RuntimeTransformationValues)(ref runtimeValues)).SetCurrentExp(form.experience);
					runtimeValues.HasBeenUsed = form.used;
					runtimeValues.IsAvailable = form.available;
					object obj = runtimeValues;
					recalculateExperience.Invoke(obj, null);
					runtimeTransformationState.RuntimeValues = (RuntimeTransformationValues)obj;
					num++;
				}
			}
			KiHandler.AddBonusKiRegen((float)num2 * MainPlugin.Config_KiRegenGainPerMasteryLevel.Value);
			((BaseUnityPlugin)this).Logger.LogInfo((object)$"Restored {num} of {pending.forms.Count} mastery entries.");
			masteryRestored = true;
		}
	}

	private void RestoreTraining(CharacterMaster master)
	{
		if (pending.training <= 0)
		{
			trainingRestored = true;
			return;
		}
		CustomDataHandler component = ((Component)master).GetComponent<CustomDataHandler>();
		CharacterBody body = master.GetBody();
		if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)body))
		{
			return;
		}
		BonusStatHandler forBody = BonusStatHandler.GetForBody(body);
		if (Object.op_Implicit((Object)(object)forBody))
		{
			if (NetworkServer.active || component.Get<int>("TrainingWeight_TrainingValue", 0) != pending.training)
			{
				component.SetIntValue("TrainingWeight_TrainingValue", pending.training);
			}
			applyTrainingBuffs.Invoke(null, new object[2] { forBody, pending.training });
			trainingRestored = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Restored Training Weight progress " + pending.training + "."));
		}
	}

	private void ClearRestore()
	{
		pending = null;
		restoringRun = null;
		masteryRestored = false;
		trainingRestored = false;
	}

	private static string Serialize<T>(T snapshot)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		using MemoryStream memoryStream = new MemoryStream();
		((XmlObjectSerializer)new DataContractJsonSerializer(typeof(T))).WriteObject((Stream)memoryStream, (object)snapshot);
		return Encoding.UTF8.GetString(memoryStream.ToArray());
	}

	private static T Deserialize<T>(string json)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		using MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json));
		return (T)((XmlObjectSerializer)new DataContractJsonSerializer(typeof(T))).ReadObject((Stream)memoryStream);
	}
}