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.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using BoneLib;
using BoneLib.BoneMenu;
using HarmonyLib;
using Il2CppCysharp.Threading.Tasks;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSLZ.Marrow;
using Il2CppSLZ.Marrow.Data;
using Il2CppSLZ.Marrow.Interaction;
using Il2CppSLZ.Marrow.Pool;
using Il2CppSLZ.Marrow.SceneStreaming;
using Il2CppSLZ.Marrow.Warehouse;
using Il2CppSystem;
using LabFusion.Data;
using LabFusion.Entities;
using LabFusion.Marrow.Messages;
using LabFusion.Marrow.Patching;
using LabFusion.Network;
using LabFusion.Player;
using LabFusion.RPC;
using LabFusion.Scene;
using LabFusion.Utilities;
using MapMemory;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(MapMemoryMod), "Map Memory", "0.1.0", "Codex", null)]
[assembly: MelonGame("Stress Level Zero", "BONELAB")]
[assembly: MelonAdditionalDependencies(new string[] { "BoneLib" })]
[assembly: MelonOptionalDependencies(new string[] { "LabFusion" })]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("MapMemory")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MapMemory")]
[assembly: AssemblyTitle("MapMemory")]
[assembly: AssemblyVersion("1.0.0.0")]
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;
}
}
}
namespace MapMemory
{
internal sealed record LiveLink(ConstraintTracker Tracker, ConstraintTracker Other, Transform First, Transform Second, bool HadJoint, int Mode, Vector Point1, Vector Point2, Vector Normal1, Vector Normal2, Pose CreationPose1, Pose CreationPose2)
{
public Link Describe(Endpoint first, Endpoint second)
{
return new Link(first, second, Mode, Point1, Point2, Normal1, Normal2, CreationPose1, CreationPose2);
}
}
[HarmonyPatch(typeof(Constrainer), "PrimaryButtonUp")]
internal static class ConstraintCapture
{
private sealed record Creation(Transform First, Transform Second, int Mode, Vector Point1, Vector Point2, Vector Normal1, Vector Normal2, Pose Pose1, Pose Pose2, HashSet<int> Prior);
internal static readonly Dictionary<int, LiveLink> Links = new Dictionary<int, LiveLink>();
[HarmonyPrefix]
private static void Prefix(Constrainer __instance, out Creation? __state)
{
//IL_0004: Unknown result type (might be due to invalid IL or missing references)
//IL_000a: Invalid comparison between Unknown and I4
//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_005c: 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_0072: Unknown result type (might be due to invalid IL or missing references)
//IL_00c6: Expected I4, but got Unknown
__state = null;
if ((int)__instance.mode == 6 || __instance._raycastMissedOnDown)
{
return;
}
GameObject gO = __instance._gO1;
GameObject gO2 = __instance._gO2;
if (Object.op_Implicit((Object)(object)gO) && Object.op_Implicit((Object)(object)gO2) && !((Object)(object)gO == (Object)(object)gO2))
{
__state = new Creation(gO.transform, gO2.transform, (int)__instance.mode, Vector.Capture(__instance._point1), Vector.Capture(__instance._point2), Vector.Capture(__instance._normal1), Vector.Capture(__instance._normal2), Pose.Capture(gO.transform), Pose.Capture(gO2.transform), ((IEnumerable<ConstraintTracker>)gO.GetComponents<ConstraintTracker>()).Select((ConstraintTracker t) => ((Object)t).GetInstanceID()).ToHashSet());
}
}
[HarmonyPostfix]
[HarmonyPriority(0)]
private static void Postfix(Creation? __state)
{
if ((object)__state == null || !Object.op_Implicit((Object)(object)__state.First) || !Object.op_Implicit((Object)(object)__state.Second))
{
return;
}
foreach (ConstraintTracker component in ((Component)__state.First).GetComponents<ConstraintTracker>())
{
int instanceID = ((Object)component).GetInstanceID();
if (!__state.Prior.Contains(instanceID) && !Links.ContainsKey(instanceID))
{
ConstraintTracker otherTracker = component.otherTracker;
if (Object.op_Implicit((Object)(object)otherTracker) && !((Object)(object)((Component)otherTracker).gameObject != (Object)(object)((Component)__state.Second).gameObject))
{
Links[instanceID] = new LiveLink(component, otherTracker, __state.First, __state.Second, (Object)(object)component.joint != (Object)null, __state.Mode, __state.Point1, __state.Point2, __state.Normal1, __state.Normal2, __state.Pose1, __state.Pose2);
}
}
}
}
public static void Restore(Constrainer tool, Transform first, Transform second, Link link)
{
//IL_0039: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_005b: Unknown result type (might be due to invalid IL or missing references)
//IL_006c: Unknown result type (might be due to invalid IL or missing references)
Pose pose = Pose.Capture(first);
Pose pose2 = Pose.Capture(second);
try
{
link.CreationPose1.Apply(first);
link.CreationPose2.Apply(second);
tool.mode = (ConstraintMode)link.Mode;
tool._point1 = link.Point1.Value;
tool._point2 = link.Point2.Value;
tool._normal1 = link.Normal1.Value;
tool._normal2 = link.Normal2.Value;
tool._gO1 = ((Component)first).gameObject;
tool._gO2 = ((Component)second).gameObject;
tool._mb1 = ((Component)first).GetComponent<MarrowBody>();
tool._mb2 = ((Component)second).GetComponent<MarrowBody>();
tool._raycastMissedOnDown = false;
tool.PrimaryButtonUp();
}
finally
{
pose.Apply(first);
pose2.Apply(second);
}
}
}
internal enum PlayMode
{
Solo,
Fusion,
Guest
}
internal static class FusionBridge
{
public static bool Installed { get; set; }
public static PlayMode Mode
{
get
{
if (!Installed)
{
return PlayMode.Solo;
}
return GetMode();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static PlayMode GetMode()
{
if (NetworkInfo.HasServer)
{
if (!NetworkInfo.IsHost)
{
return PlayMode.Guest;
}
return PlayMode.Fusion;
}
return PlayMode.Solo;
}
public static bool Ready(bool needsConstrainer)
{
if (NetworkSceneManager.IsLevelNetworked && !FusionSceneManager.IsDelayedLoading())
{
if (needsConstrainer)
{
return ConstrainerUtilities.HasConstrainer;
}
return true;
}
return false;
}
public static void Spawn(Spawnable crate, Pose pose, Action<GameObject?> done)
{
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
//IL_0037: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0044: Unknown result type (might be due to invalid IL or missing references)
//IL_005c: Unknown result type (might be due to invalid IL or missing references)
NetworkAssetSpawner.Spawn(new SpawnRequestInfo
{
Spawnable = crate,
Position = pose.Position.Value,
Rotation = pose.Rotation.Value,
SpawnSource = (EntitySource)2,
SpawnCallback = delegate(SpawnCallbackInfo info)
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
done(info.Spawned);
}
});
}
public static void CreateLink(Transform first, Transform second, Link link)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_0037: Unknown result type (might be due to invalid IL or missing references)
//IL_003c: Unknown result type (might be due to invalid IL or missing references)
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
//IL_005b: Unknown result type (might be due to invalid IL or missing references)
//IL_0060: 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_0072: Unknown result type (might be due to invalid IL or missing references)
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_0078: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: 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_00a9: Unknown result type (might be due to invalid IL or missing references)
//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Expected O, but got Unknown
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00d4: 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)
//IL_00e3: Expected O, but got Unknown
//IL_0106: Unknown result type (might be due to invalid IL or missing references)
ConstrainerPointPair val = new ConstrainerPointPair
{
mode = (ConstraintMode)link.Mode,
go1 = ((Component)first).gameObject,
go2 = ((Component)second).gameObject,
point1 = link.Point1.Value,
point2 = link.Point2.Value,
normal1 = link.Normal1.Value,
normal2 = link.Normal2.Value
};
ConstraintCreateData obj = ConstraintCreateData.Create(PlayerIDManager.LocalSmallID, (ushort?)null, val);
obj.Tracker1Transform = new SerializedTransform(link.CreationPose1.Position.Value, link.CreationPose1.Rotation.Value);
obj.Tracker2Transform = new SerializedTransform(link.CreationPose2.Position.Value, link.CreationPose2.Rotation.Value);
EntityIDList<NetworkEntity> registeredEntities = NetworkEntityManager.IDManager.RegisteredEntities;
obj.Point1Id = registeredEntities.AllocateNewID();
obj.Point2Id = registeredEntities.AllocateNewID();
MessageRelay.RelayModule<ConstraintCreateMessage, ConstraintCreateData>(obj, CommonMessageRoutes.ReliableToClients);
}
}
public sealed class MapMemoryMod : MelonMod
{
private sealed record Baseline(string Address, Rigidbody Body, Poolee Pool, ulong PoolId, Body State, bool Active);
private sealed record ScenePool(string Address, Poolee Pool, ulong Id, Pose Pose, Vector Scale, bool Active);
private const float SaveInterval = 25f;
private const string ConstrainerBarcode = "c1534c5a-3813-49d6-a98c-f595436f6e73";
private static MapMemoryMod _mod;
private readonly Dictionary<int, Baseline> _baseline = new Dictionary<int, Baseline>();
private readonly Dictionary<int, ScenePool> _scenePools = new Dictionary<int, ScenePool>();
private SaveStore _store;
private Page _saves;
private FunctionElement _status;
private MelonPreferences_Entry<bool> _autosave;
private string? _map;
private string _title = "";
private PlayMode _mode;
private float _nextSave;
private int _generation;
private bool _restoring;
private bool _blocked;
private bool _deleted;
private bool _loading;
private bool _switchingMode;
public override void OnInitializeMelon()
{
//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
//IL_00f4: Expected O, but got Unknown
//IL_012f: Unknown result type (might be due to invalid IL or missing references)
//IL_013d: Expected O, but got Unknown
_mod = this;
_store = new SaveStore(Path.Combine(MelonEnvironment.UserDataDirectory, "MapMemory"));
_autosave = MelonPreferences.CreateCategory("MapMemory").CreateEntry<bool>("AutoSave", true, (string)null, (string)null, false, false, (ValueValidator)null, (string)null);
Hooking.OnLevelLoaded += delegate
{
LevelReady();
};
Hooking.OnLevelUnloaded += LevelUnloaded;
Type[][] array = new Type[2][]
{
new Type[2]
{
typeof(Barcode),
typeof(Barcode)
},
new Type[2]
{
typeof(LevelCrateReference),
typeof(LevelCrateReference)
}
};
foreach (Type[] array2 in array)
{
MethodInfo methodInfo = AccessTools.Method(typeof(SceneStreamer), "Load", array2, (Type[])null);
((MelonBase)this).HarmonyInstance.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(MapMemoryMod), "BeforeLevelChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
((MelonBase)this).HarmonyInstance.Patch((MethodBase)AccessTools.Method(typeof(SceneStreamer), "Reload", Type.EmptyTypes, (Type[])null), new HarmonyMethod(typeof(MapMemoryMod), "BeforeLevelChange", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
public override void OnLateInitializeMelon()
{
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
//IL_004c: 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_0095: Unknown result type (might be due to invalid IL or missing references)
//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
FusionBridge.Installed = MelonTypeBase<MelonMod>.RegisteredMelons.Any((MelonMod mod) => ((MelonBase)mod).MelonAssembly.Assembly.GetName().Name == "LabFusion");
Page val = Page.Root.CreatePage("Map Memory", Color.cyan, 0, true);
_status = val.CreateFunction("Waiting for a map", Color.white, (Action)delegate
{
((MelonBase)this).LoggerInstance.Msg(((Element)_status).ElementName);
});
val.CreateBool("Autosave", Color.cyan, _autosave.Value, (Action<bool>)delegate(bool value)
{
_autosave.Value = value;
MelonPreferences.Save();
});
val.CreateFunction("Save Now", Color.green, (Action)delegate
{
Save(manual: true);
});
val.CreateFunction("Refresh Saved Maps", Color.cyan, (Action)RefreshSaves);
_saves = val.CreatePage("Saved Maps", Color.cyan, 9, true);
RefreshSaves();
}
public override void OnUpdate()
{
if (_map != null && !_loading && !_switchingMode)
{
if (_mode != FusionBridge.Mode)
{
_switchingMode = true;
SetStatus("Reload the map for this session");
}
else if (!_restoring && _autosave.Value && Time.realtimeSinceStartup >= _nextSave)
{
Save();
}
}
}
public override void OnApplicationQuit()
{
if (_autosave.Value)
{
Save();
}
}
private static void BeforeLevelChange()
{
if (!_mod._loading && FusionBridge.Mode != PlayMode.Guest && _mod._autosave.Value)
{
_mod.Save();
}
}
private void LevelUnloaded()
{
_generation++;
_loading = true;
_restoring = false;
_map = null;
_baseline.Clear();
_scenePools.Clear();
ConstraintCapture.Links.Clear();
SetStatus("Waiting for a map");
}
private void LevelReady()
{
LevelCrate level = SceneStreamer.Session.Level;
if (Object.op_Implicit((Object)(object)level) && !string.IsNullOrEmpty(((Scannable)level).Barcode.ID))
{
_map = ((Scannable)level).Barcode.ID;
_title = ((Scannable)level).Title;
_mode = FusionBridge.Mode;
_loading = false;
_restoring = true;
_blocked = false;
_deleted = false;
_switchingMode = false;
MelonCoroutines.Start(BeginLevel(++_generation));
}
}
private IEnumerator BeginLevel(int generation)
{
float readyAt = Time.realtimeSinceStartup + 1.5f;
while (Current(generation) && Time.realtimeSinceStartup < readyAt)
{
yield return null;
}
if (!Current(generation))
{
yield break;
}
if (_mode == PlayMode.Guest)
{
Complete(blocked: false, "Only the Fusion host saves");
yield break;
}
IEnumerator restore;
try
{
IdentifySceneProps();
Snapshot snapshot = _store.Read(_map, _mode.ToString());
if ((object)snapshot == null)
{
Complete(blocked: false, "Ready to save");
yield break;
}
restore = Restore(snapshot, generation);
}
catch (Exception error)
{
Failed(error);
yield break;
}
while (Current(generation))
{
object current;
try
{
if (!restore.MoveNext())
{
break;
}
current = restore.Current;
goto IL_0123;
}
catch (Exception error2)
{
Failed(error2);
}
break;
IL_0123:
yield return current;
}
(restore as IDisposable)?.Dispose();
}
private bool Current(int generation)
{
if (generation == _generation && !_loading)
{
return _mode == FusionBridge.Mode;
}
return false;
}
private void IdentifySceneProps()
{
//IL_007b: Unknown result type (might be due to invalid IL or missing references)
_baseline.Clear();
_scenePools.Clear();
foreach (Poolee item in Object.FindObjectsOfType<Poolee>())
{
if (Object.op_Implicit((Object)(object)item) && !item.IsInPool && !IsPlayer(((Component)item).transform))
{
string text = SceneAddress.Of(((Component)item).transform);
if (text != null)
{
_scenePools[((Object)item).GetInstanceID()] = new ScenePool(text, item, item.ID, Pose.Capture(((Component)item).transform), Vector.Capture(((Component)item).transform.localScale), ((Component)item).gameObject.activeSelf);
}
}
}
foreach (Rigidbody item2 in Object.FindObjectsOfType<Rigidbody>(true))
{
if (!Object.op_Implicit((Object)(object)item2) || IsPlayer(((Component)item2).transform))
{
continue;
}
string text2 = SceneAddress.Of(((Component)item2).transform);
if (text2 != null)
{
Poolee componentInParent = ((Component)item2).GetComponentInParent<Poolee>(true);
if (!Object.op_Implicit((Object)(object)componentInParent) || (!componentInParent.IsInPool && _scenePools.ContainsKey(((Object)componentInParent).GetInstanceID())))
{
_baseline[((Object)item2).GetInstanceID()] = new Baseline(text2, item2, componentInParent, Object.op_Implicit((Object)(object)componentInParent) ? componentInParent.ID : 0, Body.Capture("", item2), ((Component)item2).gameObject.activeSelf);
}
}
}
}
private bool IsScenePool(Poolee pool)
{
if (_scenePools.TryGetValue(((Object)pool).GetInstanceID(), out ScenePool value))
{
return value.Id == pool.ID;
}
return false;
}
private static bool IsPlayer(Transform transform)
{
return (Object)(object)((Component)transform).GetComponentInParent<RigManager>(true) != (Object)null;
}
private void Save(bool manual = false)
{
_nextSave = Time.realtimeSinceStartup + 25f;
if (_map == null || _loading || _restoring || _blocked || _switchingMode || _mode == PlayMode.Guest || _mode != FusionBridge.Mode || (_deleted && !manual))
{
if (manual)
{
((MelonBase)this).LoggerInstance.Warning("The current map is unavailable for saving. See the Map Memory status.");
}
return;
}
try
{
Snapshot snapshot = Capture();
bool flag = !_store.Exists(snapshot.Map, snapshot.Mode);
_store.Write(snapshot);
_deleted = false;
SetStatus($"Saved {snapshot.Spawned.Count} props and {snapshot.Constraints.Count} links");
if (manual || flag)
{
RefreshSaves();
}
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Error((object)ex);
SetStatus("Save failed. See MelonLoader log.");
}
}
private Snapshot Capture()
{
//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
//IL_0101: Unknown result type (might be due to invalid IL or missing references)
//IL_0106: Unknown result type (might be due to invalid IL or missing references)
//IL_010b: Unknown result type (might be due to invalid IL or missing references)
//IL_0127: Unknown result type (might be due to invalid IL or missing references)
//IL_013d: Unknown result type (might be due to invalid IL or missing references)
//IL_0226: Unknown result type (might be due to invalid IL or missing references)
//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
List<SceneProp> list = new List<SceneProp>();
foreach (Baseline value in _baseline.Values)
{
if (!Object.op_Implicit((Object)(object)value.Body) || (Object.op_Implicit((Object)(object)value.Pool) && (value.Pool.IsInPool || value.Pool.ID != value.PoolId)))
{
if (!Object.op_Implicit((Object)(object)value.Pool) || !_scenePools.ContainsKey(((Object)value.Pool).GetInstanceID()))
{
list.Add(new SceneProp(value.Address, null, Active: false, Removed: true));
}
continue;
}
Body body = Body.Capture("", value.Body);
bool activeSelf = ((Component)value.Body).gameObject.activeSelf;
if (activeSelf == value.Active)
{
Vector3 val = body.Pose.Position.Value - value.State.Pose.Position.Value;
if (!(((Vector3)(ref val)).sqrMagnitude > 1E-06f) && !(Quaternion.Angle(body.Pose.Rotation.Value, value.State.Pose.Rotation.Value) > 0.1f) && body.Kinematic == value.State.Kinematic && body.Constraints == value.State.Constraints)
{
continue;
}
}
list.Add(new SceneProp(value.Address, body, activeSelf, Removed: false));
}
foreach (ScenePool value2 in _scenePools.Values)
{
Poolee pool = value2.Pool;
if (!Object.op_Implicit((Object)(object)pool) || pool.IsInPool || pool.ID != value2.Id)
{
list.Add(new SceneProp(value2.Address, null, Active: false, Removed: true));
continue;
}
Pose pose = Pose.Capture(((Component)pool).transform);
Vector vector = Vector.Capture(((Component)pool).transform.localScale);
bool activeSelf2 = ((Component)pool).gameObject.activeSelf;
if (activeSelf2 != value2.Active || pose != value2.Pose || vector != value2.Scale)
{
list.Add(new SceneProp(value2.Address, null, activeSelf2, Removed: false, pose, vector));
}
}
List<SpawnedProp> list2 = new List<SpawnedProp>();
Dictionary<int, int> dictionary = new Dictionary<int, int>();
foreach (Poolee item in Object.FindObjectsOfType<Poolee>())
{
if (!Object.op_Implicit((Object)(object)item) || item.IsInPool || !Object.op_Implicit((Object)(object)item.SpawnableCrate) || IsScenePool(item) || IsPlayer(((Component)item).transform) || SceneAddress.Of(((Component)item).transform) == null || (Object.op_Implicit((Object)(object)((Component)item).transform.parent) && Object.op_Implicit((Object)(object)((Component)((Component)item).transform.parent).GetComponentInParent<Poolee>(true))))
{
continue;
}
string iD = ((Scannable)item.SpawnableCrate).Barcode.ID;
if (string.IsNullOrEmpty(iD))
{
continue;
}
int num = list2.Count + 1;
dictionary.Add(((Object)item).GetInstanceID(), num);
List<Body> list3 = new List<Body>();
foreach (Rigidbody componentsInChild in ((Component)item).GetComponentsInChildren<Rigidbody>(true))
{
list3.Add(Body.Capture(SceneAddress.Relative(((Component)item).transform, ((Component)componentsInChild).transform), componentsInChild));
}
list2.Add(new SpawnedProp(num, iD, Pose.Capture(((Component)item).transform), Vector.Capture(((Component)item).transform.localScale), list3));
}
List<Link> list4 = new List<Link>();
KeyValuePair<int, LiveLink>[] array = ConstraintCapture.Links.ToArray();
for (int i = 0; i < array.Length; i++)
{
KeyValuePair<int, LiveLink> keyValuePair = array[i];
var (key, liveLink2) = (KeyValuePair<int, LiveLink>)(ref keyValuePair);
if (!Object.op_Implicit((Object)(object)liveLink2.Tracker) || !Object.op_Implicit((Object)(object)liveLink2.Other) || (liveLink2.HadJoint && !Object.op_Implicit((Object)(object)liveLink2.Tracker.joint)) || !Object.op_Implicit((Object)(object)liveLink2.First) || !Object.op_Implicit((Object)(object)liveLink2.Second) || !((Component)liveLink2.First).gameObject.activeInHierarchy || !((Component)liveLink2.Second).gameObject.activeInHierarchy)
{
ConstraintCapture.Links.Remove(key);
continue;
}
Endpoint endpoint = CaptureEndpoint(liveLink2.First, dictionary);
Endpoint endpoint2 = CaptureEndpoint(liveLink2.Second, dictionary);
if ((object)endpoint != null && (object)endpoint2 != null)
{
list4.Add(liveLink2.Describe(endpoint, endpoint2));
}
}
return new Snapshot(_map, _title, _mode.ToString(), DateTimeOffset.UtcNow, list, list2, list4);
}
private Endpoint? CaptureEndpoint(Transform transform, Dictionary<int, int> ids)
{
if (IsPlayer(transform))
{
return null;
}
Poolee componentInParent = ((Component)transform).GetComponentInParent<Poolee>(true);
if (Object.op_Implicit((Object)(object)componentInParent) && ids.TryGetValue(((Object)componentInParent).GetInstanceID(), out var value))
{
return new Endpoint(value, SceneAddress.Relative(((Component)componentInParent).transform, transform));
}
if (Object.op_Implicit((Object)(object)componentInParent) && (componentInParent.IsInPool || (Object.op_Implicit((Object)(object)componentInParent.SpawnableCrate) && !IsScenePool(componentInParent))))
{
return null;
}
string text = SceneAddress.Of(transform);
if (text == null)
{
return null;
}
return new Endpoint(null, text);
}
private IEnumerator Restore(Snapshot save, int generation)
{
SetStatus("Restoring " + save.Title);
if (_mode == PlayMode.Fusion)
{
float deadline = Time.realtimeSinceStartup + 20f;
while (!FusionBridge.Ready(save.Constraints.Count > 0) && Current(generation) && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
if (!FusionBridge.Ready(save.Constraints.Count > 0))
{
Complete(blocked: true, "Fusion did not finish loading. Save kept.");
yield break;
}
}
SpawnableCrate val = default(SpawnableCrate);
foreach (SpawnedProp item in save.Spawned)
{
if (!AssetWarehouse.Instance.TryGetCrate<SpawnableCrate>(new Barcode(item.Barcode), ref val))
{
((MelonBase)this).LoggerInstance.Warning("Missing spawnable crate " + item.Barcode);
Complete(blocked: true, "Missing content mod. Save kept.");
yield break;
}
}
bool incomplete = false;
Dictionary<int, Transform> restored = new Dictionary<int, Transform>();
foreach (SpawnedProp prop in save.Spawned)
{
GameObject spawned = null;
bool done = false;
Spawnable crate = new Spawnable
{
crateRef = new SpawnableCrateReference(prop.Barcode)
};
if (_mode == PlayMode.Fusion)
{
FusionBridge.Spawn(crate, prop.Pose, OnSpawn);
}
else
{
SpawnLocal(crate, prop.Pose, OnSpawn);
}
float deadline = Time.realtimeSinceStartup + 12f;
while (!done && Current(generation) && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
if (Current(generation))
{
if (!Object.op_Implicit((Object)(object)spawned))
{
((MelonBase)this).LoggerInstance.Warning("Spawn failed for " + prop.Barcode);
incomplete = true;
}
else
{
restored[prop.Id] = spawned.transform;
spawned.transform.localScale = prop.Scale.Value;
}
continue;
}
yield break;
void OnSpawn(GameObject? gameObject)
{
if (Current(generation))
{
spawned = gameObject;
done = true;
}
}
}
Constrainer tool = null;
if (save.Constraints.Count != 0 && _mode == PlayMode.Solo)
{
SpawnableCrate val2 = default(SpawnableCrate);
if (!AssetWarehouse.Instance.TryGetCrate<SpawnableCrate>(new Barcode("c1534c5a-3813-49d6-a98c-f595436f6e73"), ref val2))
{
Complete(blocked: true, "Constrainer crate missing. Save kept.");
yield break;
}
bool done2 = false;
bool accepting = true;
Action<GameObject> action = delegate(GameObject prefab)
{
//IL_003e: Unknown result type (might be due to invalid IL or missing references)
//IL_0043: Unknown result type (might be due to invalid IL or missing references)
if (accepting && Current(generation))
{
if (Object.op_Implicit((Object)(object)prefab))
{
GameObject val5 = Object.Instantiate<GameObject>(prefab, new Vector3(0f, -10000f, 0f), Quaternion.identity);
val5.SetActive(false);
tool = val5.GetComponent<Constrainer>();
if (!Object.op_Implicit((Object)(object)tool))
{
Object.Destroy((Object)(object)val5);
}
}
done2 = true;
}
};
((CrateT<GameObject>)(object)val2).LoadAsset(Action<GameObject>.op_Implicit(action));
float deadline = Time.realtimeSinceStartup + 10f;
while (!done2 && Current(generation) && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
accepting = false;
if (!Object.op_Implicit((Object)(object)tool))
{
incomplete = true;
}
}
try
{
foreach (SpawnedProp item2 in save.Spawned)
{
if (!restored.TryGetValue(item2.Id, out Transform value) || !Object.op_Implicit((Object)(object)value))
{
continue;
}
item2.Pose.Apply(value);
foreach (Body body in item2.Bodies)
{
Transform? obj = SceneAddress.Resolve(value, body.Path);
Rigidbody val3 = ((obj != null) ? ((Component)obj).GetComponent<Rigidbody>() : null);
if (Object.op_Implicit((Object)(object)val3))
{
body.Apply(val3);
}
else
{
incomplete = true;
}
}
}
foreach (SceneProp item3 in save.Scene.OrderBy((SceneProp sceneProp) => (!sceneProp.Removed) ? (((object)sceneProp.RootPose == null) ? 1 : 0) : 2))
{
Transform val4 = SceneAddress.Resolve(item3.Address);
if (!Object.op_Implicit((Object)(object)val4))
{
incomplete = true;
continue;
}
if (item3.Removed)
{
((Component)val4).gameObject.SetActive(false);
continue;
}
if ((object)item3.RootPose != null)
{
item3.RootPose.Apply(val4);
}
if ((object)item3.RootScale != null)
{
val4.localScale = item3.RootScale.Value;
}
Rigidbody component = ((Component)val4).GetComponent<Rigidbody>();
if (Object.op_Implicit((Object)(object)component) && (object)item3.Body != null)
{
item3.Body.Apply(component);
}
((Component)val4).gameObject.SetActive(item3.Active);
}
foreach (Link constraint in save.Constraints)
{
Link link = constraint;
if (!Current(generation))
{
yield break;
}
Transform first = ResolveEndpoint(link.First, restored);
Transform second = ResolveEndpoint(link.Second, restored);
if (!Object.op_Implicit((Object)(object)first) || !Object.op_Implicit((Object)(object)second) || (Object)(object)first == (Object)(object)second)
{
incomplete = true;
continue;
}
int before = CountMatchingLinks();
if (_mode == PlayMode.Fusion)
{
FusionBridge.CreateLink(first, second, link);
}
else if (Object.op_Implicit((Object)(object)tool))
{
ConstraintCapture.Restore(tool, first, second, link);
}
float deadline = Time.realtimeSinceStartup + 2f;
while (_mode == PlayMode.Fusion && Current(generation) && CountMatchingLinks() == before && Time.realtimeSinceStartup < deadline)
{
yield return null;
}
if (!Current(generation))
{
yield break;
}
if (CountMatchingLinks() == before)
{
((MelonBase)this).LoggerInstance.Warning($"Constraint mode {link.Mode} did not restore between {((Object)first).name} and {((Object)second).name}.");
incomplete = true;
}
int CountMatchingLinks()
{
return ConstraintCapture.Links.Values.Count((LiveLink existing) => Object.op_Implicit((Object)(object)existing.Tracker) && Object.op_Implicit((Object)(object)existing.Other) && (Object)(object)existing.First == (Object)(object)first && (Object)(object)existing.Second == (Object)(object)second && existing.Mode == link.Mode);
}
}
}
finally
{
if (Object.op_Implicit((Object)(object)tool))
{
Object.Destroy((Object)(object)((Component)tool).gameObject);
}
}
Complete(incomplete, incomplete ? "Some objects could not restore. Save kept." : $"Restored {save.Spawned.Count} props and {save.Constraints.Count} links");
}
private static Transform? ResolveEndpoint(Endpoint endpoint, Dictionary<int, Transform> restored)
{
int? spawnId = endpoint.SpawnId;
if (spawnId.HasValue)
{
int valueOrDefault = spawnId.GetValueOrDefault();
if (!restored.TryGetValue(valueOrDefault, out Transform value) || !Object.op_Implicit((Object)(object)value))
{
return null;
}
return SceneAddress.Resolve(value, endpoint.Address);
}
return SceneAddress.Resolve(endpoint.Address);
}
private static void SpawnLocal(Spawnable crate, Pose pose, Action<GameObject?> done)
{
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Unknown result type (might be due to invalid IL or missing references)
Nullable<Vector3> val = new Nullable<Vector3>(Vector3.zero)
{
hasValue = false
};
Nullable<int> val2 = new Nullable<int>(0)
{
hasValue = false
};
UniTask<Poolee> val3 = AssetSpawner.SpawnAsync(crate, pose.Position.Value, pose.Rotation.Value, val, (Transform)null, false, val2, (Action<GameObject>)null, (Action<GameObject>)null, (Action<GameObject>)null);
Awaiter<Poolee> awaiter = val3.GetAwaiter();
Action action = delegate
{
Poolee result = awaiter.GetResult();
done(Object.op_Implicit((Object)(object)result) ? ((Component)result).gameObject : null);
};
awaiter.OnCompleted(action);
}
private void Complete(bool blocked, string status)
{
_restoring = false;
_blocked = blocked;
_nextSave = Time.realtimeSinceStartup + 25f;
SetStatus(status);
}
private void Failed(Exception error)
{
((MelonBase)this).LoggerInstance.Error((object)error);
Complete(blocked: true, "Restore failed. Save kept.");
}
private void SetStatus(string status)
{
if (_status != null)
{
((Element)_status).ElementName = status;
}
}
private void RefreshSaves()
{
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00f2: 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_0132: Unknown result type (might be due to invalid IL or missing references)
if (_saves == null)
{
return;
}
foreach (Page indexPage in _saves.IndexPages)
{
indexPage.RemoveAll();
}
_saves.RemoveAll();
foreach (Snapshot save in from snapshot in _store.List()
orderby snapshot.SavedAt descending
select snapshot)
{
Page obj = _saves.CreatePage(save.Title + " (" + save.Mode + ")", Color.white, 0, true);
obj.CreateFunction(save.SavedAt.LocalDateTime.ToString("g"), Color.gray, (Action)delegate
{
});
obj.CreatePage("Delete Save", Color.red, 0, true).CreateFunction("Confirm Delete", Color.red, (Action)delegate
{
Delete(save);
});
}
}
private void Delete(Snapshot save)
{
if (_restoring && _map == save.Map && _mode.ToString() == save.Mode)
{
SetStatus("Wait for the current restore to finish");
return;
}
try
{
if (_store.Delete(save.Map, save.Mode))
{
if (_map == save.Map && _mode.ToString() == save.Mode)
{
_deleted = true;
_blocked = false;
}
SetStatus("Deleted " + save.Title);
RefreshSaves();
Menu.OpenPage(_saves);
}
}
catch (Exception ex)
{
((MelonBase)this).LoggerInstance.Error((object)ex);
SetStatus("Delete failed. See MelonLoader log.");
}
}
}
internal static class SceneAddress
{
public static string? Of(Transform transform)
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
//IL_003a: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_008f: 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)
Scene scene = ((Component)transform).gameObject.scene;
if (!((Scene)(ref scene)).IsValid() || !((Scene)(ref scene)).isLoaded || ((Scene)(ref scene)).name == "DontDestroyOnLoad")
{
return null;
}
int num = 0;
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene sceneAt = SceneManager.GetSceneAt(i);
if (((Scene)(ref sceneAt)).handle == ((Scene)(ref scene)).handle)
{
return SceneKey(scene) + ":" + num + "/" + Relative(null, transform);
}
if (SceneKey(sceneAt) == SceneKey(scene))
{
num++;
}
}
return null;
}
public static string Relative(Transform? root, Transform child)
{
Stack<string> stack = new Stack<string>();
Transform val = child;
while (Object.op_Implicit((Object)(object)val) && (Object)(object)val != (Object)(object)root)
{
stack.Push(val.GetSiblingIndex() + ":" + Encode(((Object)val).name));
val = val.parent;
}
return string.Join("/", stack);
}
public static Transform? Resolve(string address)
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
int num = address.IndexOf('/');
if (num < 0)
{
return null;
}
string text = address.Substring(0, num);
Dictionary<string, int> dictionary = new Dictionary<string, int>();
for (int i = 0; i < SceneManager.sceneCount; i++)
{
Scene sceneAt = SceneManager.GetSceneAt(i);
string text2 = SceneKey(sceneAt);
dictionary.TryGetValue(text2, out var value);
dictionary[text2] = value + 1;
if (!((Scene)(ref sceneAt)).isLoaded || text != text2 + ":" + value)
{
continue;
}
string[] array = address.Substring(num + 1).Split('/');
foreach (GameObject item in (Il2CppArrayBase<GameObject>)(object)((Scene)(ref sceneAt)).GetRootGameObjects())
{
if (Matches(item.transform, array[0]))
{
return Walk(item.transform, array.Skip(1));
}
}
}
return null;
}
public static Transform? Resolve(Transform root, string address)
{
return Walk(root, address.Split('/', StringSplitOptions.RemoveEmptyEntries));
}
private static Transform? Walk(Transform current, IEnumerable<string> parts)
{
foreach (string part in parts)
{
int num = part.IndexOf(':');
if (num < 0 || !int.TryParse(part.Substring(0, num), out var result) || result < 0 || result >= current.childCount)
{
return null;
}
current = current.GetChild(result);
if (!Matches(current, part))
{
return null;
}
}
return current;
}
private static bool Matches(Transform t, string part)
{
return part == t.GetSiblingIndex() + ":" + Encode(((Object)t).name);
}
private static string SceneKey(Scene scene)
{
return Encode(((Scene)(ref scene)).path + "|" + ((Scene)(ref scene)).name);
}
private static string Encode(string name)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(name)).Replace('/', '_');
}
}
internal sealed record Snapshot(string Map, string Title, string Mode, DateTimeOffset SavedAt, List<SceneProp> Scene, List<SpawnedProp> Spawned, List<Link> Constraints, int Version = 1);
internal sealed record Vector(float X, float Y, float Z)
{
[JsonIgnore]
public Vector3 Value => new Vector3(X, Y, Z);
public static Vector Capture(Vector3 value)
{
//IL_0000: 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)
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
return new Vector(value.x, value.y, value.z);
}
}
internal sealed record Rotation(float X, float Y, float Z, float W)
{
[JsonIgnore]
public Quaternion Value => new Quaternion(X, Y, Z, W);
public static Rotation Capture(Quaternion value)
{
//IL_0000: 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)
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
return new Rotation(value.x, value.y, value.z, value.w);
}
}
internal sealed record Pose(Vector Position, Rotation Rotation)
{
public static Pose Capture(Transform t)
{
//IL_0001: Unknown result type (might be due to invalid IL or missing references)
//IL_000c: Unknown result type (might be due to invalid IL or missing references)
return new Pose(Vector.Capture(t.position), MapMemory.Rotation.Capture(t.rotation));
}
public void Apply(Transform t)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
t.SetPositionAndRotation(Position.Value, Rotation.Value);
}
}
internal sealed record Body(string Path, Pose Pose, Vector Velocity, Vector Spin, bool Kinematic, int Constraints)
{
public static Body Capture(string path, Rigidbody body)
{
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_0018: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Expected I4, but got Unknown
return new Body(path, MapMemory.Pose.Capture(((Component)body).transform), Vector.Capture(body.velocity), Vector.Capture(body.angularVelocity), body.isKinematic, (int)body.constraints);
}
public void Apply(Rigidbody body)
{
//IL_001d: Unknown result type (might be due to invalid IL or missing references)
//IL_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
//IL_0075: Unknown result type (might be due to invalid IL or missing references)
Pose.Apply(((Component)body).transform);
body.position = Pose.Position.Value;
body.rotation = Pose.Rotation.Value;
body.constraints = (RigidbodyConstraints)Constraints;
body.isKinematic = Kinematic;
if (!Kinematic)
{
body.velocity = Velocity.Value;
body.angularVelocity = Spin.Value;
}
}
}
internal sealed record SceneProp(string Address, Body? Body, bool Active, bool Removed, Pose? RootPose = null, Vector? RootScale = null);
internal sealed record SpawnedProp(int Id, string Barcode, Pose Pose, Vector Scale, List<Body> Bodies);
internal sealed record Endpoint(int? SpawnId, string Address);
internal sealed record Link(Endpoint First, Endpoint Second, int Mode, Vector Point1, Vector Point2, Vector Normal1, Vector Normal2, Pose CreationPose1, Pose CreationPose2);
internal sealed class SaveStore
{
private readonly string _folder;
public SaveStore(string folder)
{
_folder = folder;
Directory.CreateDirectory(folder);
}
private string PathFor(string map, string mode)
{
return Path.Combine(_folder, Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(mode + "\n" + map))) + ".json");
}
public bool Exists(string map, string mode)
{
return File.Exists(PathFor(map, mode));
}
public Snapshot? Read(string map, string mode)
{
string path = PathFor(map, mode);
if (!File.Exists(path))
{
return null;
}
Snapshot snapshot = ReadFile(path);
if (snapshot.Map != map || snapshot.Mode != mode)
{
throw new InvalidDataException("Save identity does not match this map.");
}
return snapshot;
}
public void Write(Snapshot save)
{
string text = PathFor(save.Map, save.Mode);
string text2 = text + ".tmp";
using (FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write, FileShare.None))
{
JsonSerializer.Serialize(fileStream, save);
fileStream.Flush(flushToDisk: true);
}
File.Move(text2, text, overwrite: true);
}
public bool Delete(string map, string mode)
{
string path = PathFor(map, mode);
if (!File.Exists(path))
{
return false;
}
File.Delete(path);
return true;
}
public IEnumerable<Snapshot> List()
{
foreach (string item in Directory.EnumerateFiles(_folder, "*.json"))
{
Snapshot snapshot;
try
{
snapshot = ReadFile(item);
}
catch (IOException)
{
continue;
}
catch (InvalidDataException)
{
continue;
}
catch (JsonException)
{
continue;
}
yield return snapshot;
}
}
private static Snapshot ReadFile(string path)
{
using FileStream utf8Json = File.OpenRead(path);
Snapshot snapshot = JsonSerializer.Deserialize<Snapshot>(utf8Json);
if ((object)snapshot == null || snapshot.Version != 1 || string.IsNullOrWhiteSpace(snapshot.Map) || (snapshot.Mode != "Solo" && snapshot.Mode != "Fusion") || snapshot.Scene == null || snapshot.Spawned == null || snapshot.Constraints == null)
{
throw new InvalidDataException("Unrecognized Map Memory save.");
}
return snapshot;
}
}
}