Decompiled source of Nivalis Modding Toolkit v0.0.2

plugins/modules/NpcInspector.Feature.module

Decompiled an hour ago
using System;
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.Text.Json;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using Nivalis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("NpcInspector.Feature")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("NpcInspector.Feature")]
[assembly: AssemblyTitle("NpcInspector.Feature")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	public sealed class InspectorModule : IFeatureModule, IReloadableModule, IDisposable
	{
		private sealed record ViewState(bool Visible, bool IncludeInactive);

		private ModuleServices services;

		private NpcOverlay overlay;

		public void Configure(ModuleServices services)
		{
			this.services = services;
		}

		public void Initialize(Action<string> log, string? state)
		{
			ViewState viewState = ((state == null) ? new ViewState(Visible: false, IncludeInactive: false) : JsonSerializer.Deserialize<ViewState>(state));
			overlay = new NpcOverlay(log, viewState.Visible, viewState.IncludeInactive);
		}

		public string CaptureState()
		{
			return JsonSerializer.Serialize(new ViewState(overlay.Visible, overlay.IncludeInactive));
		}

		public void Update()
		{
			overlay.Update();
			services.InspectorOpen = overlay.Visible;
		}

		public void OnGUI()
		{
			overlay.OnGUI();
		}

		public void Dispose()
		{
			overlay?.Dispose();
			services.InspectorOpen = false;
		}
	}
	internal sealed class NpcOverlay : IDisposable
	{
		private readonly Action<string> log;

		private bool refreshPending;

		private NpcRow[] rows = Array.Empty<NpcRow>();

		private bool visible;

		private bool includeInactive;

		private int page;

		private string status = "No snapshot yet";

		private GUIStyle? textStyle;

		private static readonly string OutputPath = Path.Combine(ToolkitPaths.Data, "npcs.json");

		private int PageSize => Math.Max(1, (Screen.height - 150) / 24);

		public bool Visible => visible;

		public bool IncludeInactive => includeInactive;

		public NpcOverlay(Action<string> log, bool visible, bool includeInactive)
		{
			this.log = log;
			this.visible = visible;
			this.includeInactive = includeInactive;
			refreshPending = visible;
		}

		public void Close()
		{
			visible = false;
			refreshPending = false;
			rows = Array.Empty<NpcRow>();
			textStyle = null;
		}

		public void Dispose()
		{
			Close();
		}

		public void Update()
		{
			if (refreshPending)
			{
				refreshPending = false;
				Refresh();
			}
			Keyboard current = Keyboard.current;
			if (current == null)
			{
				return;
			}
			if (((ButtonControl)current.f8Key).wasPressedThisFrame)
			{
				visible = !visible;
				if (visible)
				{
					Refresh();
				}
			}
			if (((ButtonControl)current.f9Key).wasPressedThisFrame)
			{
				Refresh();
			}
			if (visible)
			{
				if (((ButtonControl)current.f10Key).wasPressedThisFrame)
				{
					includeInactive = !includeInactive;
					Refresh();
				}
				int val = Math.Max(0, (rows.Length - 1) / PageSize);
				if (((ButtonControl)current.pageDownKey).wasPressedThisFrame)
				{
					page = Math.Min(page + 1, val);
				}
				if (((ButtonControl)current.pageUpKey).wasPressedThisFrame)
				{
					page = Math.Max(page - 1, 0);
				}
				page = Math.Min(page, val);
			}
		}

		private void Refresh()
		{
			try
			{
				NpcSnapshot npcSnapshot = NpcReader.Capture(includeInactive, log);
				rows = npcSnapshot.Npcs;
				page = 0;
				Directory.CreateDirectory(Path.GetDirectoryName(OutputPath));
				File.WriteAllText(OutputPath + ".tmp", JsonSerializer.Serialize(npcSnapshot, new JsonSerializerOptions
				{
					WriteIndented = true
				}));
				File.Move(OutputPath + ".tmp", OutputPath, overwrite: true);
				status = $"{rows.Length} NPCs | {npcSnapshot.CapturedAt:HH:mm:ss} | skipped {npcSnapshot.Skipped} | JSON saved";
				log(status + ": " + OutputPath);
			}
			catch (Exception ex)
			{
				status = "Refresh/export failed; see BepInEx/LogOutput.log. Previous snapshot may be stale.";
				log(ex.ToString());
			}
		}

		public void OnGUI()
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: 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_0035: Expected O, but got Unknown
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			if (!visible)
			{
				return;
			}
			if (textStyle == null)
			{
				textStyle = new GUIStyle(GUI.skin.label)
				{
					fontSize = 16,
					wordWrap = false
				};
			}
			float num = Math.Min(Screen.width - 24, 1200);
			GUI.Box(new Rect(12f, 12f, num, (float)Math.Min(Screen.height - 24, 125 + PageSize * 24)), "");
			GUI.Label(new Rect(24f, 20f, num - 24f, 24f), "NPC Inspector (hotload) [" + typeof(NpcOverlay).Module.ModuleVersionId.ToString().Substring(0, 8) + "] | F8 close | F9 refresh | PgUp/PgDn | F10 inactive", textStyle);
			GUI.Label(new Rect(24f, 46f, num - 24f, 24f), status, textStyle);
			GUI.Label(new Rect(24f, 72f, num - 24f, 24f), $"Snapshot | all loaded scenes | inactive: {includeInactive} | page {page + 1}/{Math.Max(1, (rows.Length + PageSize - 1) / PageSize)}", textStyle);
			int num2 = page * PageSize;
			for (int i = num2; i < Math.Min(rows.Length, num2 + PageSize); i++)
			{
				NpcRow npcRow = rows[i];
				float? distanceFromCamera = npcRow.DistanceFromCamera;
				object obj;
				if (distanceFromCamera.HasValue)
				{
					float valueOrDefault = distanceFromCamera.GetValueOrDefault();
					obj = $"{valueOrDefault:0.0}m";
				}
				else
				{
					obj = "?m";
				}
				string value = (string)obj;
				string text = $"{value} | #{npcRow.InstanceId} | {npcRow.ObjectName} | {npcRow.CharacterType} | {npcRow.Scene}";
				if (!npcRow.Active)
				{
					text += " [inactive]";
				}
				GUI.Label(new Rect(24f, (float)(104 + (i - num2) * 24), num - 24f, 24f), text, textStyle);
			}
		}
	}
	internal static class NpcReader
	{
		public static NpcSnapshot Capture(bool includeInactive, Action<string> log)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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: 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_011c: 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)
			List<NpcRow> list = new List<NpcRow>();
			Camera main = Camera.main;
			int num = 0;
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Character>()))
			{
				Character val = ((Il2CppObjectBase)item).Cast<Character>();
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				GameObject gameObject = ((Component)val).gameObject;
				Scene scene = gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded && (includeInactive || gameObject.activeInHierarchy))
				{
					try
					{
						Vector3 position = ((Component)val).transform.position;
						CharacterCommunication communication = val.Communication;
						Transform val2 = (((Object)(object)communication == (Object)null) ? null : communication.Head);
						list.Add(new NpcRow(((Object)val).GetInstanceID(), ((Object)gameObject).name, ((Scene)(ref scene)).name, ((Scene)(ref scene)).handle, HierarchyPath(((Component)val).transform), ((object)val.Type/*cast due to .constrained prefix*/).ToString(), gameObject.activeInHierarchy, ((Behaviour)val).enabled, new Point(position.x, position.y, position.z), ((Object)(object)main == (Object)null) ? ((float?)null) : new float?(Vector3.Distance(((Component)main).transform.position, position)), (Object)(object)val.DialogueInteraction != (Object)null, ((Object)(object)val2 == (Object)null) ? null : HierarchyPath(val2)));
					}
					catch (Exception ex)
					{
						num++;
						log("Could not inspect NPC " + ((Object)gameObject).name + ": " + ex.Message);
					}
				}
			}
			NpcRow[] array = (from row in list
				orderby row.DistanceFromCamera ?? float.MaxValue, row.Scene, row.InstanceId
				select row).ToArray();
			DateTimeOffset now = DateTimeOffset.Now;
			Scene activeScene = SceneManager.GetActiveScene();
			return new NpcSnapshot(now, ((Scene)(ref activeScene)).name, "Nivalis.Character objects in all loaded scenes, including persistent objects; prefab assets excluded", includeInactive, num, array.Length, array);
		}

		private static string HierarchyPath(Transform transform)
		{
			List<string> list = new List<string>();
			Transform val = transform;
			while ((Object)(object)val != (Object)null)
			{
				list.Add($"{((Object)val).name}[{val.GetSiblingIndex()}]");
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}
	}
	public sealed record Point(float X, float Y, float Z);
	public sealed record NpcRow(int InstanceId, string ObjectName, string Scene, int SceneHandle, string HierarchyPath, string CharacterType, bool Active, bool ComponentEnabled, Point Position, float? DistanceFromCamera, bool HasDialogueInteraction, string? HeadTransformPath);
	public sealed record NpcSnapshot(DateTimeOffset CapturedAt, string ActiveScene, string Scope, bool IncludeInactive, int Skipped, int Count, NpcRow[] Npcs);
}

plugins/modules/SceneObjectEditor.Feature.module

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using Nivalis;
using Nivalis.Dialogue;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SceneObjectEditor.Feature")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("SceneObjectEditor.Feature")]
[assembly: AssemblyTitle("SceneObjectEditor.Feature")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	internal sealed class EditHistory
	{
		private readonly Stack<Action> undo = new Stack<Action>();

		public const int Capacity = 256;

		public int Count => undo.Count;

		public void Apply(Action change, Action restore)
		{
			if (Count >= 256)
			{
				throw new InvalidOperationException("256 edits reached. Undo or reset the session first.");
			}
			undo.Push(restore);
			try
			{
				change();
			}
			catch
			{
				Undo();
				throw;
			}
		}

		public void Undo()
		{
			if (undo.Count != 0)
			{
				undo.Peek()();
				undo.Pop();
			}
		}

		public void Reset()
		{
			List<Exception> list = null;
			Action result;
			while (undo.TryPop(out result))
			{
				try
				{
					result();
				}
				catch (Exception item)
				{
					(list ?? (list = new List<Exception>())).Add(item);
				}
			}
			if (list != null)
			{
				throw new AggregateException("Some scene edits could not be restored.", list);
			}
		}
	}
	internal sealed class EditorInput : IDisposable
	{
		private GameObject? root;

		private UIPanel? panel;

		private readonly List<InputAction> actions = new List<InputAction>();

		public bool Active => (Object)(object)root != (Object)null;

		internal bool PauseRegistered
		{
			get
			{
				UIManager val = default(UIManager);
				if ((Object)(object)panel != (Object)null && Singleton<UIManager>.InstanceExist(ref val) && val._pauseTimePanels.Contains(panel))
				{
					return val._pauseLock != null;
				}
				return false;
			}
		}

		public bool Obscured()
		{
			UIManager val = default(UIManager);
			if (!Application.isFocused || (Object)(object)Camera.main == (Object)null || !Singleton<UIManager>.InstanceExist(ref val))
			{
				return true;
			}
			if ((Object)(object)DialogueUI._instance != (Object)null && ((UIWindow)DialogueUI._instance)._isOpen)
			{
				return true;
			}
			Enumerator<UIPanel> enumerator = val._openPanels.GetEnumerator();
			while (enumerator.MoveNext())
			{
				UIPanel current = enumerator.Current;
				if ((Object)(object)current != (Object)null && (Object)(object)current != (Object)(object)panel && current.IsVisible && (current.requiresMouse || current.PauseTime))
				{
					return true;
				}
			}
			if (!Active)
			{
				if (!val.IsPointerRequired)
				{
					return Time.timeScale == 0f;
				}
				return true;
			}
			return false;
		}

		public void Open()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			if (Active || Obscured())
			{
				return;
			}
			try
			{
				root = new GameObject("Scene Object Editor input");
				root.SetActive(false);
				CanvasGroup canvasGroup = root.AddComponent<CanvasGroup>();
				panel = root.AddComponent<UIPanel>();
				panel._canvasGroup = canvasGroup;
				panel._startVisible = true;
				panel.requiresMouse = true;
				panel.pauseTimeWhenOpen = true;
				panel.pauseTimeCompletely = true;
				panel.closeWithCancel = false;
				panel.closeWithPause = false;
				panel.fadeTime = new OptionalFloat(0f, true);
				root.SetActive(true);
				panel.SetVisible(true);
				Enumerator<InputAction> enumerator = InputSystem.ListEnabledActions().GetEnumerator();
				while (enumerator.MoveNext())
				{
					InputAction current = enumerator.Current;
					actions.Add(current);
				}
				foreach (InputAction action in actions)
				{
					action.Disable();
				}
			}
			catch
			{
				Dispose();
				throw;
			}
		}

		public void Dispose()
		{
			List<Exception> list = null;
			try
			{
				if ((Object)(object)panel != (Object)null)
				{
					panel.SetVisible(false);
				}
			}
			catch (Exception item)
			{
				(list ?? (list = new List<Exception>())).Add(item);
			}
			try
			{
				if ((Object)(object)root != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)root);
				}
			}
			catch (Exception item2)
			{
				(list ?? (list = new List<Exception>())).Add(item2);
			}
			finally
			{
				root = null;
				panel = null;
			}
			foreach (InputAction action in actions)
			{
				try
				{
					action.Enable();
				}
				catch (Exception item3)
				{
					(list ?? (list = new List<Exception>())).Add(item3);
				}
			}
			actions.Clear();
			if (list != null)
			{
				throw new AggregateException("Editor input cleanup failed.", list);
			}
		}
	}
	internal sealed class PropVisual
	{
		internal sealed record Part(Mesh Mesh, Material Material, int Submesh, Matrix4x4 LocalMatrix, MaterialPropertyBlock Properties, ShadowCastingMode Shadows, bool ReceiveShadows, int Layer)
		{
			[CompilerGenerated]
			public void Deconstruct(out Mesh Mesh, out Material Material, out int Submesh, out Matrix4x4 LocalMatrix, out MaterialPropertyBlock Properties, out ShadowCastingMode Shadows, out bool ReceiveShadows, out int Layer)
			{
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0020: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: Expected I4, but got Unknown
				Mesh = this.Mesh;
				Material = this.Material;
				Submesh = this.Submesh;
				LocalMatrix = this.LocalMatrix;
				Properties = this.Properties;
				Shadows = (ShadowCastingMode)(int)this.Shadows;
				ReceiveShadows = this.ReceiveShadows;
				Layer = this.Layer;
			}
		}

		public readonly List<Part> Parts = new List<Part>();

		public GameObject Root { get; }

		public Bounds LocalBounds { get; }

		public Bounds Bounds => TransformBounds(Root.transform.localToWorldMatrix, LocalBounds);

		public PropVisual(GameObject root, GameObject source)
		{
			//IL_001f: 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_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0206: Expected O, but got Unknown
			//IL_0227: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			Root = root;
			LocalBounds = TransformBounds(root.transform.worldToLocalMatrix, SceneEdits.BoundsOf(source));
			HashSet<int> hashSet = new HashSet<int>();
			foreach (LODGroup componentsInChild in source.GetComponentsInChildren<LODGroup>(true))
			{
				Il2CppReferenceArray<LOD> lODs = componentsInChild.GetLODs();
				if (((Il2CppArrayBase<LOD>)(object)lODs).Length == 0)
				{
					continue;
				}
				HashSet<int> hashSet2 = (from r in (IEnumerable<Renderer>)((Il2CppArrayBase<LOD>)(object)lODs)[0].renderers
					where (Object)(object)r != (Object)null
					select ((Object)r).GetInstanceID()).ToHashSet();
				foreach (LOD item in ((IEnumerable<LOD>)lODs).Skip(1))
				{
					foreach (Renderer item2 in (Il2CppArrayBase<Renderer>)(object)item.renderers)
					{
						if ((Object)(object)item2 != (Object)null && !hashSet2.Contains(((Object)item2).GetInstanceID()))
						{
							hashSet.Add(((Object)item2).GetInstanceID());
						}
					}
				}
			}
			foreach (MeshRenderer componentsInChild2 in source.GetComponentsInChildren<MeshRenderer>())
			{
				if (((Renderer)componentsInChild2).forceRenderingOff || hashSet.Contains(((Object)componentsInChild2).GetInstanceID()))
				{
					continue;
				}
				MeshFilter component = ((Component)componentsInChild2).GetComponent<MeshFilter>();
				Mesh val = ((component != null) ? component.sharedMesh : null);
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				Il2CppReferenceArray<Material> sharedMaterials = ((Renderer)componentsInChild2).sharedMaterials;
				int num = (((Renderer)componentsInChild2).isPartOfStaticBatch ? componentsInChild2.subMeshStartIndex : 0);
				Matrix4x4 localMatrix = root.transform.worldToLocalMatrix * ((Renderer)componentsInChild2).localToWorldMatrix;
				for (int num2 = 0; num2 < ((Il2CppArrayBase<Material>)(object)sharedMaterials).Length && num + num2 < val.subMeshCount; num2++)
				{
					if (!((Object)(object)((Il2CppArrayBase<Material>)(object)sharedMaterials)[num2] == (Object)null))
					{
						MaterialPropertyBlock val2 = new MaterialPropertyBlock();
						((Renderer)componentsInChild2).GetPropertyBlock(val2, num2);
						Parts.Add(new Part(val, ((Il2CppArrayBase<Material>)(object)sharedMaterials)[num2], num + num2, localMatrix, val2, ((Renderer)componentsInChild2).shadowCastingMode, ((Renderer)componentsInChild2).receiveShadows, ((Component)componentsInChild2).gameObject.layer));
					}
				}
			}
			if (Parts.Count == 0)
			{
				throw new InvalidOperationException("This group has no available mesh/material geometry.");
			}
		}

		public PropVisual(GameObject root, PropVisual source)
		{
			//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)
			Root = root;
			LocalBounds = source.LocalBounds;
			Parts.AddRange(source.Parts);
		}

		public void Draw()
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: 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)
			if ((Object)(object)Root == (Object)null || !Root.activeInHierarchy)
			{
				return;
			}
			foreach (Part part in Parts)
			{
				if ((Object)(object)part.Mesh != (Object)null && (Object)(object)part.Material != (Object)null)
				{
					Graphics.DrawMesh(part.Mesh, Root.transform.localToWorldMatrix * part.LocalMatrix, part.Material, part.Layer, (Camera)null, part.Submesh, part.Properties, part.Shadows, part.ReceiveShadows);
				}
			}
		}

		public static Bounds TransformBounds(Matrix4x4 matrix, Bounds bounds)
		{
			//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_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			Bounds result = default(Bounds);
			((Bounds)(ref result))..ctor(((Matrix4x4)(ref matrix)).MultiplyPoint3x4(((Bounds)(ref bounds)).center), Vector3.zero);
			for (int i = -1; i <= 1; i += 2)
			{
				for (int j = -1; j <= 1; j += 2)
				{
					for (int k = -1; k <= 1; k += 2)
					{
						((Bounds)(ref result)).Encapsulate(((Matrix4x4)(ref matrix)).MultiplyPoint3x4(((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)i, (float)j, (float)k))));
					}
				}
			}
			return result;
		}
	}
	internal sealed class SceneEdits
	{
		public readonly EditHistory History = new EditHistory();

		private readonly HashSet<int> owned = new HashSet<int>();

		private readonly Dictionary<int, PropVisual> visuals = new Dictionary<int, PropVisual>();

		private readonly List<GameObject> hiddenRoots = new List<GameObject>();

		public GameObject? Selected { get; set; }

		public Bounds SelectionBounds
		{
			get
			{
				//IL_0044: 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_003c: Unknown result type (might be due to invalid IL or missing references)
				//IL_004d: Unknown result type (might be due to invalid IL or missing references)
				if (!((Object)(object)Selected != (Object)null) || !visuals.TryGetValue(((Object)Selected).GetInstanceID(), out PropVisual value))
				{
					if (!((Object)(object)Selected == (Object)null))
					{
						return BoundsOf(Selected);
					}
					return default(Bounds);
				}
				return value.Bounds;
			}
		}

		internal PropVisual? VisualFor(GameObject obj)
		{
			return visuals.GetValueOrDefault(((Object)obj).GetInstanceID());
		}

		public static bool Loaded(GameObject? obj)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//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)
			if ((Object)(object)obj != (Object)null)
			{
				Scene scene = obj.scene;
				if (((Scene)(ref scene)).IsValid())
				{
					scene = obj.scene;
					return ((Scene)(ref scene)).isLoaded;
				}
			}
			return false;
		}

		public GameObject? OwnedRoot(GameObject obj)
		{
			Transform val = obj.transform;
			while ((Object)(object)val != (Object)null)
			{
				if (owned.Contains(((Object)((Component)val).gameObject).GetInstanceID()))
				{
					return ((Component)val).gameObject;
				}
				val = val.parent;
			}
			return null;
		}

		public string? Rejection(GameObject? obj)
		{
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011a: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			if (!Loaded(obj) || !obj.activeInHierarchy)
			{
				return "Object is no longer active in a loaded scene.";
			}
			if (owned.Contains(((Object)obj).GetInstanceID()))
			{
				return null;
			}
			foreach (GameObject hiddenRoot in hiddenRoots)
			{
				if ((Object)(object)hiddenRoot != (Object)null && (hiddenRoot.transform.IsChildOf(obj.transform) || obj.transform.IsChildOf(hiddenRoot.transform)))
				{
					return "This group overlaps an earlier edit. Undo it before selecting its parent.";
				}
			}
			if ((Object)(object)obj.GetComponentInParent<Character>() != (Object)null || (Object)(object)obj.GetComponentInParent<PlayerCharacter>() != (Object)null || (Object)(object)obj.GetComponentInParent<Rigidbody>() != (Object)null || (Object)(object)obj.GetComponentInParent<Animator>() != (Object)null)
			{
				return "Characters and player hierarchies are protected.";
			}
			Il2CppArrayBase<Transform> componentsInChildren = obj.GetComponentsInChildren<Transform>(true);
			if (componentsInChildren.Length > 256)
			{
				return "Select a smaller prop group (256 transforms maximum).";
			}
			Il2CppArrayBase<MeshRenderer> componentsInChildren2 = obj.GetComponentsInChildren<MeshRenderer>();
			if (componentsInChildren2.Length == 0 || componentsInChildren2.Length > 128)
			{
				return "Select a prop containing 1–128 mesh renderers.";
			}
			Bounds val = BoundsOf(obj);
			Vector3 size = ((Bounds)(ref val)).size;
			if (((Vector3)(ref size)).magnitude > 30f)
			{
				return "Select a smaller prop group (30 m bounds maximum).";
			}
			foreach (Transform item in componentsInChildren)
			{
				foreach (Component component in ((Component)item).GetComponents<Component>())
				{
					if ((Object)(object)((Il2CppObjectBase)component).TryCast<MonoBehaviour>() != (Object)null || (Object)(object)((Il2CppObjectBase)component).TryCast<Rigidbody>() != (Object)null || (Object)(object)((Il2CppObjectBase)component).TryCast<Animator>() != (Object)null || (Object)(object)((Il2CppObjectBase)component).TryCast<SkinnedMeshRenderer>() != (Object)null || (Object)(object)((Il2CppObjectBase)component).TryCast<Camera>() != (Object)null)
					{
						return "Gameplay/dynamic component: " + ((MemberInfo)((Object)component).GetIl2CppType()).Name + ". Select a mesh child instead.";
					}
				}
			}
			return null;
		}

		public static Bounds BoundsOf(GameObject obj)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//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_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			Il2CppArrayBase<MeshRenderer> componentsInChildren = obj.GetComponentsInChildren<MeshRenderer>();
			if (componentsInChildren.Length == 0)
			{
				return new Bounds(obj.transform.position, Vector3.zero);
			}
			Bounds bounds = ((Renderer)componentsInChildren[0]).bounds;
			foreach (MeshRenderer item in ((IEnumerable<MeshRenderer>)componentsInChildren).Skip(1))
			{
				((Bounds)(ref bounds)).Encapsulate(((Renderer)item).bounds);
			}
			return bounds;
		}

		public void Draw()
		{
			foreach (PropVisual value in visuals.Values)
			{
				value.Draw();
			}
		}

		public unsafe GameObject Create(PrimitiveType type, Vector3 position)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			GameObject created = null;
			History.Apply(delegate
			{
				//IL_0002: 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)
				created = GameObject.CreatePrimitive(type);
				((Object)created).name = "Editor " + ((object)(*(PrimitiveType*)(&type))/*cast due to .constrained prefix*/).ToString();
				created.transform.position = position;
				owned.Add(((Object)created).GetInstanceID());
				Selected = created;
				Physics.SyncTransforms();
			}, delegate
			{
				Remove(created);
			});
			return created;
		}

		private GameObject MakeCopy(GameObject source)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_001f: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(((Object)source).name + " (editor copy)");
			val.SetActive(false);
			try
			{
				SceneManager.MoveGameObjectToScene(val, source.scene);
				val.transform.SetPositionAndRotation(source.transform.position, source.transform.rotation);
				val.transform.localScale = source.transform.lossyScale;
				PropVisual value;
				PropVisual propVisual = (visuals.TryGetValue(((Object)source).GetInstanceID(), out value) ? new PropVisual(val, value) : new PropVisual(val, source));
				CopyColliders(source.transform, val.transform);
				if (val.GetComponentsInChildren<Collider>(true).Length == 0)
				{
					BoxCollider obj = val.AddComponent<BoxCollider>();
					Bounds localBounds = propVisual.LocalBounds;
					obj.center = ((Bounds)(ref localBounds)).center;
					localBounds = propVisual.LocalBounds;
					obj.size = ((Bounds)(ref localBounds)).size;
				}
				visuals.Add(((Object)val).GetInstanceID(), propVisual);
				owned.Add(((Object)val).GetInstanceID());
				val.SetActive(true);
				Physics.SyncTransforms();
				return val;
			}
			catch
			{
				Object.DestroyImmediate((Object)(object)val);
				throw;
			}
		}

		private static void CopyColliders(Transform source, Transform target)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			((Component)target).gameObject.layer = ((Component)source).gameObject.layer;
			foreach (Collider component in ((Component)source).GetComponents<Collider>())
			{
				if (!component.enabled || component.isTrigger)
				{
					continue;
				}
				Collider val = null;
				BoxCollider val2 = ((Il2CppObjectBase)component).TryCast<BoxCollider>();
				if (val2 != null)
				{
					BoxCollider obj = ((Component)target).gameObject.AddComponent<BoxCollider>();
					obj.center = val2.center;
					obj.size = val2.size;
					val = (Collider)(object)obj;
				}
				else
				{
					SphereCollider val3 = ((Il2CppObjectBase)component).TryCast<SphereCollider>();
					if (val3 != null)
					{
						SphereCollider obj2 = ((Component)target).gameObject.AddComponent<SphereCollider>();
						obj2.center = val3.center;
						obj2.radius = val3.radius;
						val = (Collider)(object)obj2;
					}
					else
					{
						CapsuleCollider val4 = ((Il2CppObjectBase)component).TryCast<CapsuleCollider>();
						if (val4 != null)
						{
							CapsuleCollider obj3 = ((Component)target).gameObject.AddComponent<CapsuleCollider>();
							obj3.center = val4.center;
							obj3.radius = val4.radius;
							obj3.height = val4.height;
							obj3.direction = val4.direction;
							val = (Collider)(object)obj3;
						}
						else
						{
							MeshCollider val5 = ((Il2CppObjectBase)component).TryCast<MeshCollider>();
							if (val5 != null)
							{
								MeshCollider obj4 = ((Component)target).gameObject.AddComponent<MeshCollider>();
								obj4.sharedMesh = val5.sharedMesh;
								obj4.convex = val5.convex;
								val = (Collider)(object)obj4;
							}
						}
					}
				}
				if ((Object)(object)val != (Object)null)
				{
					val.sharedMaterial = component.sharedMaterial;
				}
			}
			for (int i = 0; i < source.childCount; i++)
			{
				Transform child = source.GetChild(i);
				if (((Component)child).gameObject.activeSelf)
				{
					GameObject val6 = new GameObject(((Object)child).name);
					val6.transform.SetParent(target, false);
					val6.transform.localPosition = child.localPosition;
					val6.transform.localRotation = child.localRotation;
					val6.transform.localScale = child.localScale;
					CopyColliders(child, val6.transform);
				}
			}
		}

		public GameObject Copy()
		{
			GameObject source = RequireSelection();
			GameObject copy = null;
			History.Apply(delegate
			{
				//IL_0023: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: 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)
				copy = MakeCopy(source);
				Transform transform = copy.transform;
				transform.position += Vector3.right * 0.5f;
				Selected = copy;
				Physics.SyncTransforms();
			}, delegate
			{
				Remove(copy);
			});
			return copy;
		}

		private (Action Hide, Action Restore) Visibility(GameObject source)
		{
			(Renderer Renderer, bool Hidden)[] renderers = ((IEnumerable<Renderer>)source.GetComponentsInChildren<Renderer>(true)).Select((Renderer r) => (Renderer: r, Hidden: r.forceRenderingOff)).ToArray();
			(Collider Collider, bool Enabled)[] colliders = ((IEnumerable<Collider>)source.GetComponentsInChildren<Collider>(true)).Select((Collider c) => (Collider: c, Enabled: c.enabled)).ToArray();
			return (Hide: delegate
			{
				hiddenRoots.Add(source);
				(Renderer, bool)[] array = renderers;
				for (int i = 0; i < array.Length; i++)
				{
					Renderer item = array[i].Item1;
					if ((Object)(object)item != (Object)null)
					{
						item.forceRenderingOff = true;
					}
				}
				(Collider, bool)[] array2 = colliders;
				for (int i = 0; i < array2.Length; i++)
				{
					Collider item2 = array2[i].Item1;
					if ((Object)(object)item2 != (Object)null)
					{
						item2.enabled = false;
					}
				}
				Physics.SyncTransforms();
			}, Restore: delegate
			{
				hiddenRoots.Remove(source);
				(Renderer, bool)[] array = renderers;
				for (int i = 0; i < array.Length; i++)
				{
					var (val, forceRenderingOff) = array[i];
					if ((Object)(object)val != (Object)null)
					{
						val.forceRenderingOff = forceRenderingOff;
					}
				}
				(Collider, bool)[] array2 = colliders;
				for (int i = 0; i < array2.Length; i++)
				{
					var (val2, enabled) = array2[i];
					if ((Object)(object)val2 != (Object)null)
					{
						val2.enabled = enabled;
					}
				}
				Physics.SyncTransforms();
			});
		}

		private void TransformSelection(Action<GameObject> change)
		{
			//IL_0056: 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_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			GameObject target = RequireSelection();
			if (owned.Contains(((Object)target).GetInstanceID()))
			{
				Vector3 position = target.transform.localPosition;
				Quaternion rotation = target.transform.localRotation;
				History.Apply(delegate
				{
					change(target);
					Physics.SyncTransforms();
				}, delegate
				{
					//IL_0023: 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)
					if (Loaded(target))
					{
						target.transform.localPosition = position;
						target.transform.localRotation = rotation;
						Physics.SyncTransforms();
					}
				});
				return;
			}
			GameObject replacement = null;
			(Action Hide, Action Restore) visibility = Visibility(target);
			History.Apply(delegate
			{
				replacement = MakeCopy(target);
				visibility.Hide();
				change(replacement);
				Selected = replacement;
				Physics.SyncTransforms();
			}, delegate
			{
				visibility.Restore();
				Remove(replacement);
				Selected = (Loaded(target) ? target : null);
			});
		}

		public void Move(Vector3 position)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			TransformSelection(delegate(GameObject target)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				target.transform.position = position;
			});
		}

		public void Rotate(float degrees)
		{
			TransformSelection(delegate(GameObject target)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				target.transform.Rotate(Vector3.up, degrees, (Space)0);
			});
		}

		public void Delete()
		{
			GameObject target = RequireSelection();
			if (owned.Contains(((Object)target).GetInstanceID()))
			{
				History.Apply(delegate
				{
					target.SetActive(false);
				}, delegate
				{
					if (Loaded(target))
					{
						target.SetActive(true);
					}
				});
			}
			else
			{
				(Action, Action) tuple = Visibility(target);
				History.Apply(tuple.Item1, tuple.Item2);
			}
			Selected = null;
		}

		public void Reset()
		{
			try
			{
				History.Reset();
			}
			finally
			{
				Selected = null;
				owned.Clear();
				visuals.Clear();
				hiddenRoots.Clear();
			}
		}

		private GameObject RequireSelection()
		{
			string text = Rejection(Selected);
			if (text != null)
			{
				throw new InvalidOperationException(text);
			}
			return Selected;
		}

		private void Remove(GameObject? obj)
		{
			if (!((Object)(object)obj == (Object)null))
			{
				owned.Remove(((Object)obj).GetInstanceID());
				visuals.Remove(((Object)obj).GetInstanceID());
				if ((Object)(object)Selected == (Object)(object)obj)
				{
					Selected = null;
				}
				Object.DestroyImmediate((Object)(object)obj);
			}
		}
	}
	public sealed class SceneObjectEditorModule : IFeatureModule, IReloadableModule, IDisposable
	{
		private ModuleServices services;

		private Action<string> log;

		private readonly EditorInput input = new EditorInput();

		private readonly SceneEdits edits = new SceneEdits();

		private int scene;

		private string status = "Click an existing prop. Parent/Child adjusts the selected group.";

		private readonly List<GameObject> selectionChain = new List<GameObject>();

		private Action? pending;

		private float step = 0.25f;

		private GUIStyle? label;

		private GUIStyle? buttonStyle;

		private readonly Rect panelRect = new Rect(18f, 18f, 460f, 448f);

		public void Configure(ModuleServices services)
		{
			this.services = services;
		}

		public void Initialize(Action<string> log, string? state)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			this.log = log;
			Scene activeScene = SceneManager.GetActiveScene();
			scene = ((Scene)(ref activeScene)).handle;
			log("Scene Object Editor ready. F6 opens the editor; session edits reset on disable/reload/scene change.");
		}

		public string? CaptureState()
		{
			return null;
		}

		public void Update()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_036e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_0345: Unknown result type (might be due to invalid IL or missing references)
			//IL_0347: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Scene activeScene = SceneManager.GetActiveScene();
				int handle = ((Scene)(ref activeScene)).handle;
				if (scene != handle)
				{
					pending = null;
					input.Dispose();
					edits.Reset();
					scene = handle;
				}
				edits.Draw();
				if (input.Active && (services.InspectorOpen || input.Obscured()))
				{
					pending = null;
					input.Dispose();
				}
				Keyboard current = Keyboard.current;
				if (current != null && ((ButtonControl)current.f6Key).wasPressedThisFrame)
				{
					pending = null;
					if (input.Active)
					{
						input.Dispose();
					}
					else if (!services.InspectorOpen)
					{
						input.Open();
					}
				}
				else
				{
					if (!input.Active)
					{
						return;
					}
					if (pending != null)
					{
						Action? action = pending;
						pending = null;
						action();
					}
					if (!input.Active)
					{
						return;
					}
					if ((Object)(object)edits.Selected != (Object)null && !SceneEdits.Loaded(edits.Selected))
					{
						edits.Selected = null;
					}
					if (current != null && ((ButtonControl)current.escapeKey).wasPressedThisFrame)
					{
						input.Dispose();
						return;
					}
					if (current != null)
					{
						bool flag = ((ButtonControl)current.leftCtrlKey).isPressed || ((ButtonControl)current.rightCtrlKey).isPressed;
						if (((ButtonControl)current.rightBracketKey).wasPressedThisFrame)
						{
							CycleSelection(1);
						}
						if (((ButtonControl)current.leftBracketKey).wasPressedThisFrame)
						{
							CycleSelection(-1);
						}
						if (flag && ((ButtonControl)current.zKey).wasPressedThisFrame)
						{
							edits.History.Undo();
							status = "Undid the last edit.";
						}
						else if (flag && ((ButtonControl)current.dKey).wasPressedThisFrame)
						{
							edits.Copy();
							status = "Copied mesh; move or place it.";
						}
						else if (((ButtonControl)current.deleteKey).wasPressedThisFrame)
						{
							edits.Delete();
							status = "Hidden for this session. Ctrl+Z restores it.";
						}
						else if (((ButtonControl)current.pKey).wasPressedThisFrame)
						{
							PlaceAtPointer();
						}
						else if ((Object)(object)edits.Selected != (Object)null)
						{
							Vector3 zero = Vector3.zero;
							if (((ButtonControl)current.leftArrowKey).wasPressedThisFrame)
							{
								zero.x -= step;
							}
							if (((ButtonControl)current.rightArrowKey).wasPressedThisFrame)
							{
								zero.x += step;
							}
							if (((ButtonControl)current.upArrowKey).wasPressedThisFrame)
							{
								zero.z += step;
							}
							if (((ButtonControl)current.downArrowKey).wasPressedThisFrame)
							{
								zero.z -= step;
							}
							if (((ButtonControl)current.pageUpKey).wasPressedThisFrame)
							{
								zero.y += step;
							}
							if (((ButtonControl)current.pageDownKey).wasPressedThisFrame)
							{
								zero.y -= step;
							}
							if (((Vector3)(ref zero)).sqrMagnitude > 0f)
							{
								edits.Move(edits.Selected.transform.position + zero);
							}
						}
					}
					Mouse current2 = Mouse.current;
					if (current2 != null && current2.leftButton.wasPressedThisFrame && !OverPanel(((InputControl<Vector2>)(object)((Pointer)current2).position).ReadValue()))
					{
						SelectAtPointer();
					}
				}
			}
			catch (Exception ex)
			{
				status = ex.Message;
				log("Scene editor: " + ex);
				try
				{
					input.Dispose();
				}
				catch (Exception ex2)
				{
					log("Scene editor input cleanup: " + ex2);
				}
			}
		}

		private bool OverPanel(Vector2 screen)
		{
			//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)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			Rect val = panelRect;
			return ((Rect)(ref val)).Contains(new Vector2(screen.x, (float)Screen.height - screen.y));
		}

		private Ray PointerRay()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: 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_0039: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			Mouse current = Mouse.current;
			Vector2 val = (Vector2)((current == null) ? new Vector2((float)Screen.width / 2f, (float)Screen.height / 2f) : ((InputControl<Vector2>)(object)((Pointer)current).position).ReadValue());
			return Camera.main.ScreenPointToRay(new Vector3(val.x, val.y, 0f));
		}

		private void SelectAtPointer()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: 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_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_016f: Unknown result type (might be due to invalid IL or missing references)
			edits.Selected = null;
			selectionChain.Clear();
			Ray val = PointerRay();
			RaycastHit val2 = (from h in (IEnumerable<RaycastHit>)Physics.RaycastAll(val, 30f, -1, (QueryTriggerInteraction)1)
				where (Object)(object)((Component)((RaycastHit)(ref h)).collider).GetComponentInParent<PlayerCharacter>() == (Object)null
				orderby ((RaycastHit)(ref h)).distance
				select h).FirstOrDefault();
			if ((Object)(object)((RaycastHit)(ref val2)).collider != (Object)null)
			{
				GameObject val3 = edits.OwnedRoot(((Component)((RaycastHit)(ref val2)).collider).gameObject);
				if ((Object)(object)val3 != (Object)null)
				{
					edits.Selected = val3;
					status = "Selected " + ((Object)val3).name;
					return;
				}
				AddSelectionChain(((Component)((RaycastHit)(ref val2)).collider).gameObject);
			}
			if (selectionChain.Count == 0)
			{
				float num = (((Object)(object)((RaycastHit)(ref val2)).collider == (Object)null) ? 30f : (((RaycastHit)(ref val2)).distance + 0.5f));
				MeshRenderer val4 = null;
				float num2 = default(float);
				foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<MeshRenderer>()))
				{
					MeshRenderer val5 = ((Il2CppObjectBase)item).Cast<MeshRenderer>();
					if (SceneEdits.Loaded(((Component)val5).gameObject) && ((Component)val5).gameObject.activeInHierarchy && ((Renderer)val5).enabled && !((Renderer)val5).forceRenderingOff)
					{
						Bounds bounds = ((Renderer)val5).bounds;
						if (((Bounds)(ref bounds)).IntersectRay(val, ref num2) && num2 >= 0f && num2 < num)
						{
							num = num2;
							val4 = val5;
						}
					}
				}
				if ((Object)(object)val4 != (Object)null)
				{
					AddSelectionChain(((Component)val4).gameObject);
				}
			}
			if (selectionChain.Count == 0)
			{
				status = "No editable prop at pointer. Aim at a decorative mesh within 30 m.";
				return;
			}
			edits.Selected = ((IEnumerable<GameObject>)selectionChain).FirstOrDefault((Func<GameObject, bool>)((GameObject o) => (Object)(object)o.GetComponent<LODGroup>() != (Object)null)) ?? selectionChain[0];
			status = "Selected " + ((Object)edits.Selected).name + ". [ / ] selects Child / Parent.";
		}

		private void AddSelectionChain(GameObject target)
		{
			Transform val = target.transform;
			while ((Object)(object)val != (Object)null && !((Object)((Component)val).gameObject).name.StartsWith("_", StringComparison.Ordinal))
			{
				if (edits.Rejection(((Component)val).gameObject) == null)
				{
					selectionChain.Add(((Component)val).gameObject);
				}
				val = val.parent;
			}
		}

		private void CycleSelection(int direction)
		{
			int num = selectionChain.FindIndex((GameObject o) => (Object)(object)o == (Object)(object)edits.Selected);
			if (num < 0)
			{
				status = "Click a scene prop to choose its parent or child.";
				return;
			}
			int num2 = num + direction;
			if (num2 < 0 || num2 >= selectionChain.Count)
			{
				status = "No further editable group in that direction.";
				return;
			}
			GameObject val = selectionChain[num2];
			string text = edits.Rejection(val);
			if (text != null)
			{
				status = text;
				return;
			}
			edits.Selected = val;
			status = "Selected group: " + ((Object)val).name;
		}

		private Vector3 PlacementPoint(bool pointer)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//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_002c: 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)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: 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_00dd: 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_00f7: 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_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0180: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			Camera main = Camera.main;
			Ray val = (Ray)(pointer ? PointerRay() : new Ray(((Component)main).transform.position, ((Component)main).transform.forward));
			foreach (RaycastHit item in ((IEnumerable<RaycastHit>)Physics.RaycastAll(val, 30f, -1, (QueryTriggerInteraction)1)).OrderBy((RaycastHit hit) => ((RaycastHit)(ref hit)).distance))
			{
				RaycastHit current = item;
				if ((!((Object)(object)edits.Selected != (Object)null) || !((RaycastHit)(ref current)).transform.IsChildOf(edits.Selected.transform)) && !((Object)(object)((Component)((RaycastHit)(ref current)).collider).GetComponentInParent<PlayerCharacter>() != (Object)null))
				{
					Bounds selectionBounds;
					Vector3 val2;
					if (!((Object)(object)edits.Selected == (Object)null))
					{
						selectionBounds = edits.SelectionBounds;
						val2 = ((Bounds)(ref selectionBounds)).extents;
					}
					else
					{
						val2 = Vector3.one * 0.5f;
					}
					Vector3 val3 = val2;
					float num = Mathf.Abs(((RaycastHit)(ref current)).normal.x) * val3.x + Mathf.Abs(((RaycastHit)(ref current)).normal.y) * val3.y + Mathf.Abs(((RaycastHit)(ref current)).normal.z) * val3.z;
					Vector3 val4;
					if (!((Object)(object)edits.Selected == (Object)null))
					{
						selectionBounds = edits.SelectionBounds;
						val4 = ((Bounds)(ref selectionBounds)).center - edits.Selected.transform.position;
					}
					else
					{
						val4 = Vector3.zero;
					}
					Vector3 val5 = val4;
					return ((RaycastHit)(ref current)).point + ((RaycastHit)(ref current)).normal * (num + 0.01f) - val5;
				}
			}
			return ((Ray)(ref val)).GetPoint(3f);
		}

		private void PlaceAtPointer()
		{
			//IL_0032: 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)
			if (Mouse.current != null && OverPanel(((InputControl<Vector2>)(object)((Pointer)Mouse.current).position).ReadValue()))
			{
				status = "Point outside the editor panel, then press P.";
				return;
			}
			edits.Move(PlacementPoint(pointer: true));
			status = "Placed at pointed surface (3 m ahead if no surface).";
		}

		public void OnGUI()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_005f: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_035c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0385: Unknown result type (might be due to invalid IL or missing references)
			if (input.Active)
			{
				if (label == null)
				{
					label = new GUIStyle(GUI.skin.label)
					{
						fontSize = 16,
						wordWrap = true
					};
				}
				if (buttonStyle == null)
				{
					buttonStyle = new GUIStyle(GUI.skin.button)
					{
						fontSize = 15
					};
				}
				Color color = GUI.color;
				GUI.color = new Color(0.07f, 0.08f, 0.1f, 1f);
				GUI.DrawTexture(panelRect, (Texture)(object)Texture2D.whiteTexture);
				GUI.color = color;
				GUI.Box(panelRect, "");
				GUI.Label(new Rect(30f, 28f, 430f, 30f), "Scene Object Editor — F6 / Esc to close", label);
				GUI.Label(new Rect(30f, 60f, 430f, 45f), "Session only. Reload, disable, scene change or Reset restores all edits.", label);
				GUI.Label(new Rect(30f, 110f, 430f, 28f), ((Object)(object)edits.Selected == (Object)null) ? "No selection" : ("Selected: " + ((Object)edits.Selected).name), label);
				Button(30f, 147f, 135f, "Place cube", delegate
				{
					//IL_0015: Unknown result type (might be due to invalid IL or missing references)
					edits.Selected = null;
					edits.Create((PrimitiveType)3, PlacementPoint(pointer: false));
				});
				Button(173f, 147f, 135f, "Place sphere", delegate
				{
					//IL_0015: Unknown result type (might be due to invalid IL or missing references)
					edits.Selected = null;
					edits.Create((PrimitiveType)0, PlacementPoint(pointer: false));
				});
				Button(316f, 147f, 145f, "Undo (Ctrl+Z)", delegate
				{
					edits.History.Undo();
				});
				bool enabled = GUI.enabled;
				GUI.enabled = (Object)(object)edits.Selected != (Object)null;
				Button(30f, 188f, 135f, "Copy (Ctrl+D)", delegate
				{
					edits.Copy();
				});
				Button(173f, 188f, 135f, "Delete", delegate
				{
					edits.Delete();
				});
				Button(316f, 188f, 145f, "Rotate 15°", delegate
				{
					edits.Rotate(15f);
				});
				GUI.enabled = enabled;
				Button(30f, 229f, 135f, $"Step: {step:0.##} m", delegate
				{
					step = ((step == 0.25f) ? 1f : ((step == 1f) ? 0.05f : 0.25f));
				});
				Button(173f, 229f, 135f, "Reset session", delegate
				{
					edits.Reset();
					status = "All session edits restored.";
				});
				Button(316f, 229f, 145f, "Close editor", delegate
				{
					input.Dispose();
				});
				Button(30f, 270f, 135f, "Child [", delegate
				{
					CycleSelection(-1);
				});
				Button(173f, 270f, 135f, "Parent ]", delegate
				{
					CycleSelection(1);
				});
				GUI.Label(new Rect(30f, 310f, 430f, 56f), "Click: select prop   P: place at pointer\nArrows: world X/Z   Page Up/Down: height", label);
				GUI.Label(new Rect(30f, 370f, 430f, 72f), $"{edits.History.Count}/256 edits • {status}", label);
				DrawSelection();
			}
		}

		private void Button(float x, float y, float width, string text, Action action)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			if (GUI.Button(new Rect(x, y, width, 32f), text, buttonStyle))
			{
				pending = action;
			}
		}

		private void DrawSelection()
		{
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: 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_0050: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: 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_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			if (!SceneEdits.Loaded(edits.Selected) || !edits.Selected.activeInHierarchy || (Object)(object)Camera.main == (Object)null)
			{
				return;
			}
			Camera main = Camera.main;
			Bounds selectionBounds = edits.SelectionBounds;
			Vector3 val = main.WorldToScreenPoint(((Bounds)(ref selectionBounds)).center);
			if (val.z <= 0f)
			{
				return;
			}
			Color color = GUI.color;
			GUI.color = Color.yellow;
			GUI.Box(new Rect(val.x - 12f, (float)Screen.height - val.y - 12f, 24f, 24f), "+");
			Bounds selectionBounds2 = edits.SelectionBounds;
			float num = Screen.width;
			float num2 = Screen.height;
			float num3 = 0f;
			float num4 = 0f;
			bool flag = true;
			for (int i = -1; i <= 1; i += 2)
			{
				for (int j = -1; j <= 1; j += 2)
				{
					for (int k = -1; k <= 1; k += 2)
					{
						Vector3 val2 = Camera.main.WorldToScreenPoint(((Bounds)(ref selectionBounds2)).center + Vector3.Scale(((Bounds)(ref selectionBounds2)).extents, new Vector3((float)i, (float)j, (float)k)));
						if (val2.z <= 0f)
						{
							flag = false;
							continue;
						}
						num = Mathf.Min(num, val2.x);
						num3 = Mathf.Max(num3, val2.x);
						num2 = Mathf.Min(num2, (float)Screen.height - val2.y);
						num4 = Mathf.Max(num4, (float)Screen.height - val2.y);
					}
				}
			}
			if (flag)
			{
				GUI.DrawTexture(new Rect(num, num2, num3 - num, 2f), (Texture)(object)Texture2D.whiteTexture);
				GUI.DrawTexture(new Rect(num, num4, num3 - num, 2f), (Texture)(object)Texture2D.whiteTexture);
				GUI.DrawTexture(new Rect(num, num2, 2f, num4 - num2), (Texture)(object)Texture2D.whiteTexture);
				GUI.DrawTexture(new Rect(num3, num2, 2f, num4 - num2), (Texture)(object)Texture2D.whiteTexture);
			}
			GUI.color = color;
		}

		public void Dispose()
		{
			pending = null;
			try
			{
				input.Dispose();
			}
			finally
			{
				edits.Reset();
				label = null;
				buttonStyle = null;
			}
		}
	}
}

plugins/modules/NivalisModdingToolkit.Runtime.module

Decompiled an hour ago
using System;
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.Text.Json;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using Nivalis;
using Nivalis.Localization;
using Nivalis.UI.Concrete;
using Nivalis.UI.InGameMenu;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("NivalisModdingToolkit.Runtime")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("NivalisModdingToolkit.Runtime")]
[assembly: AssemblyTitle("NivalisModdingToolkit.Runtime")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	internal sealed record FeatureDescriptor(string Id, string Label, string FileName, Func<FeatureSettings, bool> IsOn, Func<FeatureSettings, bool, FeatureSettings> With);
	internal static class FeatureCatalog
	{
		public static readonly FeatureDescriptor[] All = new FeatureDescriptor[5]
		{
			new FeatureDescriptor("inspector", "NPC Inspector", "NpcInspector.Feature.module", (FeatureSettings s) => s.Inspector, (FeatureSettings s, bool on) => s with
			{
				Inspector = on
			}),
			new FeatureDescriptor("api", "Local API", "LocalApi.Feature.module", (FeatureSettings s) => s.Api, (FeatureSettings s, bool on) => s with
			{
				Api = on
			}),
			new FeatureDescriptor("editor", "Scene Object Editor (F6)", "SceneObjectEditor.Feature.module", (FeatureSettings s) => s.SceneEditor, (FeatureSettings s, bool on) => s with
			{
				SceneEditor = on
			}),
			new FeatureDescriptor("greeting", "Click-to-Hello", "ClickToHello.Feature.module", (FeatureSettings s) => s.Greeting, (FeatureSettings s, bool on) => s with
			{
				Greeting = on
			}),
			new FeatureDescriptor("noclip", "No-clip (F5)", "NoClip.Feature.module", (FeatureSettings s) => s.NoClip, (FeatureSettings s, bool on) => s with
			{
				NoClip = on
			})
		};

		public static FeatureDescriptor[] Installed(Func<string, bool> moduleExists)
		{
			return All.Where((FeatureDescriptor feature) => moduleExists(feature.FileName)).ToArray();
		}
	}
	public sealed record FeatureSettings(bool Inspector = true, bool Api = true, bool Greeting = true, bool SceneEditor = false, bool NoClip = false)
	{
		public const string FileName = "modules.json";

		public static FeatureSettings Load(string path, Action<string> log)
		{
			if (!File.Exists(path))
			{
				return new FeatureSettings();
			}
			try
			{
				return JsonSerializer.Deserialize<FeatureSettings>(File.ReadAllText(path)) ?? new FeatureSettings();
			}
			catch (Exception ex)
			{
				log("Could not read module settings; using defaults: " + ex.Message);
				return new FeatureSettings();
			}
		}

		public void Save(string path)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(this, new JsonSerializerOptions
			{
				WriteIndented = true
			}));
			File.Move(path + ".tmp", path, overwrite: true);
		}

		[CompilerGenerated]
		private FeatureSettings(FeatureSettings original)
		{
			Inspector = original.Inspector;
			Api = original.Api;
			Greeting = original.Greeting;
			SceneEditor = original.SceneEditor;
			NoClip = original.NoClip;
		}
	}
	internal sealed class FeatureSlot : IDisposable
	{
		private readonly ReloadController loader;

		private readonly string path;

		private readonly Action<string> log;

		private float nextCheck;

		private string? lastReadError;

		public string FileName { get; }

		public string? BuildId => loader.BuildId;

		public IModuleSettings? Settings => loader.Settings;

		public FeatureSlot(string fileName, ModuleServices services, Action<string> log)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			FileName = fileName;
			path = Path.Combine(ToolkitPaths.Modules, fileName);
			this.log = delegate(string message)
			{
				log("[" + fileName + "] " + message);
			};
			loader = new ReloadController(this.log, (Action<IReloadableModule>)delegate(IReloadableModule module)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				((IFeatureModule)module).Configure(services);
			});
		}

		public void Tick(bool enabled)
		{
			if (enabled)
			{
				PollFile();
				loader.Update();
			}
		}

		private void PollFile()
		{
			Keyboard current = Keyboard.current;
			bool flag = current != null && ((ButtonControl)current.f7Key).wasPressedThisFrame;
			if (!flag && Time.realtimeSinceStartup < nextCheck)
			{
				return;
			}
			nextCheck = Time.realtimeSinceStartup + 1f;
			try
			{
				loader.Reload(File.ReadAllBytes(path), flag);
				lastReadError = null;
			}
			catch (Exception ex)
			{
				if (lastReadError != ex.Message)
				{
					log("Cannot read feature; retaining current module: " + ex.Message);
				}
				lastReadError = ex.Message;
			}
		}

		public void OnGUI()
		{
			loader.OnGUI();
		}

		public void Disable()
		{
			loader.Dispose();
			nextCheck = 0f;
		}

		public void Dispose()
		{
			Disable();
		}
	}
	internal static class ModuleCleanup
	{
		public static void Dispose(params IDisposable?[] resources)
		{
			List<Exception> list = null;
			foreach (IDisposable disposable in resources)
			{
				try
				{
					disposable?.Dispose();
				}
				catch (Exception item)
				{
					(list ?? (list = new List<Exception>())).Add(item);
				}
			}
			if (list != null)
			{
				throw new AggregateException("Module cleanup failed.", list);
			}
		}
	}
	internal sealed class ModulesMenu : IDisposable
	{
		private readonly List<(Button Button, string Id)> settingsButtons = new List<(Button, string)>();

		private readonly List<Button> popupButtons = new List<Button>();

		private readonly List<(Selectable Control, bool Enabled)> blockedControls = new List<(Selectable, bool)>();

		private GameObject? popup;

		private GameObject? previousSelection;

		private IModuleSettings? popupProvider;

		private string? popupModule;

		private readonly FeatureDescriptor[] features;

		private readonly Func<FeatureSettings> read;

		private readonly Action<FeatureSettings> apply;

		private readonly Action<string> log;

		private readonly Func<string, IModuleSettings?> settingsFor;

		private FeatureSettings draft = new FeatureSettings();

		private WindowToggleController? controller;

		private Il2CppReferenceArray<Toggle>? originalToggles;

		private Il2CppReferenceArray<UISubPanel>? originalPanels;

		private int originalEventCount;

		private GameObject? staging;

		private GameObject? tabObject;

		private GameObject? panelObject;

		private UISubPanel? panel;

		private TMP_Text settingsText;

		private readonly List<Toggle> toggles = new List<Toggle>();

		private readonly List<Button> buttons = new List<Button>();

		private readonly Dictionary<string, Toggle> featureToggles = new Dictionary<string, Toggle>();

		private Button? applyButton;

		private Button? resetButton;

		private float nextAttempt;

		private bool failed;

		private Toggle FeatureRow(GameObject template, Button buttonTemplate, Transform parent, string id, string label, Action<bool> changed)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: 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)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_0156: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(label + " row", (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			val.transform.SetParent(parent, false);
			val.AddComponent<LayoutElement>().preferredHeight = 70f;
			Toggle obj = Row(template, val.transform, label, changed);
			RectTransform obj2 = ((Il2CppObjectBase)((Component)obj).transform).Cast<RectTransform>();
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(0f, 0.5f);
			obj2.anchorMax = val2;
			obj2.anchorMin = val2;
			obj2.pivot = new Vector2(0f, 0.5f);
			obj2.anchoredPosition = Vector2.zero;
			obj2.sizeDelta = new Vector2(700f, 70f);
			GameObject val3 = Object.Instantiate<GameObject>(((Component)buttonTemplate).gameObject, staging.transform);
			((Object)val3).name = label + " Settings";
			Button val4 = CreateButton(val3.GetComponent<Button>(), "Settings", delegate
			{
				OpenSettingsPopup(id, label, buttonTemplate);
			});
			val3.transform.SetParent(val.transform, false);
			Place(val3, new Vector2(395f, 0f), new Vector2(180f, 48f));
			val3.SetActive(true);
			((Selectable)val4).interactable = settingsFor(id) != null;
			settingsButtons.Add((val4, id));
			return obj;
		}

		private void UpdateSettingsPopup()
		{
			if (popupModule != null && !PopupIsStale())
			{
				return;
			}
			if (popupModule != null)
			{
				CloseSettingsPopup();
			}
			foreach (var (val, arg) in settingsButtons)
			{
				if ((Object)(object)val != (Object)null)
				{
					((Selectable)val).interactable = settingsFor(arg) != null;
				}
			}
		}

		private bool PopupIsStale()
		{
			if (!((Object)(object)popup == (Object)null) && !((Object)(object)controller == (Object)null) && controller.parentPanel.IsVisible && !((Object)(object)panel == (Object)null) && panel.IsVisible)
			{
				return popupProvider != settingsFor(popupModule);
			}
			return true;
		}

		private void OpenSettingsPopup(string id, string title, Button template)
		{
			CloseSettingsPopup();
			IModuleSettings val = settingsFor(id);
			if (val == null)
			{
				return;
			}
			try
			{
				IReadOnlyList<NumberSetting> readOnlyList = val.ReadSettings();
				Dictionary<string, float> values = readOnlyList.ToDictionary((NumberSetting setting) => setting.Id, (NumberSetting setting) => setting.Value);
				popupProvider = val;
				popupModule = id;
				BlockBackgroundControls();
				(GameObject Frame, float Height) tuple = CreatePopupFrame(title, readOnlyList.Count);
				GameObject item = tuple.Frame;
				float item2 = tuple.Height;
				for (int num = 0; num < readOnlyList.Count; num++)
				{
					AddSettingRow(item, template, readOnlyList[num], values, item2 / 2f - 120f - (float)(num * 75));
				}
				AddPopupActions(item, template, val, id, title, values, item2);
			}
			catch (Exception value)
			{
				CloseSettingsPopup();
				log($"Could not open {title} settings: {value}");
			}
		}

		private void BlockBackgroundControls()
		{
			EventSystem current = EventSystem.current;
			previousSelection = ((current != null) ? current.currentSelectedGameObject : null);
			foreach (Selectable componentsInChild in ((Component)controller.parentPanel).GetComponentsInChildren<Selectable>(true))
			{
				blockedControls.Add((componentsInChild, componentsInChild.interactable));
				componentsInChild.interactable = false;
			}
		}

		private (GameObject Frame, float Height) CreatePopupFrame(string title, int rows)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			//IL_0050: 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_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_0154: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Expected O, but got Unknown
			popup = new GameObject("Module settings popup", (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			popup.transform.SetParent(((Component)controller.parentPanel).transform, false);
			RectTransform obj = ((Il2CppObjectBase)popup.transform).Cast<RectTransform>();
			obj.anchorMin = Vector2.zero;
			obj.anchorMax = Vector2.one;
			Vector2 offsetMin = (obj.offsetMax = Vector2.zero);
			obj.offsetMin = offsetMin;
			((Graphic)popup.AddComponent<Image>()).color = new Color(0f, 0f, 0f, 0.85f);
			GameObject val = new GameObject(title + " settings", (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			val.transform.SetParent(popup.transform, false);
			float num = 240 + rows * 75;
			Place(val, Vector2.zero, new Vector2(820f, num));
			((Graphic)val.AddComponent<Image>()).color = new Color(0.12f, 0.11f, 0.1f, 1f);
			Label(val.transform, settingsText, title + " Settings", new Vector2(0f, num / 2f - 45f), new Vector2(740f, 50f));
			return (Frame: val, Height: num);
		}

		private void AddSettingRow(GameObject frame, Button template, NumberSetting setting, Dictionary<string, float> values, float y)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: 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)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011f: Unknown result type (might be due to invalid IL or missing references)
			Label(frame.transform, settingsText, setting.Label, new Vector2(-190f, y), new Vector2(340f, 50f));
			TMP_Text valueText = Label(frame.transform, settingsText, "", new Vector2(160f, y), new Vector2(160f, 50f));
			Button decrease = null;
			Button increase = null;
			decrease = PopupButton(template, frame.transform, setting.Label + " decrease", "−", new Vector2(40f, y), new Vector2(60f, 48f), delegate
			{
				values[setting.Id] = Math.Max(setting.Minimum, values[setting.Id] - setting.Step);
				Refresh();
			});
			increase = PopupButton(template, frame.transform, setting.Label + " increase", "+", new Vector2(280f, y), new Vector2(60f, 48f), delegate
			{
				values[setting.Id] = Math.Min(setting.Maximum, values[setting.Id] + setting.Step);
				Refresh();
			});
			Refresh();
			void Refresh()
			{
				valueText.text = $"{values[setting.Id]:0.#} {setting.Unit}";
				((Selectable)decrease).interactable = values[setting.Id] > setting.Minimum;
				((Selectable)increase).interactable = values[setting.Id] < setting.Maximum;
			}
		}

		private void AddPopupActions(GameObject frame, Button template, IModuleSettings provider, string id, string title, Dictionary<string, float> values, float height)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			TMP_Text status = Label(frame.transform, settingsText, "", new Vector2(0f, (0f - height) / 2f + 100f), new Vector2(740f, 48f));
			status.fontSize = 18f;
			PopupButton(template, frame.transform, "Module settings Apply", "Apply", new Vector2(130f, (0f - height) / 2f + 45f), new Vector2(210f, 48f), delegate
			{
				if (provider != settingsFor(id))
				{
					CloseSettingsPopup();
					return;
				}
				try
				{
					provider.ApplySettings((IReadOnlyDictionary<string, float>)values);
					CloseSettingsPopup();
				}
				catch (Exception value)
				{
					status.text = "Could not save settings. See log.";
					log($"{title} settings were not applied: {value}");
				}
			});
			Button val = PopupButton(template, frame.transform, "Module settings Cancel", "Cancel", new Vector2(-130f, (0f - height) / 2f + 45f), new Vector2(210f, 48f), CloseSettingsPopup);
			EventSystem current = EventSystem.current;
			if (current != null)
			{
				current.SetSelectedGameObject(((Component)val).gameObject);
			}
		}

		private Button PopupButton(Button template, Transform parent, string name, string text, Vector2 position, Vector2 size, Action action)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(((Component)template).gameObject, parent);
			((Object)val).name = name;
			Button val2 = CreateButton(val.GetComponent<Button>(), text, action);
			((Selectable)val2).interactable = true;
			Place(val, position, size);
			val.SetActive(true);
			popupButtons.Add(val2);
			return val2;
		}

		private static TMP_Text Label(Transform parent, TMP_Text template, string text, Vector2 position, Vector2 size)
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject((text.Length == 0) ? "Setting value" : text, (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			val.transform.SetParent(parent, false);
			Place(val, position, size);
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).font = template.font;
			((TMP_Text)obj).fontSize = 26f;
			((Graphic)obj).color = ((Graphic)template).color;
			((TMP_Text)obj).alignment = (TextAlignmentOptions)514;
			((Graphic)obj).raycastTarget = false;
			((TMP_Text)obj).text = text;
			return (TMP_Text)(object)obj;
		}

		private static void Place(GameObject obj, Vector2 position, Vector2 size)
		{
			//IL_001f: 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_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			RectTransform obj2 = ((Il2CppObjectBase)obj.transform).Cast<RectTransform>();
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(0.5f, 0.5f);
			obj2.pivot = val;
			Vector2 anchorMin = (obj2.anchorMax = val);
			obj2.anchorMin = anchorMin;
			obj2.anchoredPosition = position;
			obj2.sizeDelta = size;
			((Transform)obj2).localScale = Vector3.one;
		}

		private void CloseSettingsPopup()
		{
			foreach (Button popupButton in popupButtons)
			{
				if (!((Object)(object)popupButton == (Object)null))
				{
					((UnityEventBase)popupButton.onClick).RemoveAllListeners();
					buttons.Remove(popupButton);
				}
			}
			popupButtons.Clear();
			if ((Object)(object)popup != (Object)null)
			{
				popup.SetActive(false);
				Object.Destroy((Object)(object)popup);
			}
			popup = null;
			popupProvider = null;
			popupModule = null;
			foreach (var (val, interactable) in blockedControls)
			{
				if ((Object)(object)val != (Object)null)
				{
					val.interactable = interactable;
				}
			}
			blockedControls.Clear();
			if ((Object)(object)previousSelection != (Object)null && (Object)(object)EventSystem.current != (Object)null)
			{
				EventSystem.current.SetSelectedGameObject(previousSelection);
			}
			previousSelection = null;
		}

		public ModulesMenu(FeatureDescriptor[] features, Func<FeatureSettings> read, Action<FeatureSettings> apply, Action<string> log, Func<string, IModuleSettings?> settingsFor)
		{
			this.features = features;
			this.read = read;
			this.apply = apply;
			this.log = log;
			this.settingsFor = settingsFor;
		}

		public void Update()
		{
			//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)
			UpdateSettingsPopup();
			if (failed || (Object)(object)controller != (Object)null || Time.unscaledTime < nextAttempt)
			{
				return;
			}
			nextAttempt = Time.unscaledTime + 1f;
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<SettingsPanel>()))
			{
				SettingsPanel val = ((Il2CppObjectBase)item).Cast<SettingsPanel>();
				Scene scene = ((Component)val).gameObject.scene;
				if (((Scene)(ref scene)).IsValid())
				{
					try
					{
						Install(val);
						break;
					}
					catch (Exception value)
					{
						log($"Modules tab installation failed: {value}");
						Dispose();
						failed = true;
						break;
					}
				}
			}
		}

		private void Install(SettingsPanel settings)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Expected O, but got Unknown
			//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c1: Expected O, but got Unknown
			controller = settings.togglesGroup;
			originalToggles = controller.toggles;
			originalPanels = controller.panels;
			originalEventCount = controller.events.Count;
			GameplaySettingsUI val = ((Il2CppObjectBase)((Il2CppArrayBase<UISubPanel>)(object)originalPanels)[0]).Cast<GameplaySettingsUI>();
			settingsText = ((Component)val.invertYAxis).GetComponentInChildren<TMP_Text>(true);
			draft = read();
			staging = new GameObject("Modules staging");
			staging.SetActive(false);
			staging.transform.SetParent(((Component)settings).transform, false);
			tabObject = Object.Instantiate<GameObject>(((Component)((Il2CppArrayBase<Toggle>)(object)originalToggles)[0]).gameObject, staging.transform);
			((Object)tabObject).name = "ModulesToggle";
			SetLabels(tabObject, "Modules");
			Toggle component = tabObject.GetComponent<Toggle>();
			component.onValueChanged = new ToggleEvent();
			component.SetIsOnWithoutNotify(false);
			toggles.Add(component);
			CreatePanel(val);
			RectTransform val2 = CreateFeatureRows(val);
			CreateButtons(val);
			int index = ((Il2CppArrayBase<Toggle>)(object)originalToggles).Length;
			controller.toggles = new Il2CppReferenceArray<Toggle>(((IEnumerable<Toggle>)originalToggles).Concat((IEnumerable<Toggle>)(object)new Toggle[1] { component }).ToArray());
			controller.panels = new Il2CppReferenceArray<UISubPanel>(((IEnumerable<UISubPanel>)originalPanels).Concat((IEnumerable<UISubPanel>)(object)new UISubPanel[1] { panel }).ToArray());
			while (controller.events.Count <= index)
			{
				controller.events.Add(new UnityEvent());
			}
			((UnityEvent<bool>)(object)component.onValueChanged).AddListener(DelegateSupport.ConvertDelegate<UnityAction<bool>>((Delegate)(Action<bool>)delegate(bool on)
			{
				if (on)
				{
					draft = read();
					RefreshValues();
				}
				controller.ToggleValueChanged(on, index);
			}));
			tabObject.transform.SetParent(((Component)((Il2CppArrayBase<Toggle>)(object)originalToggles)[0]).transform.parent, false);
			Transform transform = tabObject.transform;
			Il2CppReferenceArray<Toggle>? obj = originalToggles;
			transform.SetSiblingIndex(((Component)((Il2CppArrayBase<Toggle>)(object)obj)[((Il2CppArrayBase<Toggle>)(object)obj).Length - 1]).transform.GetSiblingIndex() + 1);
			tabObject.SetActive(true);
			panelObject.SetActive(true);
			panel.SetInvisibleImmediate();
			RefreshValues();
			LayoutRebuilder.ForceRebuildLayoutImmediate(val2);
			Object.Destroy((Object)(object)staging);
			staging = null;
			log("Modules settings tab installed: " + string.Join(", ", features.Select((FeatureDescriptor feature) => feature.Label)) + ".");
		}

		private void CreatePanel(GameplaySettingsUI gameplay)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			panelObject = new GameObject("ModulesSettings", (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			panelObject.SetActive(false);
			panelObject.transform.SetParent(((Component)gameplay).transform.parent, false);
			CopyRect(((Il2CppObjectBase)((Component)gameplay).transform).Cast<RectTransform>(), ((Il2CppObjectBase)panelObject.transform).Cast<RectTransform>());
			CanvasGroup canvasGroup = panelObject.AddComponent<CanvasGroup>();
			panel = panelObject.AddComponent<UISubPanel>();
			panel.parentWindow = ((UISubPanel)gameplay).parentWindow;
			panel.fadeInTimeOverride = ((UISubPanel)gameplay).fadeInTimeOverride;
			panel.fadeOutTimeOverride = ((UISubPanel)gameplay).fadeOutTimeOverride;
			panel.ease = ((UISubPanel)gameplay).ease;
			panel._canvasGroup = canvasGroup;
			panel.startVisible = false;
		}

		private RectTransform CreateFeatureRows(GameplaySettingsUI gameplay)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Module toggles", (Type[])(object)new Type[1] { Il2CppType.Of<RectTransform>() });
			val.transform.SetParent(panelObject.transform, false);
			RectTransform val2 = ((Il2CppObjectBase)val.transform).Cast<RectTransform>();
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(0.5f, 1f);
			val2.anchorMax = val3;
			val2.anchorMin = val3;
			val2.pivot = new Vector2(0.5f, 1f);
			val2.anchoredPosition = new Vector2(0f, -45f);
			val2.sizeDelta = new Vector2(1000f, 400f);
			VerticalLayoutGroup obj = val.AddComponent<VerticalLayoutGroup>();
			((HorizontalOrVerticalLayoutGroup)obj).spacing = 30f;
			((HorizontalOrVerticalLayoutGroup)obj).childControlWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childControlHeight = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandWidth = true;
			((HorizontalOrVerticalLayoutGroup)obj).childForceExpandHeight = false;
			GameObject gameObject = ((Component)gameplay.invertYAxis).gameObject;
			FeatureDescriptor[] array = features;
			foreach (FeatureDescriptor feature in array)
			{
				featureToggles[feature.Id] = FeatureRow(gameObject, ((SettingsTabPanel)gameplay).applyButton, val.transform, feature.Id, feature.Label, delegate(bool value)
				{
					draft = feature.With(draft, value);
				});
			}
			if (featureToggles.Count > 0)
			{
				panel.firstSelected = ((Component)featureToggles[features[0].Id]).gameObject;
			}
			return val2;
		}

		private void CreateButtons(GameplaySettingsUI gameplay)
		{
			//IL_005d: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			GameObject obj = Object.Instantiate<GameObject>(((Component)((Component)((SettingsTabPanel)gameplay).applyButton).transform.parent).gameObject, staging.transform);
			((Object)obj).name = "Module buttons";
			obj.transform.SetParent(panelObject.transform, false);
			RectTransform obj2 = ((Il2CppObjectBase)obj.transform).Cast<RectTransform>();
			obj2.anchorMin = new Vector2(0f, 0f);
			obj2.anchorMax = new Vector2(1f, 0f);
			obj2.pivot = new Vector2(0.5f, 0f);
			obj2.anchoredPosition = Vector2.zero;
			obj2.sizeDelta = new Vector2(0f, 40f);
			foreach (Button componentsInChild in obj.GetComponentsInChildren<Button>(true))
			{
				if (((Object)componentsInChild).name == ((Object)((SettingsTabPanel)gameplay).applyButton).name)
				{
					applyButton = CreateButton(componentsInChild, "Apply", ApplyDraft);
					continue;
				}
				if (((Object)componentsInChild).name == ((Object)((SettingsTabPanel)gameplay).resetButton).name)
				{
					resetButton = CreateButton(componentsInChild, "Reset", delegate
					{
						draft = read();
						RefreshValues();
					});
					continue;
				}
				if (((Object)componentsInChild).name == ((Object)((SettingsTabPanel)gameplay).restoreDefaultsButton).name)
				{
					CreateButton(componentsInChild, "Restore Default", delegate
					{
						draft = new FeatureSettings();
						RefreshValues();
					});
					continue;
				}
				throw new InvalidOperationException("Unexpected settings button: " + ((Object)componentsInChild).name);
			}
			if ((Object)(object)applyButton == (Object)null || (Object)(object)resetButton == (Object)null)
			{
				throw new InvalidOperationException("Settings button template changed.");
			}
		}

		private Button CreateButton(Button template, string label, Action action)
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: 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)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Unknown result type (might be due to invalid IL or missing references)
			//IL_0201: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)template).gameObject;
			foreach (MonoBehaviour component2 in gameObject.GetComponents<MonoBehaviour>())
			{
				bool flag = (Object)(object)((Il2CppObjectBase)component2).TryCast<Button>() != (Object)null;
				if (!flag)
				{
					bool flag2;
					switch (((MemberInfo)((Object)component2).GetIl2CppType()).Name)
					{
					case "UI_ButtonFocus":
					case "UI_ButtonHoverResize":
					case "ManualUINavigation":
					case "UIInteractionSounds":
						flag2 = true;
						break;
					default:
						flag2 = false;
						break;
					}
					flag = flag2;
				}
				if (flag)
				{
					Object.DestroyImmediate((Object)(object)component2);
				}
			}
			foreach (Image componentsInChild in gameObject.GetComponentsInChildren<Image>(true))
			{
				if ((Object)(object)((Component)componentsInChild).gameObject != (Object)(object)gameObject)
				{
					((Component)componentsInChild).gameObject.SetActive(false);
				}
			}
			Button val = gameObject.AddComponent<Button>();
			Image component = gameObject.GetComponent<Image>();
			((Graphic)component).color = new Color(0.25f, 0.23f, 0.2f, 1f);
			((Selectable)val).targetGraphic = (Graphic)(object)component;
			ColorBlock colors = ((Selectable)val).colors;
			((ColorBlock)(ref colors)).normalColor = Color.white;
			((ColorBlock)(ref colors)).highlightedColor = new Color(1.5f, 1.3f, 1f, 1f);
			((ColorBlock)(ref colors)).disabledColor = new Color(0.6f, 0.6f, 0.6f, 1f);
			((Selectable)val).colors = colors;
			SetLabels(gameObject, label);
			foreach (TMP_Text componentsInChild2 in gameObject.GetComponentsInChildren<TMP_Text>(true))
			{
				((Component)componentsInChild2).gameObject.SetActive(false);
			}
			RectTransform rectTransform = Label(gameObject.transform, settingsText, label, Vector2.zero, Vector2.zero).rectTransform;
			rectTransform.anchorMin = Vector2.zero;
			rectTransform.anchorMax = Vector2.one;
			Vector2 offsetMin = (rectTransform.offsetMax = Vector2.zero);
			rectTransform.offsetMin = offsetMin;
			buttons.Add(val);
			Bind(val, action);
			return val;
		}

		private void ApplyDraft()
		{
			try
			{
				apply(draft);
				RefreshValues();
			}
			catch (Exception value)
			{
				log($"Module settings were not applied: {value}");
			}
		}

		private Toggle Row(GameObject template, Transform parent, string label, Action<bool> changed)
		{
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Object.Instantiate<GameObject>(template, staging.transform);
			((Object)val).name = label;
			foreach (MonoBehaviour component2 in val.GetComponents<MonoBehaviour>())
			{
				bool flag;
				switch (((MemberInfo)((Object)component2).GetIl2CppType()).Name)
				{
				case "ToggleSettingUI":
				case "ManualUINavigation":
				case "GamepadAutoScroll":
				case "BetterContentSizeFitter":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (flag)
				{
					Object.DestroyImmediate((Object)(object)component2);
				}
			}
			SetLabels(val, label);
			Toggle component = val.GetComponent<Toggle>();
			foreach (CanvasGroup componentsInChild in val.GetComponentsInChildren<CanvasGroup>(true))
			{
				componentsInChild.interactable = true;
				componentsInChild.blocksRaycasts = true;
				componentsInChild.alpha = 1f;
			}
			((Selectable)component).interactable = true;
			((Behaviour)component).enabled = true;
			component.group = null;
			component.onValueChanged = new ToggleEvent();
			Navigation navigation = ((Selectable)component).navigation;
			navigation.mode = (Mode)3;
			((Selectable)component).navigation = navigation;
			((UnityEvent<bool>)(object)component.onValueChanged).AddListener(DelegateSupport.ConvertDelegate<UnityAction<bool>>((Delegate)(Action<bool>)delegate(bool value)
			{
				changed(value);
				RefreshButtons();
			}));
			toggles.Add(component);
			val.transform.SetParent(parent, false);
			val.transform.localScale = Vector3.one;
			val.SetActive(true);
			return component;
		}

		private static void SetLabels(GameObject root, string label)
		{
			foreach (LocalizedStaticUILabel componentsInChild in root.GetComponentsInChildren<LocalizedStaticUILabel>(true))
			{
				Object.DestroyImmediate((Object)(object)componentsInChild);
			}
			foreach (TMP_Text componentsInChild2 in root.GetComponentsInChildren<TMP_Text>(true))
			{
				componentsInChild2.text = label;
			}
		}

		private static void Bind(Button button, Action action)
		{
			((UnityEvent)button.onClick).AddListener(DelegateSupport.ConvertDelegate<UnityAction>((Delegate)action));
		}

		private void RefreshValues()
		{
			FeatureDescriptor[] array = features;
			foreach (FeatureDescriptor featureDescriptor in array)
			{
				featureToggles[featureDescriptor.Id].SetIsOnWithoutNotify(featureDescriptor.IsOn(draft));
			}
			RefreshButtons();
		}

		private void RefreshButtons()
		{
			bool interactable = draft != read();
			if ((Object)(object)applyButton != (Object)null)
			{
				((Selectable)applyButton).interactable = interactable;
			}
			if ((Object)(object)resetButton != (Object)null)
			{
				((Selectable)resetButton).interactable = interactable;
			}
		}

		private static void CopyRect(RectTransform from, RectTransform to)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			to.anchorMin = from.anchorMin;
			to.anchorMax = from.anchorMax;
			to.pivot = from.pivot;
			to.sizeDelta = from.sizeDelta;
			to.anchoredPosition = from.anchoredPosition;
		}

		public void Dispose()
		{
			CloseSettingsPopup();
			settingsButtons.Clear();
			RestoreController();
			foreach (Toggle toggle in toggles)
			{
				if ((Object)(object)toggle != (Object)null)
				{
					((UnityEventBase)toggle.onValueChanged).RemoveAllListeners();
				}
			}
			foreach (Button button in buttons)
			{
				if ((Object)(object)button != (Object)null)
				{
					((UnityEventBase)button.onClick).RemoveAllListeners();
				}
			}
			toggles.Clear();
			buttons.Clear();
			featureToggles.Clear();
			if ((Object)(object)tabObject != (Object)null)
			{
				tabObject.SetActive(false);
				Object.Destroy((Object)(object)tabObject);
			}
			if ((Object)(object)panelObject != (Object)null)
			{
				panelObject.SetActive(false);
				Object.Destroy((Object)(object)panelObject);
			}
			if ((Object)(object)staging != (Object)null)
			{
				Object.Destroy((Object)(object)staging);
			}
			tabObject = null;
			panelObject = null;
			staging = null;
			controller = null;
		}

		private void RestoreController()
		{
			if (!((Object)(object)controller == (Object)null) && originalToggles != null && originalPanels != null)
			{
				if (controller.CurrentIndex >= ((Il2CppArrayBase<Toggle>)(object)originalToggles).Length)
				{
					controller.SwitchToPanel(0);
				}
				controller.toggles = originalToggles;
				controller.panels = originalPanels;
				while (controller.events.Count > originalEventCount)
				{
					controller.events.RemoveAt(controller.events.Count - 1);
				}
			}
		}
	}
	public sealed class ToolkitCoordinator : IReloadableModule, IDisposable
	{
		private FeatureSettings features = new FeatureSettings();

		private ModulesMenu? menu;

		private readonly List<(FeatureDescriptor Feature, FeatureSlot Slot)> installed = new List<(FeatureDescriptor, FeatureSlot)>();

		private readonly ModuleServices services = new ModuleServices();

		private Action<string> log;

		private static string SettingsPath => ToolkitPaths.Config("modules.json");

		public void Initialize(Action<string> log, string? state)
		{
			this.log = log;
			features = FeatureSettings.Load(SettingsPath, log);
			FeatureDescriptor[] array = FeatureCatalog.Installed((string file) => File.Exists(Path.Combine(ToolkitPaths.Modules, file)));
			foreach (FeatureDescriptor featureDescriptor in array)
			{
				installed.Add((featureDescriptor, new FeatureSlot(featureDescriptor.FileName, services, log)));
			}
			string version = typeof(ToolkitCoordinator).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "dev";
			services.HealthJson = delegate
			{
				//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)
				string version2 = version;
				string buildId = typeof(ToolkitCoordinator).Module.ModuleVersionId.ToString();
				Scene activeScene = SceneManager.GetActiveScene();
				return JsonSerializer.Serialize(new
				{
					Status = "ok",
					ApiVersion = 1,
					Version = version2,
					BuildId = buildId,
					ActiveScene = ((Scene)(ref activeScene)).name,
					InspectorOpen = services.InspectorOpen,
					Modules = installed.ToDictionary<(FeatureDescriptor, FeatureSlot), string, bool>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature.Id, ((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature.IsOn(features)),
					ModuleBuilds = installed.ToDictionary<(FeatureDescriptor, FeatureSlot), string, string>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature.Id, ((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Slot.BuildId),
					Capabilities = new string[9] { "npcs", "quests", "dialogue", "dialogue-current", "items", "recipes", "screenshot", "ui", "ui-actions" }
				});
			};
			menu = new ModulesMenu(installed.Select<(FeatureDescriptor, FeatureSlot), FeatureDescriptor>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature).ToArray(), () => features, ApplyFeatures, log, (string id) => installed.FirstOrDefault<(FeatureDescriptor, FeatureSlot)>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature.Id == id).Item2?.Settings);
			log($"Toolkit runtime {version}: installed features {string.Join(", ", installed.Select<(FeatureDescriptor, FeatureSlot), string>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => entry.Feature.Id))}.");
		}

		public string? CaptureState()
		{
			return null;
		}

		private void ApplyFeatures(FeatureSettings updated)
		{
			updated.Save(SettingsPath);
			features = updated;
			foreach (var (featureDescriptor, featureSlot) in installed)
			{
				if (!featureDescriptor.IsOn(features))
				{
					featureSlot.Disable();
				}
			}
			log("Modules applied: " + string.Join(", ", installed.Select<(FeatureDescriptor, FeatureSlot), string>(((FeatureDescriptor Feature, FeatureSlot Slot) entry) => $"{entry.Feature.Id}={entry.Feature.IsOn(features)}")) + ".");
		}

		public void Update()
		{
			menu?.Update();
			foreach (var item in installed)
			{
				var (featureDescriptor, _) = item;
				item.Slot.Tick(featureDescriptor.IsOn(features));
			}
		}

		public void OnGUI()
		{
			foreach (var item in installed)
			{
				item.Slot.OnGUI();
			}
		}

		public void Dispose()
		{
			ModuleCleanup.Dispose((from entry in installed
				select entry.Slot into slot
				orderby (!slot.FileName.StartsWith("SceneObjectEditor")) ? 1 : 0
				select slot).Cast<IDisposable>().Append(menu).ToArray());
			installed.Clear();
			menu = null;
			services.HealthJson = () => "{}";
		}
	}
}

plugins/modules/LocalApi.Feature.module

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using Microsoft.CodeAnalysis;
using Nivalis;
using Nivalis.CraftingSystem;
using Nivalis.Dialogue;
using Nivalis.Dialogue.ArticyImporter;
using Nivalis.GhostSystem.Ai;
using Nivalis.InventorySystem;
using Nivalis.Localization;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("LocalApi.Feature")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("LocalApi.Feature")]
[assembly: AssemblyTitle("LocalApi.Feature")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	public sealed class LocalApiModule : IFeatureModule, IReloadableModule, IDisposable
	{
		private ModuleServices services;

		private InspectorApi? api;

		private MenuAutomation? menuAutomation;

		private DebugAutomation? debugAutomation;

		private ModQuestCatalog? modQuests;

		private Action<string> log;

		private bool started;

		public void Configure(ModuleServices services)
		{
			this.services = services;
		}

		public void Initialize(Action<string> log, string? state)
		{
			this.log = log;
			menuAutomation = new MenuAutomation();
			debugAutomation = new DebugAutomation();
			modQuests = new ModQuestCatalog();
		}

		public string? CaptureState()
		{
			return null;
		}

		public void Update()
		{
			if (!started)
			{
				started = true;
				api = new InspectorApi((bool inactive) => JsonSerializer.Serialize(NpcReader.Capture(inactive, log)), () => services.HealthJson(), () => JsonSerializer.Serialize(menuAutomation.Capture()), (UiCommand command) => JsonSerializer.Serialize(menuAutomation.Execute(command)), GameScreenshot.Capture, () => JsonSerializer.Serialize(QuestSnapshot.Capture(log)), (DialogueQuery query) => JsonSerializer.Serialize(DialogueCatalog.Capture(query, log)), () => JsonSerializer.Serialize(DialogueSnapshot.Capture(log)), () => JsonSerializer.Serialize(ItemSnapshot.Capture(log)), () => JsonSerializer.Serialize(RecipeSnapshot.Capture(log)), log, () => JsonSerializer.Serialize(debugAutomation.Capture()), (DebugCommand command) => JsonSerializer.Serialize(debugAutomation.Execute(command)), () => JsonSerializer.Serialize(QuestCandidates.Capture(log)), () => JsonSerializer.Serialize(modQuests.Capture(log)), (NameValueCollection query) => JsonSerializer.Serialize(ModQuestCatalog.Send(query)));
			}
			api?.Update();
		}

		public void OnGUI()
		{
		}

		public void Dispose()
		{
			api?.Dispose();
			api = null;
			menuAutomation = null;
			debugAutomation = null;
			modQuests = null;
		}
	}
	internal static class GameScreenshot
	{
		public static Task<byte[]> Capture(CancellationToken cancellation)
		{
			string text = Path.Combine(ToolkitPaths.Data, "screenshots");
			Directory.CreateDirectory(text);
			string text2 = Path.Combine(text, $"{DateTime.UtcNow:yyyyMMdd-HHmmss-fff}-{Guid.NewGuid():N}.png");
			ScreenCapture.CaptureScreenshot(text2);
			return ScreenshotFile.ReadWhenReady(text2, cancellation);
		}
	}
	internal sealed class MenuAutomation
	{
		private sealed record UiBounds(float X, float Y, float Width, float Height);

		private readonly Dictionary<int, Selectable> observed = new Dictionary<int, Selectable>();

		private string? snapshotId;

		private int sceneHandle;

		private GameObject? selectedAtCapture;

		public object Capture()
		{
			//IL_0024: 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_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			observed.Clear();
			snapshotId = Guid.NewGuid().ToString("N");
			Scene activeScene = SceneManager.GetActiveScene();
			sceneHandle = ((Scene)(ref activeScene)).handle;
			List<object> list = new List<object>();
			GameObject val = (selectedAtCapture = (((Object)(object)EventSystem.current == (Object)null) ? null : EventSystem.current.currentSelectedGameObject));
			foreach (Selectable item in (Il2CppArrayBase<Selectable>)(object)Selectable.allSelectablesArray)
			{
				if (IsVisible(item))
				{
					int instanceID = ((Object)item).GetInstanceID();
					observed.Add(instanceID, item);
					UiBounds bounds = Bounds(((Il2CppObjectBase)((Component)item).transform).Cast<RectTransform>());
					Vector2? val2 = PointerPoint(item);
					string name = ((Object)item).name;
					string name2 = ((MemberInfo)((Object)item).GetIl2CppType()).Name;
					string label = string.Join(" | ", (from text in (IEnumerable<TMP_Text>)((Component)item).GetComponentsInChildren<TMP_Text>()
						select text.text into text
						where !string.IsNullOrWhiteSpace(text)
						select text).Distinct());
					bool selected = (Object)(object)((Component)item).gameObject == (Object)(object)val;
					bool interactable = item.IsInteractable();
					Toggle val3 = ((Il2CppObjectBase)item).TryCast<Toggle>();
					list.Add(new
					{
						Id = instanceID,
						Name = name,
						Type = name2,
						Label = label,
						Selected = selected,
						Interactable = interactable,
						IsOn = ((val3 != null) ? new bool?(val3.isOn) : ((bool?)null)),
						Bounds = bounds,
						CanSelect = val2.HasValue,
						CanClick = (val2.HasValue && (Object)(object)ExecuteEvents.GetEventHandler<IPointerClickHandler>(((Component)item).gameObject) == (Object)(object)((Component)item).gameObject),
						ClickPoint = (val2.HasValue ? new
						{
							X = val2.Value.x,
							Y = (float)Screen.height - val2.Value.y
						} : null)
					});
				}
			}
			var panels = (from panel in ((IEnumerable<Object>)Resources.FindObjectsOfTypeAll(Il2CppType.Of<UIPanel>())).Select((Object obj) => ((Il2CppObjectBase)obj).Cast<UIPanel>()).Where(delegate(UIPanel panel)
				{
					//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_001b: Unknown result type (might be due to invalid IL or missing references)
					//IL_0020: Unknown result type (might be due to invalid IL or missing references)
					Scene scene = ((Component)panel).gameObject.scene;
					if (((Scene)(ref scene)).IsValid())
					{
						scene = ((Component)panel).gameObject.scene;
						if (((Scene)(ref scene)).isLoaded && ((Component)panel).gameObject.activeInHierarchy && panel.IsVisible)
						{
							return GroupsAllow(((Component)panel).transform, pointer: false);
						}
					}
					return false;
				})
				select new
				{
					Name = ((Object)panel).name,
					Type = ((MemberInfo)((Object)panel).GetIl2CppType()).Name
				}).ToArray();
			return new
			{
				SnapshotId = snapshotId,
				ScreenWidth = Screen.width,
				ScreenHeight = Screen.height,
				CoordinateOrigin = "top-left",
				Panels = panels,
				Controls = list
			};
		}

		public unsafe object Execute(UiCommand command)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_0429: Unknown result type (might be due to invalid IL or missing references)
			//IL_0438: Expected O, but got Unknown
			//IL_0413: Unknown result type (might be due to invalid IL or missing references)
			//IL_0422: Expected O, but got Unknown
			//IL_0331: Unknown result type (might be due to invalid IL or missing references)
			//IL_036d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_0379: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0382: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_038a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0393: Expected O, but got Unknown
			//IL_0340: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_035e: Unknown result type (might be due to invalid IL or missing references)
			if (!(snapshotId != command.Snapshot))
			{
				int num = sceneHandle;
				Scene activeScene = SceneManager.GetActiveScene();
				if (num == ((Scene)(ref activeScene)).handle)
				{
					snapshotId = null;
					try
					{
						string action = command.Action;
						if ((action == "open-settings" || action == "close-settings") ? true : false)
						{
							SettingsPanel[] array = ((IEnumerable<Object>)Resources.FindObjectsOfTypeAll(Il2CppType.Of<SettingsPanel>())).Select((Object val6) => ((Il2CppObjectBase)val6).Cast<SettingsPanel>()).Where(delegate(SettingsPanel panel)
							{
								//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_001b: Unknown result type (might be due to invalid IL or missing references)
								//IL_0020: Unknown result type (might be due to invalid IL or missing references)
								Scene scene = ((Component)panel).gameObject.scene;
								if (((Scene)(ref scene)).IsValid())
								{
									scene = ((Component)panel).gameObject.scene;
									return ((Scene)(ref scene)).isLoaded;
								}
								return false;
							}).ToArray();
							if (array.Length != 1)
							{
								throw new ApiFailure(409, "A unique Settings panel is not available in this scene.");
							}
							if (command.Action == "open-settings")
							{
								if (!((UIPanel)array[0]).IsVisible)
								{
									((UIPanel)array[0]).Show();
								}
							}
							else if (((UIPanel)array[0]).IsVisible)
							{
								((UIPanel)array[0]).OnClose();
							}
							return new
							{
								Status = "ok",
								Action = command.Action
							};
						}
						EventSystem current = EventSystem.current;
						if ((Object)(object)current == (Object)null)
						{
							throw new ApiFailure(409, "No UI event system is available.");
						}
						action = command.Action;
						if ((action == "click" || action == "select") ? true : false)
						{
							if (!observed.TryGetValue(command.Id.Value, out Selectable value) || !IsVisible(value) || !value.IsInteractable())
							{
								throw new ApiFailure(409, "Control is no longer visible and interactable. Read GET /ui again.");
							}
							Vector2? val = PointerPoint(value);
							if (!val.HasValue)
							{
								throw new ApiFailure(409, "Control is blocked or not ready for pointer input.");
							}
							if (command.Action == "click" && (Object)(object)ExecuteEvents.GetEventHandler<IPointerClickHandler>(((Component)value).gameObject) != (Object)(object)((Component)value).gameObject)
							{
								throw new ApiFailure(409, "Control does not handle pointer clicks. Use select and directional navigation.");
							}
							current.SetSelectedGameObject(((Component)value).gameObject);
							if (command.Action == "click")
							{
								PointerEventData val2 = new PointerEventData(current)
								{
									button = (InputButton)0,
									position = val.Value
								};
								ExecuteEvents.Execute<IPointerClickHandler>(((Component)value).gameObject, (BaseEventData)(object)val2, ExecuteEvents.pointerClickHandler);
							}
						}
						else
						{
							GameObject currentSelectedGameObject = current.currentSelectedGameObject;
							if ((Object)(object)currentSelectedGameObject != (Object)(object)selectedAtCapture)
							{
								throw new ApiFailure(409, "Selection changed after the snapshot. Read GET /ui again.");
							}
							Selectable val3 = (((Object)(object)currentSelectedGameObject == (Object)null) ? null : currentSelectedGameObject.GetComponent<Selectable>());
							if ((Object)(object)val3 == (Object)null || !IsVisible(val3) || !val3.IsInteractable() || !PointerPoint(val3).HasValue)
							{
								throw new ApiFailure(409, "Select a visible, unblocked control first.");
							}
							bool flag;
							if (!(command.Action == "move"))
							{
								flag = ((!(command.Action == "submit")) ? ((Object)(object)ExecuteEvents.ExecuteHierarchy<ICancelHandler>(currentSelectedGameObject, new BaseEventData(current), ExecuteEvents.cancelHandler) != (Object)null) : ExecuteEvents.Execute<ISubmitHandler>(currentSelectedGameObject, new BaseEventData(current), ExecuteEvents.submitHandler));
							}
							else
							{
								object obj = command.Direction switch
								{
									"up" => ((MoveDirection)1, Vector2.up), 
									"down" => ((MoveDirection)3, Vector2.down), 
									"left" => ((MoveDirection)0, Vector2.left), 
									_ => ((MoveDirection)2, Vector2.right), 
								};
								MoveDirection item = ((ValueTuple<MoveDirection, Vector2>*)(&obj))->Item1;
								Vector2 item2 = ((ValueTuple<MoveDirection, Vector2>*)(&obj))->Item2;
								AxisEventData val4 = new AxisEventData(current)
								{
									moveDir = item,
									moveVector = item2
								};
								flag = ExecuteEvents.Execute<IMoveHandler>(currentSelectedGameObject, (BaseEventData)(object)val4, ExecuteEvents.moveHandler);
								GameObject currentSelectedGameObject2 = current.currentSelectedGameObject;
								Selectable val5 = (((Object)(object)currentSelectedGameObject2 == (Object)null) ? null : currentSelectedGameObject2.GetComponent<Selectable>());
								if ((Object)(object)val5 == (Object)null || !IsVisible(val5) || !PointerPoint(val5).HasValue)
								{
									current.SetSelectedGameObject(currentSelectedGameObject);
									throw new ApiFailure(409, "Native navigation targeted a blocked control. Focus was restored; use select with a visible control id.");
								}
							}
							if (!flag)
							{
								throw new ApiFailure(409, "The selected control does not handle this navigation event.");
							}
						}
						return new
						{
							Status = "ok",
							Action = command.Action
						};
					}
					finally
					{
						observed.Clear();
						selectedAtCapture = null;
					}
				}
			}
			throw new ApiFailure(409, "UI snapshot is stale. Read GET /ui again before acting.");
		}

		private static bool IsVisible(Selectable control)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)control == (Object)null) && ((UIBehaviour)control).IsActive())
			{
				Scene scene = ((Component)control).gameObject.scene;
				if (((Scene)(ref scene)).IsValid())
				{
					if ((Object)(object)control.targetGraphic != (Object)null && control.targetGraphic.canvasRenderer.cull)
					{
						return false;
					}
					if (!GroupsAllow(((Component)control).transform, pointer: false))
					{
						return false;
					}
					Canvas componentInParent = ((Component)control).GetComponentInParent<Canvas>();
					if ((Object)(object)componentInParent == (Object)null || !((Behaviour)componentInParent).isActiveAndEnabled)
					{
						return false;
					}
					UiBounds uiBounds = Bounds(((Il2CppObjectBase)((Component)control).transform).Cast<RectTransform>());
					if (uiBounds.Width > 0f && uiBounds.Height > 0f && uiBounds.X < (float)Screen.width && uiBounds.Y < (float)Screen.height && uiBounds.X + uiBounds.Width > 0f)
					{
						return uiBounds.Y + uiBounds.Height > 0f;
					}
					return false;
				}
			}
			return false;
		}

		private static bool GroupsAllow(Transform transform, bool pointer)
		{
			Transform val = transform;
			while ((Object)(object)val != (Object)null)
			{
				bool flag = false;
				foreach (CanvasGroup component in ((Component)val).GetComponents<CanvasGroup>())
				{
					if (((Behaviour)component).enabled)
					{
						if (component.alpha < (pointer ? 0.99f : 0.01f) || (pointer && (!component.interactable || !component.blocksRaycasts)))
						{
							return false;
						}
						flag |= component.ignoreParentGroups;
					}
				}
				if (flag)
				{
					break;
				}
				val = val.parent;
			}
			return true;
		}

		internal static Vector2? PointerPoint(Selectable control)
		{
			//IL_007a: 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_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)EventSystem.current == (Object)null || !control.IsInteractable() || !GroupsAllow(((Component)control).transform, pointer: true))
			{
				return null;
			}
			Toggle obj = ((Il2CppObjectBase)control).TryCast<Toggle>();
			Graphic val = ((obj != null) ? obj.graphic : null) ?? control.targetGraphic;
			RectTransform val2 = (((Object)(object)val == (Object)null) ? ((Il2CppObjectBase)((Component)control).transform).Cast<RectTransform>() : val.rectTransform);
			Camera worldCamera = ((Component)val2).GetComponentInParent<Canvas>().rootCanvas.worldCamera;
			Rect rect = val2.rect;
			Vector2 val3 = RectTransformUtility.WorldToScreenPoint(worldCamera, ((Transform)val2).TransformPoint(Vector2.op_Implicit(((Rect)(ref rect)).center)));
			PointerEventData val4 = new PointerEventData(EventSystem.current)
			{
				position = val3
			};
			List<RaycastResult> val5 = new List<RaycastResult>();
			EventSystem.current.RaycastAll(val4, val5);
			if (val5.Count == 0 || (Object)(object)val5[0].gameObject.GetComponentInParent<Selectable>() != (Object)(object)control)
			{
				return null;
			}
			return val3;
		}

		private static UiBounds Bounds(RectTransform rect)
		{
			Il2CppStructArray<Vector3> val = new Il2CppStructArray<Vector3>(4L);
			rect.GetWorldCorners(val);
			Canvas canvas = ((Component)rect).GetComponentInParent<Canvas>().rootCanvas;
			Vector2[] source = ((IEnumerable<Vector3>)val).Select((Vector3 point) => RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, point)).ToArray();
			float num = source.Min((Vector2 point) => point.x);
			float num2 = source.Max((Vector2 point) => point.x);
			float num3 = source.Min((Vector2 point) => point.y);
			float num4 = source.Max((Vector2 point) => point.y);
			return new UiBounds(num, (float)Screen.height - num4, num2 - num, num4 - num3);
		}
	}
	internal static class ScreenshotFile
	{
		public static bool IsCompletePng(byte[] bytes)
		{
			if (bytes.Length >= 20 && bytes.AsSpan(0, 8).SequenceEqual(new byte[8] { 137, 80, 78, 71, 13, 10, 26, 10 }))
			{
				return bytes.AsSpan(bytes.Length - 12).SequenceEqual(new byte[12]
				{
					0, 0, 0, 0, 73, 69, 78, 68, 174, 66,
					96, 130
				});
			}
			return false;
		}

		public static async Task<byte[]> ReadWhenReady(string path, CancellationToken cancellation)
		{
			using CancellationTokenSource deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
			deadline.CancelAfter(TimeSpan.FromSeconds(8.0));
			try
			{
				while (true)
				{
					deadline.Token.ThrowIfCancellationRequested();
					try
					{
						byte[] array = await File.ReadAllBytesAsync(path, deadline.Token).ConfigureAwait(continueOnCapturedContext: false);
						if (IsCompletePng(array))
						{
							return array;
						}
					}
					catch (FileNotFoundException)
					{
					}
					catch (IOException ex2) when ((uint)((ex2.HResult & 0xFFFF) - 32) <= 1u)
					{
					}
					await Task.Delay(50, deadline.Token).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			catch (OperationCanceledException) when (!cancellation.IsCancellationRequested)
			{
				throw new ApiFailure(504, "Screenshot was not completed within eight seconds. Ensure the game is rendering.");
			}
		}
	}
	internal sealed class ApiFailure : Exception
	{
		public int StatusCode { get; }

		public ApiFailure(int statusCode, string message)
			: base(message)
		{
			StatusCode = statusCode;
		}
	}
	internal sealed record UiCommand(string Action, string Snapshot, int? Id, string? Direction)
	{
		public static UiCommand Parse(NameValueCollection query)
		{
			string text = query["action"];
			bool flag;
			switch (text)
			{
			case "cancel":
			case "select":
			case "submit":
			case "open-settings":
			case "close-settings":
			case "click":
			case "move":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				throw new ApiFailure(400, "action must be open-settings, close-settings, click, select, move, submit, or cancel.");
			}
			string text2 = query["snapshot"];
			if (!Guid.TryParseExact(text2, "N", out var _))
			{
				throw new ApiFailure(400, "Supply SnapshotId from GET /ui.");
			}
			int? id = null;
			if ((text == "click" || text == "select") ? true : false)
			{
				if (!int.TryParse(query["id"], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2))
				{
					throw new ApiFailure(400, "click/select requires a control id from GET /ui.");
				}
				id = result2;
			}
			string text3 = query["direction"];
			flag = text == "move";
			if (flag)
			{
				bool flag2;
				switch (text3)
				{
				case "up":
				case "down":
				case "left":
				case "right":
					flag2 = true;
					break;
				default:
					flag2 = false;
					break;
				}
				flag = !flag2;
			}
			if (flag)
			{
				throw new ApiFailure(400, "move requires direction=up, down, left, or right.");
			}
			return new UiCommand(text, text2, id, text3);
		}
	}
	internal sealed class DebugAutomation
	{
		private string? snapshot;

		private int scene;

		private PlayerCharacter? observedPlayer;

		private IntPtr observedStep;

		private bool observedOpen;

		private readonly Dictionary<int, StartDialogueInteraction> targets = new Dictionary<int, StartDialogueInteraction>();

		public object Capture()
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			snapshot = Guid.NewGuid().ToString("N");
			Scene activeScene = SceneManager.GetActiveScene();
			scene = ((Scene)(ref activeScene)).handle;
			Player val = Player();
			observedPlayer = ((val != null) ? val.Character : null);
			DialogueUI instance = DialogueUI._instance;
			observedOpen = (Object)(object)instance != (Object)null && ((UIWindow)instance)._isOpen;
			IntPtr intPtr;
			if (!observedOpen)
			{
				intPtr = IntPtr.Zero;
			}
			else
			{
				DialogueStepDisplayData currentStepData = instance._currentStepData;
				intPtr = ((currentStepData != null) ? ((Il2CppObjectBase)currentStepData).Pointer : IntPtr.Zero);
			}
			observedStep = intPtr;
			targets.Clear();
			List<object> list = new List<object>();
			if (Character.instances != null)
			{
				Enumerator<Character> enumerator = Character.instances.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Character current = enumerator.Current;
					if (!((Object)(object)current == (Object)null) && Loaded((Component)(object)current))
					{
						StartDialogueInteraction dialogueInteraction = current.DialogueInteraction;
						if (CanStart(dialogueInteraction))
						{
							int instanceID = ((Object)current).GetInstanceID();
							targets[instanceID] = dialogueInteraction;
							list.Add(new
							{
								CharacterId = instanceID,
								Name = ((Object)current).name,
								Position = Position(((Component)current).transform.position)
							});
						}
					}
				}
			}
			string? snapshotId = snapshot;
			activeScene = SceneManager.GetActiveScene();
			return new
			{
				SnapshotId = snapshotId,
				Scene = ((Scene)(ref activeScene)).name,
				PlayerAvailable = ((Object)(object)observedPlayer != (Object)null && Loaded((Component)(object)observedPlayer)),
				PlayerPosition = (((Object)(object)observedPlayer == (Object)null) ? null : Position(((Component)observedPlayer).transform.position)),
				DialogueOpen = observedOpen,
				DialogueTargets = list
			};
		}

		public object Execute(DebugCommand command)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			if (!(snapshot != command.Snapshot))
			{
				int num = scene;
				Scene activeScene = SceneManager.GetActiveScene();
				if (num == ((Scene)(ref activeScene)).handle)
				{
					snapshot = null;
					Player val = Player();
					PlayerCharacter val2 = ((val != null) ? val.Character : null);
					if ((Object)(object)val2 == (Object)null || (Object)(object)val2 != (Object)(object)observedPlayer || !Loaded((Component)(object)val2))
					{
						throw new ApiFailure(409, "The observed player is no longer available.");
					}
					DialogueUI instance = DialogueUI._instance;
					bool flag = (Object)(object)instance != (Object)null && ((UIWindow)instance)._isOpen;
					IntPtr intPtr;
					if (!flag)
					{
						intPtr = IntPtr.Zero;
					}
					else
					{
						DialogueStepDisplayData currentStepData = instance._currentStepData;
						intPtr = ((currentStepData != null) ? ((Il2CppObjectBase)currentStepData).Pointer : IntPtr.Zero);
					}
					IntPtr intPtr2 = intPtr;
					if (flag != observedOpen || intPtr2 != observedStep)
					{
						throw new ApiFailure(409, "Dialogue changed. Read GET /debug and /dialogue/current again.");
					}
					if (command.Action == "teleport")
					{
						if (flag || (Object)(object)val2.DrivenBoat != (Object)null || (Object)(object)val2.Controller == (Object)null)
						{
							throw new ApiFailure(409, "Teleport requires an on-foot player outside dialogue.");
						}
						val2.Controller.StopMovement();
						val2.Controller.TeleportPlayer(new Vector3(command.X, command.Y, command.Z), ((Component)val2).transform.rotation, false);
						return new
						{
							Status = "ok",
							Action = command.Action,
							Position = Position(((Component)val2).transform.position)
						};
					}
					if (command.Action == "start-dialogue")
					{
						if (flag)
						{
							throw new ApiFailure(409, "A dialogue is already open.");
						}
						if (!targets.TryGetValue(command.CharacterId, out StartDialogueInteraction value) || !CanStart(value))
						{
							throw new ApiFailure(409, "NPC no longer has an available dialogue interaction. Read GET /debug again.");
						}
						value.StartDialogue(val);
						return new
						{
							Status = "requested",
							Action = command.Action,
							CharacterId = command.CharacterId
						};
					}
					if (!flag || !((UIPanel)instance)._isVisible || !Loaded((Component)(object)instance))
					{
						throw new ApiFailure(409, "No visible dialogue is open.");
					}
					Button val3 = null;
					if (command.Action == "choose-dialogue")
					{
						DialogueStepDisplayData currentStepData2 = instance._currentStepData;
						List<Choice> val4 = ((currentStepData2 != null) ? currentStepData2.Choices : null);
						if (val4 == null || command.Choice >= val4.Count || val4[command.Choice] == null || !val4[command.Choice].Enabled)
						{
							throw new ApiFailure(409, "Choice is unavailable or disabled.");
						}
						if (instance._choiceInstances != null)
						{
							Enumerator<DialogueChoiceUI> enumerator = instance._choiceInstances.GetEnumerator();
							while (enumerator.MoveNext())
							{
								DialogueChoiceUI current = enumerator.Current;
								if ((Object)(object)current != (Object)null && current._choiceIndex == command.Choice && Loaded((Component)(object)current))
								{
									val3 = current.button;
									break;
								}
							}
						}
					}
					else
					{
						val3 = instance.fullScreenButton;
					}
					if ((Object)(object)val3 == (Object)null || !Loaded((Component)(object)val3) || !((Behaviour)val3).isActiveAndEnabled || !((Selectable)val3).IsInteractable() || !MenuAutomation.PointerPoint((Selectable)(object)val3).HasValue)
					{
						throw new ApiFailure(409, "Dialogue control is not ready. Read the dialogue state again.");
					}
					((UnityEvent)val3.onClick).Invoke();
					return new
					{
						Status = "requested",
						Action = command.Action
					};
				}
			}
			throw new ApiFailure(409, "Debug snapshot is stale. Read GET /debug again.");
		}

		private static Player? Player()
		{
			PlayerManager val = default(PlayerManager);
			if (!Singleton<PlayerManager>.InstanceExist(ref val))
			{
				return null;
			}
			return val.LocalPlayer;
		}

		private static bool CanStart(StartDialogueInteraction? target)
		{
			if ((Object)(object)target != (Object)null && Loaded((Component)(object)target) && ((Behaviour)target).isActiveAndEnabled && !target.dialogueInProgress && target.currentDialogueTree?.Value != null)
			{
				return target.CanInteract();
			}
			return false;
		}

		private static bool Loaded(Component component)
		{
			//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_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			Scene val = component.gameObject.scene;
			if (((Scene)(ref val)).IsValid())
			{
				val = component.gameObject.scene;
				if (((Scene)(ref val)).isLoaded)
				{
					return component.gameObject.activeInHierarchy;
				}
			}
			return false;
		}

		private static object Position(Vector3 point)
		{
			//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
			{
				X = point.x,
				Y = point.y,
				Z = point.z
			};
		}
	}
	internal sealed record DebugCommand(string Action, string Snapshot, float X, float Y, float Z, int CharacterId, int Choice)
	{
		public static DebugCommand Parse(NameValueCollection query)
		{
			string text = query["action"];
			bool flag;
			switch (text)
			{
			case "teleport":
			case "start-dialogue":
			case "advance-dialogue":
			case "choose-dialogue":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				throw new ApiFailure(400, "action must be teleport, start-dialogue, advance-dialogue, or choose-dialogue.");
			}
			if (!Guid.TryParseExact(query["snapshot"], "N", out var _))
			{
				throw new ApiFailure(400, "Supply SnapshotId from GET /debug.");
			}
			int num = ((text == "choose-dialogue") ? Integer("choice") : 0);
			if (num < 0)
			{
				throw new ApiFailure(400, "choice must be non-negative.");
			}
			return new DebugCommand(text, query["snapshot"], (text == "teleport") ? Coordinate("x") : 0f, (text == "teleport") ? Coordinate("y") : 0f, (text == "teleport") ? Coordinate("z") : 0f, (text == "start-dialogue") ? Integer("characterId") : 0, num);
			float Coordinate(string name)
			{
				if (!float.TryParse(query[name], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) || !float.IsFinite(result2))
				{
					throw new ApiFailure(400, name + " must be a finite world coordinate.");
				}
				return result2;
			}
			int Integer(string name)
			{
				if (!int.TryParse(query[name], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2))
				{
					throw new ApiFailure(400, name + " must be an integer.");
				}
				return result2;
			}
		}
	}
	internal static class DialogueCatalog
	{
		private sealed record Source(string Id, string IdKind, string Kind, string? Name, string? Description, string[] SpeakerTechnicalNames, string? StoryArcId, string? StoryArcName, string? TreeId, IDialogueTree? Tree, Conversation? Conversation, BackgroundNPCConv? Ambient);

		private sealed record WalkResult(string[] RootIds, List<IDialogue> Nodes, bool Truncated, string[] UnsupportedTypes);

		private sealed record ObjectiveLink(string? QuestId, string? QuestArticyId, string QuestName, string? ObjectiveId, string TargetId, bool CompleteOnDialogueEnd);

		private sealed record QuestLink(string? QuestId, string? QuestArticyId, string QuestName, string? ObjectiveId, string RelationKind, string TargetKind, string TargetId, bool? CompleteOnDialogueEnd, string? QuestState);

		private const int NodeLimit = 1000;

		public static object Capture(DialogueQuery query, Action<string> log)
		{
			int skipped = 0;
			List<Source> list = new List<Source>();
			HashSet<IntPtr> hashSet = new HashSet<IntPtr>();
			Dictionary<IntPtr, string> dictionary = new Dictionary<IntPtr, string>();
			DialogueTreeProgressManager val = default(DialogueTreeProgressManager);
			bool num = Singleton<DialogueTreeProgressManager>.InstanceExist(ref val);
			Dictionary<string, ValueTuple<IConversation, IStoryArc>> val2 = (num ? val._storyArcConversationsByArticyId : null);
			Dictionary<string, IDialogueTree> val3 = (num ? val.AllDialogueTrees : null);
			if (val2 != null)
			{
				Enumerator<string, ValueTuple<IConversation, IStoryArc>> enumerator = val2.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<string, ValueTuple<IConversation, IStoryArc>> current = enumerator.Current;
					try
					{
						IConversation item = current.Value.Item1;
						Conversation val4 = ((item != null) ? ((Il2CppObjectBase)item).TryCast<Conversation>() : null);
						if (val4 == null)
						{
							skipped++;
							continue;
						}
						IStoryArc item2 = current.Value.Item2;
						StoryArc val5 = ((item2 != null) ? ((Il2CppObjectBase)item2).TryCast<StoryArc>() : null);
						IDialogueTree val6 = Unwrap<IDialogueTree>(val4.dialogueTree);
						if (val6 != null)
						{
							hashSet.Add(((Il2CppObjectBase)val6).Pointer);
						}
						dictionary[((Il2CppObjectBase)val4).Pointer] = current.Key;
						list.Add(new Source(current.Key, "articy", "story", val4.convName, val4._Description_k__BackingField, Names(val4.speakerName), (val5 != null) ? val5.arcID : null, (val5 != null) ? val5.arcName : null, TreeId(val6), val6, val4, null));
					}
					catch (Exception error)
					{
						Failed("conversation " + current.Key, error);
					}
				}
			}
			if (val3 != null)
			{
				Enumerator<string, IDialogueTree> enumerator2 = val3.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					KeyValuePair<string, IDialogueTree> current2 = enumerator2.Current;
					try
					{
						IDialogueTree value = current2.Value;
						if (value != null && !hashSet.Contains(((Il2CppObjectBase)value).Pointer))
						{
							string text = TreeId(value);
							string text2 = EmptyToNull(current2.Key);
							string id = text ?? text2 ?? $"runtime-tree:{((Il2CppObjectBase)value).Pointer.ToInt64():x}";
							list.Add(new Source(id, (text != null) ? "articy" : ((text2 != null) ? "runtime-key" : "session-instance"), "standalone", text2 ?? NativeType((Il2CppObjectBase)(object)value), null, Array.Empty<string>(), null, null, text, value, null, null));
						}
					}
					catch (Exception error2)
					{
						Failed("dialogue tree " + current2.Key, error2);
					}
				}
			}
			Il2CppReferenceArray<Object> val7 = Resources.FindObjectsOfTypeAll(Il2CppType.Of<BackgroundNPCConv>());
			foreach (Object item3 in (Il2CppArrayBase<Object>)(object)val7)
			{
				try
				{
					BackgroundNPCConv val8 = ((Il2CppObjectBase)item3).Cast<BackgroundNPCConv>();
					string text3 = EmptyToNull(val8.ArticyTechnicalName);
					list.Add(new Source((text3 == null) ? $"ambient-instance:{((Object)val8).GetInstanceID()}" : ("ambient:" + text3), (text3 == null) ? "session-instance" : "ambient-technical-name", "ambient", text3 ?? ((Object)val8).name, null, (val8.speakers == null) ? Array.Empty<string>() : Il2CppArrayBase<string>.op_Implicit(val8.speakers.ToArray()), null, null, null, null, null, val8));
				}
				catch (Exception error3)
				{
					Failed("ambient conversation", error3);
				}
			}
			ObjectiveLink[] array = ReadObjectiveLinks(log, ref skipped);
			List<Source> list2 = list.Where((Source source) => Matches(source, query)).OrderBy<Source, string>((Source source) => source.Id, StringComparer.Ordinal).ToList();
			Dictionary<string, QuestLink[]> questMatches = new Dictionary<string, QuestLink[]>(StringComparer.Ordinal);
			bool questFilterComplete = skipped == 0;
			if (query.QuestId != null)
			{
				ObjectiveLink[] requested = array.Where((ObjectiveLink link) => Same(link.QuestId, query.QuestId) || Same(link.QuestArticyId, query.QuestId)).ToArray();
				list2 = list2.Where(delegate(Source source)
				{
					WalkResult walkResult2 = Walk(source, log, ref skipped);
					questFilterComplete &= !walkResult2.Truncated && walkResult2.UnsupportedTypes.Length == 0;
					QuestLink[] array2 = MatchObjectives(source, requested, walkResult2).Concat(from link in ReadQuestActionLinks(walkResult2)
						where Same(link.QuestId, query.QuestId) || Same(link.QuestArticyId, query.QuestId)
						select link).ToArray();
					questMatches[source.Id] = array2;
					return array2.Length != 0;
				}).ToList();
			}
			List<object> list3 = new List<object>();
			foreach (Source item4 in list2.Skip(query.Offset).Take(query.Limit))
			{
				try
				{
					WalkResult walkResult = (query.IncludeNodes ? Walk(item4, log, ref skipped) : null);
					QuestLink[] value2;
					QuestLink[] questReferences = (questMatches.TryGetValue(item4.Id, out value2) ? value2 : MatchObjectives(item4, array, walkResult).Concat(ReadQuestActionLinks(walkResult)).ToArray());
					list3.Add(new
					{
						Id = item4.Id,
						IdKind = item4.IdKind,
						Kind = item4.Kind,
						Name = item4.Name,
						Description = item4.Description,
						IsConditionNode = ((item4.Conversation == null) ? ((bool?)null) : new bool?(item4.Conversation.isConditionNode)),
						SpeakerTechnicalNames = item4.SpeakerTechnicalNames,
						StoryArcId = item4.StoryArcId,
						StoryArcName = item4.StoryArcName,
						TreeId = item4.TreeId,
						QuestReferences = questReferences,
						NextConversations = ReadTransitions(item4.Conversation, dictionary),
						Graph = ((walkResult == null) ? null : ReadGraph(item4, walkResult))
					});
				}
				catch (Exception error4)
				{
					Failed("catalog row " + item4.Id, error4);
				}
			}
			return new
			{
				CapturedAt = DateTimeOffset.Now,
				Scope = "All definitions in DialogueTreeProgressManager's existing conversation/tree indexes plus currently loaded BackgroundNPCConv assets. Not guaranteed to include unloaded bundles; no playability/condition evaluation.",
				Available = (val2 != null || val3 != null || ((Il2CppArrayBase<Object>)(object)val7).Length > 0),
				Skipped = skipped,
				CatalogCount = list.Count,
				Total = list2.Count,
				Offset = query.Offset,
				Limit = query.Limit,
				Count = list3.Count,
				HasMore = ((long)query.Offset + (long)query.Limit < list2.Count),
				QuestReferenceScope = "Explicit CustomQuest DialogueQuest objective references and QuestAdder/QuestEnder node actions. Summaries include root objective references; includeNodes or questId also traverses node objectives and quest actions. Does not infer relationships by names or script text.",
				QuestFilterComplete = questFilterComplete,
				IncludeNodes = query.IncludeNodes,
				Conversations = list3
			};
			void Failed(string subject, Exception ex)
			{
				skipped++;
				log("Could not inspect " + subject + ": " + ex.Message);
			}
		}

		private static bool Matches(Source source, DialogueQuery query)
		{
			if ((query.Kind == "all" || source.Kind == query.Kind) && (query.Id == null || Same(source.Id, query.Id)) && (query.Speaker == null || source.SpeakerTechnicalNames.Any((string name) => Contains(name, query.Speaker))))
			{
				if (query.Search != null && !Contains(source.Id, query.Search) && !Contains(source.Name, query.Search) && !Contains(source.Description, query.Search))
				{
					return Contains(source.StoryArcName, query.Search);
				}
				return true;
			}
			return false;
		}

		private static ObjectiveLink[] ReadObjectiveLinks(Action<string> log, ref int skipped)
		{
			List<ObjectiveLink> list = new List<ObjectiveLink>();
			Dictionary<int, Quest> dictionary = new Dictionary<int, Quest>();
			if (QuestDatabase._allItems != null)
			{
				foreach (Quest item in (Il2CppArrayBase<Quest>)(object)QuestDatabase._allItems)
				{
					if ((Object)(object)item != (Object)null)
					{
						dictionary[((Object)item).GetInstanceID()] = item;
					}
				}
			}
			foreach (Object item2 in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<CustomQuest>()))
			{
				CustomQuest val = ((Il2CppObjectBase)item2).Cast<CustomQuest>();
				dictionary[((Object)val).GetInstanceID()] = (Quest)(object)val;
			}
			foreach (Quest value in dictionary.Values)
			{
				try
				{
					CustomQuest val2 = ((Il2CppObjectBase)value).TryCast<CustomQuest>();
					if (((val2 != null) ? val2.subQuests : null) == null)
					{
						continue;
					}
					Enumerator<SubQuest> enumerator4 = val2.subQuests.GetEnumerator();
					while (enumerator4.MoveNext())
					{
						SubQuest current3 = enumerator4.Current;
						DialogueQuest val3 = ((current3 != null) ? ((Il2CppObjectBase)current3).TryCast<DialogueQuest>() : null);
						if (val3 != null && !string.IsNullOrWhiteSpace(val3.dialogueArticyGuid))
						{
							SerializableGuid guid = value.guid;
							list.Add(new ObjectiveLink((guid != null) ? guid.guid : null, value.ArticyQuestGuid, ((Object)value).name, ((SubQuest)val3).articyId, val3.dialogueArticyGuid, val3.completeOnDialogueEnd));
						}
					}
				}
				catch (Exception ex)
				{
					skipped++;
					log("Could not inspect quest dialogue references: " + ex.Message);
				}
			}
			return list.ToArray();
		}

		private static QuestLink[] MatchObjectives(Source source, ObjectiveLink[] links, WalkResult? walk)
		{
			HashSet<string> nodeIds = ((walk == null) ? null : new HashSet<string>(walk.Nodes.Select((IDialogue node) => NodeId(node)), StringComparer.OrdinalIgnoreCase));
			return (from link in links.Select(delegate(ObjectiveLink link)
				{
					List<string> list = new List<string>();
					if (source.Conversation != null && Same(link.TargetId, source.Id))
					{
						list.Add("conversation");
					}
					if (Same(link.TargetId, source.TreeId))
					{
						list.Add("tree");
					}
					HashSet<string> hashSet = nodeIds;
					if (hashSet != null && hashSet.Contains(link.TargetId))
					{
						list.Add("node");
					}
					string targetKind = string.Join("+", list);
					return (list.Count != 0) ? new QuestLink(link.QuestId, link.QuestArticyId, link.QuestName, link.ObjectiveId, "dialogue-objective", targetKind, link.TargetId, link.CompleteOnDialogueEnd, null) : null;
				})
				where link != null
				select link).Cast<QuestLink>().ToArray();
		}

		private static QuestLink[] ReadQuestActionLinks(WalkResult? walk)
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			List<QuestLink> list = new List<QuestLink>();
			if (walk == null)
			{
				return list.ToArray();
			}
			foreach (IDialogue node in walk.Nodes)
			{
				DialogueWithChoices obj = ((Il2CppObjectBase)node).TryCast<DialogueWithChoices>();
				object obj2 = ((obj != null) ? obj.actionTriggers : null);
				if (obj2 == null)
				{
					ConditionDialogueNode obj3 = ((Il2CppObjectBase)node).TryCast<ConditionDialogueNode>();
					obj2 = ((obj3 != null) ? obj3.actionTriggers : null);
					if (obj2 == null)
					{
						ScriptingDialogueObj obj4 = ((Il2CppObjectBase)node).TryCast<ScriptingDialogueObj>();
						obj2 = ((obj4 != null) ? obj4.actionTriggers : null);
					}
				}
				List<Wrapper<TriggeredAction>> val = (List<Wrapper<TriggeredAction>>)obj2;
				if (val == null)
				{
					continue;
				}
				Enumerator<Wrapper<TriggeredAction>> enumerator2 = val.GetEnumerator();
				while (enumerator2.MoveNext())
				{
					TriggeredAction? obj5 = Unwrap<TriggeredAction>(enumerator2.Current);
					QuestEnder val2 = ((obj5 != null) ? ((Il2CppObjectBase)obj5).TryCast<QuestEnder>() : null);
					object obj6;
					if (obj5 == null)
					{
						obj6 = null;
					}
					else
					{
						QuestAdder obj7 = ((Il2CppObjectBase)obj5).TryCast<QuestAdder>();
						obj6 = ((obj7 != null) ? obj7.quest : null);
					}
					if (obj6 == null)
					{
						obj6 = ((val2 != null) ? val2.quest : null);
					}
					Quest val3 = (Quest)obj6;
					if (!((Object)(object)val3 == (Object)null))
					{
						SerializableGuid guid = val3.guid;
						list.Add(new QuestLink((guid != null) ? guid.guid : null, val3.ArticyQuestGuid, ((Object)val3).name, null, (val2 == null) ? "quest-start" : "quest-end", "node", NodeId(node), null, (val2 != null) ? ((object)val2.state/*cast due to .constrained prefix*/).ToString() : null));
					}
				}
			}
			return list.ToArray();
		}

		private static object[] ReadTransitions(Conversation? conversation, Dictionary<IntPtr, string> ids)
		{
			List<object> list = new List<object>();
			if (((conversation != null) ? conversation.transitions : null) == null)
			{
				return list.ToArray();
			}
			Enumerator<ConvTransition> enumerator = conversation.transitions.GetEnumerator();
			while (enumerator.MoveNext())
			{
				ConvTransition current = enumerator.Current;
				if (current != null)
				{
					ConvConnection leadsTo = current.leadsTo;
					IConversation? obj = Unwrap<IConversation>((leadsTo != null) ? leadsTo.nextDialogue : null);
					Conversation val = ((obj != null) ? ((Il2CppObjectBase)obj).TryCast<Conversation>() : null);
					string? targetId = ((val == null) ? null : (ids.GetValueOrDefault(((Il2CppObjectBase)val).Pointer) ?? val.guid));
					ConvConnection leadsTo2 = current.leadsTo;
					list.Add(new
					{
						TargetId = targetId,
						TargetPinId = ((leadsTo2 != null) ? leadsTo2.TargetPinID : null),
						HasConditions = (current.checkers != null && current.checkers.Count > 0)
					});
				}
			}
			return list.ToArray();
		}

		private static WalkResult Walk(Source source, Action<string> log, ref int skipped)
		{
			Queue<IDialogue> queue = new Queue<IDialogue>();
			List<string> roots = new List<string>();
			HashSet<IntPtr> visited = new HashSet<IntPtr>();
			List<IDialogue> list = new List<IDialogue>();
			HashSet<string> hashSet = new HashSet<string>();
			IDialogueTree? tree = source.Tree;
			DialogueTree val = ((tree != null) ? ((Il2CppObjectBase)tree).TryCast<DialogueTree>() : null);
			if (val != null)
			{
				Root(Unwrap<IDialogue>(val.entryRoot));
				if (val.looseRoots != null)
				{
					Enumerator<Wrapper<IDialogue>> enumerator = val.looseRoots.GetEnumerator();
					while (enumerator.MoveNext())
					{
						Root(Unwrap<IDialogue>(enumerator.Current));
					}
				}
				ScriptingDialogueObj logicObj = val.logicObj;
				Root((logicObj != null) ? ((Il2CppObjectBase)logicObj).TryCast<IDialogue>() : null);
			}
			else
			{
				IDialogueTree? tree2 = source.Tree;
				LogicOnlyStoryTree val2 = ((tree2 != null) ? ((Il2CppObjectBase)tree2).TryCast<LogicOnlyStoryTree>() : null);
				if (val2 != null)
				{
					ScriptingDialogueObj logicObj2 = val2.logicObj;
					Root((logicObj2 != null) ? ((Il2CppObjectBase)logicObj2).TryCast<IDialogue>() : null);
				}
				else if (source.Tree != null)
				{
					hashSet.Add(NativeType((Il2CppObjectBase)(object)source.Tree));
				}
			}
			while (queue.Count > 0 && list.Count < 1000)
			{
				IDialogue val3 = queue.Dequeue();
				if (!visited.Add(((Il2CppObjectBase)val3).Pointer))
				{
					continue;
				}
				list.Add(val3);
				try
				{
					DialogueWithChoices val4 = ((Il2CppObjectBase)val3).TryCast<DialogueWithChoices>();
					if (val4 != null)
					{
						Enqueue(Unwrap<IDialogue>(val4.nextDialogue));
						if (val4.choices == null)
						{
							continue;
						}
						Enumerator<Wrapper<IChoice>> enumerator2 = val4.choices.GetEnumerator();
						while (enumerator2.MoveNext())
						{
							IChoice val5 = Unwrap<IChoice>(enumerator2.Current);
							DialogueChoice val6 = ((val5 != null) ? ((Il2CppObjectBase)val5).TryCast<DialogueChoice>() : null);
							if (val6 != null)
							{
								Enqueue(Unwrap<IDialogue>(val6.nextDialogue));
							}
							else if (val5 != null)
							{
								hashSet.Add(NativeType((Il2CppObjectBase)(object)val5));
							}
						}
						continue;
					}
					ConditionDialogueNode val7 = ((Il2CppObjectBase)val3).TryCast<ConditionDialogueNode>();
					if (val7 != null)
					{
						Enqueue(Unwrap<IDialogue>(val7.nextDialogue));
						Enqueue(Unwrap<IDialogue>(val7.nextDialogueOnFalse));
						continue;
					}
					ScriptingDialogueObj val8 = ((Il2CppObjectBase)val3).TryCast<ScriptingDialogueObj>();
					if (val8 != null)
					{
						Enqueue(Unwrap<IDialogue>(val8.nextDialogue));
					}
					else
					{
						hashSet.Add(NativeType((Il2CppObjectBase)(object)val3));
					}
				}
				catch (Exception ex)
				{
					skipped++;
					hashSet.Add(NativeType((Il2CppObjectBase)(object)val3));
					log("Could not inspect links in dialogue " + source.Id + ": " + ex.Message);
				}
			}
			return new WalkResult(roots.Distinct().ToArray(), list, queue.Count > 0, hashSet.OrderBy((string value) => value).ToArray());
			void Enqueue(IDialogue? node)
			{
				if (node != null && !visited.Contains(((Il2CppObjectBase)node).Pointer))
				{
					queue.Enqueue(node);
				}
			}
			void Root(IDialogue? node)
			{
				if (node != null)
				{
					roots.Add(NodeId(node));
					Enqueue(node);
				}
			}
		}

		private static object ReadGraph(Source source, WalkResult walk)
		{
			List<object> list = new List<object>();
			BackgroundNPCConv ambient = source.Ambient;
			if (ambient != null)
			{
				int num = ambient.textLines?.Count ?? 0;
				for (int i = 0; i < Math.Min(num, 1000); i++)
				{
					BGNPCLine val = ambient.textLines[i];
					string id = $"{source.Id}/line/{i}";
					string speaker = val.Speaker;
					LocObjRef<LocBackgroundDialogueLine> line = val.Line;
					object text;
					if (line == null)
					{
						text = null;
					}
					else
					{
						LocBackgroundDialogueLine obj = line.Obj;
						text = ((obj != null) ? ((LocString)obj).text : null);
					}
					list.Add(new
					{
						Id = id,
						StableId = false,
						Type = "ambient-line",
						Speaker = speaker,
						Text = (string)text,
						NextId = ((i + 1 < num) ? $"{source.Id}/line/{i + 1}" : null)
					});
				}
				return new
				{
					RootIds = ((num <= 0) ? Array.Empty<string>() : new string[1] { source.Id + "/line/0" }),
					NodeLimit = 1000,
					Truncated = (num > 1000),
					UnsupportedTypes = Array.Empty<string>(),
					Complete = (num <= 1000),
					Nodes = list
				};
			}
			foreach (IDialogue node in walk.Nodes)
			{
				DialogueWithChoices val2 = ((Il2CppObjectBase)node).TryCast<DialogueWithChoices>();
				ConditionDialogueNode val3 = ((Il2CppObjectBase)node).TryCast<ConditionDialogueNode>();
				ScriptingDialogueObj val4 = ((Il2CppObjectBase)node).TryCast<ScriptingDialogueObj>();
				List<object> list2 = new List<object>();
				if (((val2 != null) ? val2.choices : null) != null)
				{
					Enumerator<Wrapper<IChoice>> enumerator2 = val2.choices.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						IChoice? obj2 = Unwrap<IChoice>(enumerator2.Current);
						DialogueChoice val5 = ((obj2 != null) ? ((Il2CppObjectBase)obj2).TryCast<DialogueChoice>() : null);
						if (val5 != null)
						{
							string text2 = EmptyToNull(val5.ArticyGUID);
							list2.Add(new
							{
								Id = (text2 ?? $"runtime-choice:{((Il2CppObjectBase)val5).Pointer.ToInt64():x}"),
								StableId = (text2 != null),
								Text = TextVersions(val5.choiceText),
								NextId = NodeId(Unwrap<IDialogue>(val5.nextDialogue)),
								ConditionScript = val5.rawConditionScript,
								invertCondition = val5.invertCondition,
								HasCondition = (val5.choiceCondition != null)
							});
						}
					}
				}
				list.Add(new
				{
					Id = NodeId(node),
					StableId = !NodeId(node).StartsWith("runtime:", StringComparison.Ordinal),
					Type = NativeType((Il2CppObjectBase)(object)node),
					Name = (((val2 != null) ? val2.theName : null) ?? ((val3 != null) ? val3.theName : null) ?? ((val4 != null) ? val4.theName : null)),
					Speaker = (((Object)(object)((val2 != null) ? val2.speaker : null) == (Object)null) ? null : val2.speaker.articyTechnicalName),
					Text = TextVersions((val2 != null) ? val2.text : null),
					LegacyText = ((val2 != null) ? val2.dialogueText : null),
					NextId = NodeId(Unwrap<IDialogue>(((val2 != null) ? val2.nextDialogue : null) ?? ((val3 != null) ? val3.nextDialogue : null) ?? ((val4 != null) ? val4.nextDialogue : null))),
					FalseNextId = NodeId(Unwrap<IDialogue>((val3 != null) ? val3.nextDialogueOnFalse : null)),
					HasCondition = (val3 != null),
					Choices = list2,
					Actions = ReadActions(((val2 != null) ? val2.actionTriggers : null) ?? ((val3 != null) ? val3.actionTriggers : null) ?? ((val4 != null) ? val4.actionTriggers : null))
				});
			}
			return new
			{
				RootIds = walk.RootIds,
				NodeLimit = 1000,
				Truncated = walk.Truncated,
				UnsupportedTypes = walk.UnsupportedTypes,
				Complete = (!walk.Truncated && walk.UnsupportedTypes.Length == 0),
				Nodes = list
			};
		}

		private static object[] ReadActions(List<Wrapper<TriggeredAction>>? wrappers)
		{
			//IL_0094: 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)
			List<object> list = new List<object>();
			if (wrappers == null)
			{
				return list.ToArray();
			}
			Enumerator<Wrapper<TriggeredAction>> enumerator = wrappers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				TriggeredAction val = Unwrap<TriggeredAction>(enumerator.Current);
				if (val != null)
				{
					QuestEnder val2 = ((Il2CppObjectBase)val).TryCast<QuestEnder>();
					QuestAdder obj = ((Il2CppObjectBase)val).TryCast<QuestAdder>();
					Quest val3 = ((obj != null) ? obj.quest : null) ?? ((val2 != null) ? val2.quest : null);
					string name = ((MemberInfo)((Object)val).GetIl2CppType()).Name;
					object questId;
					if (val3 == null)
					{
						questId = null;
					}
					else
					{
						SerializableGuid guid = val3.guid;
						questId = ((guid != null) ? guid.guid : null);
					}
					list.Add(new
					{
						Type = name,
						QuestId = (string)questId,
						QuestArticyId = ((val3 != null) ? val3.ArticyQuestGuid : null),
						QuestState = ((val2 != null) ? ((object)val2.state/*cast due to .constrained prefix*/).ToString() : null)
					});
				}
			}
			return list.ToArray();
		}

		private static string NativeType(Il2CppObjectBase value)
		{
			return value.Cast<Object>().GetIl2CppType().FullName;
		}

		private static T? Unwrap<T>(Wrapper<T>? wrapper) where T : Il2CppObjectBase
		{
			object obj;
			if (wrapper != null)
			{
				obj = wrapper.plainObj;
				if (obj == null)
				{
					Object uObj = wrapper.uObj;
					if (uObj == null)
					{
						return default(T);
					}
					return ((Il2CppObjectBase)uObj).TryCast<T>();
				}
			}
			else
			{
				obj = default(T);
			}
			return (T?)obj;
		}

		private static string? TreeId(IDialogueTree? tree)
		{
			object obj;
			if (tree == null)
			{
				obj = null;
			}
			else
			{
				DialogueTree obj2 = ((Il2CppObjectBase)tree).TryCast<DialogueTree>();
				obj = ((obj2 != null) ? obj2.articyGuid : null);
			}
			if (obj == null)
			{
				if (tree == null)
				{
					obj = null;
				}
				else
				{
					LogicOnlyStoryTree obj3 = ((Il2CppObjectBase)tree).TryCast<LogicOnlyStoryTree>();
					obj = ((obj3 != null) ? obj3.articyGuid : null);
				}
			}
			return EmptyToNull((string?)obj);
		}

		private static string? NodeId(IDialogue? node)
		{
			object obj5;
			if (node != null)
			{
				DialogueWithChoices obj = ((Il2CppObjectBase)node).TryCast<DialogueWithChoices>();
				object obj2 = ((obj != null) ? obj.articyGuid : null);
				if (obj2 == null)
				{
					ConditionDialogueNode obj3 = ((Il2CppObjectBase)node).TryCast<ConditionDialogueNode>();
					obj2 = ((obj3 != null) ? obj3.articyGuid : null);
					if (obj2 == null)
					{
						ScriptingDialogueObj obj4 = ((Il2CppObjectBase)node).TryCast<ScriptingDialogueObj>();
						obj2 = ((obj4 != null) ? obj4.articyGuid : null);
					}
				}
				obj5 = EmptyToNull((string?)obj2);
				if (obj5 == null)
				{
					return $"runtime:{((Il2CppObjectBase)node).Pointer.ToInt64():x}";
				}
			}
			else
			{
				obj5 = null;
			}
			return (string?)obj5;
		}

		private static object? TextVersions(PronounVersionsString? text)
		{
			if (text != null)
			{
				return new
				{
					He = text.TextHeVersion,
					She = text.TextSheVersion,
					They = text.TextTheyVersion
				};
			}
			return null;
		}

		private static string? EmptyToNull(string? value)
		{
			if (!string.IsNullOrWhiteSpace(value))
			{
				return value;
			}
			return null;
		}

		private static string[] Names(string? name)
		{
			string text = EmptyToNull(name);
			if (text == null)
			{
				return Array.Empty<string>();
			}
			return new string[1] { text };
		}

		private static bool Same(string? left, string? right)
		{
			if (left != null && right != null)
			{
				return string.Equals(left, right, StringComparison.OrdinalIgnoreCase);
			}
			return false;
		}

		private static bool Contains(string? text, string value)
		{
			return text?.Contains(value, StringComparison.OrdinalIgnoreCase) ?? false;
		}
	}
	internal sealed record DialogueQuery(string? Search, string? Id, string? Speaker, string? QuestId, string Kind, int Offset, int Limit, bool IncludeNodes)
	{
		public static DialogueQuery Parse(NameValueCollection query)
		{
			string[] allKeys = query.AllKeys;
			bool flag;
			foreach (string text in allKeys)
			{
				switch (text)
				{
				case "offset":
				case "search":
				case "questId":
				case "speaker":
				case "id":
				case "kind":
				case "limit":
				case "includeNodes":
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (!flag)
				{
					throw new ApiFailure(400, "Unknown dialogue filter: " + text);
				}
				string[]? values = query.GetValues(text);
				if (values == null || values.Length != 1)
				{
					throw new ApiFailure(400, "Supply " + text + " only once.");
				}
			}
			bool result = false;
			string text2 = query["includeNodes"];
			if (text2 != null && !bool.TryParse(text2, out result))
			{
				throw new ApiFailure(400, "includeNodes must be true or false.");
			}
			string text3 = query["kind"] ?? "all";
			switch (text3)
			{
			case "all":
			case "story":
			case "standalone":
			case "ambient":
				flag = true;
				break;
			default:
				flag = false;
				break;
			}
			if (!flag)
			{
				throw new ApiFailure(400, "kind must be all, story, standalone, or ambient.");
			}
			int maximumValue = (result ? 10 : 100);
			return new DialogueQuery(Text("search"), Text("id"), Text("speaker"), Text("questId"), text3, Number("offset", 0, 0, int.MaxValue), Number("limit", result ? 5 : 25, 1, maximumValue), result);
			int Number(string key, int fallback, int minimum, int num)
			{
				string text4 = query[key];
				if (text4 == null)
				{
					return fallback;
				}
				if (!int.TryParse(text4, NumberStyles.None, CultureInfo.InvariantCulture, out var result2) || result2 < minimum || result2 > num)
				{
					throw new ApiFailure(400, $"{key} must be between {minimum} and {num}.");
				}
				return result2;
			}
			string? Text(string key)
			{
				string text4 = query[key];
				if (text4 == null)
				{
					return null;
				}
				text4 = text4.Trim();
				int length = text4.Length;
				if ((length > 256 || length == 0) ? true : false)
				{
					throw new ApiFailure(400, key + " must contain 1–256 characters.");
				}
				return text4;
			}
		}
	}
	internal static class DialogueSnapshot
	{
		private sealed record CurrentDialogue(string? ArticyLineId, string? ArticyTreeId, string? SpeakerName, string? SpeakerTechnicalName, string? CharacterTechnicalName, string? Text, int? MaxVisibleCharacters, bool IsMessage, int ChoiceCount, DialogueChoice[] Choices);

		private sealed record DialogueChoice(int Index, string? ArticyId, string? Text, bool ConditionEnabled, bool Visible, string? DisplayedText, bool Interactable, int? ButtonInstanceId);

		private sealed record OverheadBubble(int CharacterInstanceId, string ObjectName, string Scene, string CharacterType, string? SpeakerTechnicalName, string Text, bool IsConversation, bool IsPlayerDialogue, Point Position);

		public static object Capture(Action<string> log)
		{
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0164: 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_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			int skipped = 0;
			DialogueUI instance = DialogueUI._instance;
			bool flag = (Object)(object)instance != (Object)null && IsLoaded(((Component)instance).gameObject);
			bool flag2 = flag && ((UIWindow)instance)._isOpen;
			bool isVisible = flag2 && ((UIPanel)instance)._isVisible && IsShown((Component)(object)instance);
			CurrentDialogue current = null;
			if (flag2 && instance._currentStepData != null)
			{
				try
				{
					current = ReadCurrent(instance, log, ref skipped);
				}
				catch (Exception ex)
				{
					skipped++;
					log("Could not inspect current player dialogue: " + ex.Message);
				}
			}
			List<OverheadBubble> list = new List<OverheadBubble>();
			HashSet<Character> instances = Character.instances;
			if (instances != null)
			{
				Enumerator<Character> enumerator = instances.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Character current2 = enumerator.Current;
					try
					{
						if ((Object)(object)current2 == (Object)null || !IsLoaded(((Component)current2).gameObject) || !((Component)current2).gameObject.activeInHierarchy)
						{
							continue;
						}
						CharacterNameDisplay nameDisplay = current2.NameDisplay;
						CharacterNameDisplayUi val = (((Object)(object)nameDisplay == (Object)null) ? null : nameDisplay._uiDialogueInstance);
						if (!((Object)(object)val == (Object)null) && IsShown((Component)(object)val) && !((Object)(object)val.nameText == (Object)null))
						{
							string text = ((TMP_Text)val.nameText).text;
							if (!string.IsNullOrWhiteSpace(text))
							{
								CharacterCommunication communication = current2.Communication;
								Vector3 position = ((Component)current2).transform.position;
								int instanceID = ((Object)current2).GetInstanceID();
								string name = ((Object)current2).name;
								Scene scene = ((Component)current2).gameObject.scene;
								list.Add(new OverheadBubble(instanceID, name, ((Scene)(ref scene)).name, ((object)current2.Type/*cast due to .constrained prefix*/).ToString(), ((Object)(object)nameDisplay.person == (Object)null) ? null : nameDisplay.person.articyTechnicalName, text, (Object)(object)communication != (Object)null && communication._IsConversation_k__BackingField, (Object)(object)communication != (Object)null && communication.IsPlayerDialogue, new Point(position.x, position.y, position.z)));
							}
						}
					}
					catch (Exception ex2)
					{
						skipped++;
						log("Could not inspect an overhead dialogue bubble: " + ex2.Message);
					}
				}
			}
			return new
			{
				CapturedAt = DateTimeOffset.Now,
				Scope = "Current player dialogue display and active overhead dialogue bubbles in loaded scenes; no story graph traversal or condition evaluation",
				Available = (flag || instances != null),
				Skipped = skipped,
				PlayerDialogue = new
				{
					UiAvailable = flag,
					IsOpen = flag2,
					IsVisible = isVisible,
					IsPhoneCall = (flag2 && instance._isInCallDialogue),
					Current = current
				},
				OverheadCount = list.Count,
				OverheadBubbles = list.OrderBy((OverheadBubble bubble) => bubble.CharacterInstanceId).ToArray()
			};
		}

		private static CurrentDialogue ReadCurrent(DialogueUI ui, Action<string> log, ref int skipped)
		{
			DialogueStepDisplayData currentStepData = ui._currentStepData;
			IDialogue dialogue = currentStepData.Dialogue;
			DialogueWithChoices val = ((dialogue != null) ? ((Il2CppObjectBase)dialogue).TryCast<DialogueWithChoices>() : null);
			IDialogueTree dialogueTree = currentStepData.DialogueTree;
			DialogueTree val2 = ((dialogueTree != null) ? ((Il2CppObjectBase)dialogueTree).TryCast<DialogueTree>() : null);
			List<DialogueChoice> list = new List<DialogueChoice>();
			if (currentStepData.Choices != null)
			{
				for (int i = 0; i < currentStepData.Choices.Count; i++)
				{
					try
					{
						Choice val3 = currentStepData.Choices[i];
						if (val3 == null)
						{
							continue;
						}
						DialogueChoiceUI val4 = null;
						if (ui._choiceInstances != null)
						{
							Enumerator<DialogueChoiceUI> enumerator = ui._choiceInstances.GetEnumerator();
							while (enumerator.MoveNext())
							{
								DialogueChoiceUI current = enumerator.Current;
								if ((Object)(object)current != (Object)null && current._choiceIndex == i && IsShown((Component)(object)current))
								{
									val4 = current;
									break;
								}
							}
						}
						Button val5 = (((Object)(object)val4 == (Object)null) ? null : val4.button);
						list.Add(new DialogueChoice(i, val3.articyID, val3.Text, val3.Enabled, (Object)(object)val4 != (Object)null, ((Object)(object)val4 == (Object)null || (Object)(object)val4.choiceText == (Object)null) ? null : ((TMP_Text)val4.choiceText).text, (Object)(object)val5 != (Object)null && ((Behaviour)val5).isActiveAndEnabled && ((Selectable)val5).IsInteractable(), ((Object)(object)val5 == (Object)null) ? ((int?)null) : new int?(((Object)val5).GetInstanceID())));
					}
					catch (Exception ex)
					{
						skipped++;
						log($"Could not inspect dialogue choice {i}: {ex.Message}");
					}
				}
			}
			return new CurrentDialogue((val != null) ? val.articyGuid : null, (val2 != null) ? val2.articyGuid : null, ((Object)(object)ui.speakerName == (Object)null) ? null : ((TMP_Text)ui.speakerName).text, ((Object)(object)ui._currentSpeaker == (Object)null) ? null : ui._currentSpeaker.articyTechnicalName, ((Object)(object)currentStepData.Character == (Object)null) ? null : currentStepData.Character.articyTechnicalName, ((Object)(object)ui.contentText == (Object)null) ? null : ((TMP_Text)ui.contentText).text, ((Object)(object)ui.contentText == (Object)null) ? ((int?)null) : new int?(((TMP_Text)ui.contentText).maxVisibleCharacters), currentStepData.IsMessage, list.Count, list.ToArray());
		}

		private static bool IsLoaded(GameObject obj)
		{
			//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)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Scene scene = obj.scene;
			if (((Scene)(ref scene)).IsValid())
			{
				scene = obj.scene;
				return ((Scene)(ref scene)).isLoaded;
			}
			return false;
		}

		private static bool IsShown(Component component)
		{
			if (!component.gameObject.activeInHierarchy)
			{
				return false;
			}
			foreach (CanvasGroup item in component.GetComponentsInParent<CanvasGroup>())
			{
				if (((Behaviour)item).enabled && item.alpha <= 0.01f)
				{
					return false;
				}
			}
			Canvas componentInParent = component.GetComponentInParent<Canvas>();
			if (!((Object)(object)componentInParent == (Object)null))
			{
				return ((Behaviour)componentInParent).isActiveAndEnabled;
			}
			return true;
		}
	}
	internal static class ItemSnapshot
	{
		private sealed record ItemRow(int InstanceId, string? Guid, string? ArticyGuid, string AssetName, string? DisplayName, string? Description, float? BasePriceRaw, bool IsPlayerStorable, bool IsUseable, bool IsEquippable, bool IsIngredient, bool IsFurniture, bool IsFish);

		private sealed record OwnedItemRow(int ItemInstanceId, string? ItemGuid, string AssetName, long Quantity, int StackCount);

		private sealed record PlayerInventoryRow(int InstanceId, string ObjectName, string Scene, bool Active, bool Initialized, int MoneyRaw, int DistinctItemCount, long TotalQuantity, OwnedItemRow[] Items);

		public static object Capture(Action<string> log)
		{
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			int num = 0;
			Il2CppReferenceArray<Object> val = Resources.FindObjectsOfTypeAll(Il2CppType.Of<ItemType>());
			List<ItemRow> list = new List<ItemRow>();
			foreach (Object item in (Il2CppArrayBase<Object>)(object)val)
			{
				try
				{
					ItemType val2 = ((Il2CppObjectBase)item).Cast<ItemType>();
					if (!((Object)(object)val2 == (Object)null))
					{
						LocItemPlain val3 = val2.locObjRef?.Obj;
						int instanceID = ((Object)val2).GetInstanceID();
						SerializableGuid guid = val2.guid;
						list.Add(new ItemRow(instanceID, (guid != null) ? guid.guid : null, val2.ArticyGuid, ((Object)val2).name, ((val3 != null) ? val3.displayName : null) ?? val2.Name, (val3 != null) ? val3.description : null, float.IsFinite(val2.basePrice) ? new float?(val2.basePrice) : ((float?)null), val2.isPlayerStorable, val2.isUseable, val2.isEquippable, val2.isIngredient, val2.isFurniture, val2.isFish));
					}
				}
				catch (Exception ex)
				{
					num++;
					log("Could not inspect loaded item definition: " + ex.Message);
				}
			}
			List<PlayerInventoryRow> list2 = new List<PlayerInventoryRow>();
			foreach (Object item2 in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<PlayerInventory>()))
			{
				try
				{
					PlayerInventory val4 = ((Il2CppObjectBase)item2).Cast<PlayerInventory>();
					if ((Object)(object)val4 == (Object)null)
					{
						continue;
					}
					GameObject gameObject = ((Component)val4).gameObject;
					Scene scene = gameObject.scene;
					if (!((Scene)(ref scene)).IsValid())
					{
						continue;
					}
					scene = gameObject.scene;
					if (!((Scene)(ref scene)).isLoaded)
					{
						continue;
					}
					ItemContainer items = val4._items;
					LinkedList<ItemStack> val5 = ((items == null) ? null : items._items);
					bool initialized = val5 != null;
					Dictionary<int, OwnedItemRow> dictionary = new Dictionary<int, OwnedItemRow>();
					if (val5 != null)
					{
						for (LinkedListNode<ItemStack> val6 = val5.First; val6 != null; val6 = val6.Next)
						{
							try
							{
								ItemStack value = val6.Value;
								ItemType val7 = ((value != null) ? value._type : null);
								List<ItemInstanceData> val8 = ((value != null) ? value._instanceData : null);
								if ((Object)(object)val7 == (Object)null || val8 == null)
								{
									throw new InvalidOperationException("Inventory stack has no item type or instance collection.");
								}
								int instanceID2 = ((Object)val7).GetInstanceID();
								if (dictionary.TryGetValue(instanceID2, out var value2))
								{
									dictionary[instanceID2] = value2 with
									{
										Quantity = value2.Quantity + val8.Count,
										StackCount = value2.StackCount + 1
									};
								}
								else
								{
									SerializableGuid guid2 = val7.guid;
									dictionary.Add(instanceID2, new OwnedItemRow(instanceID2, (guid2 != null) ? guid2.guid : null, ((Object)val7).name, val8.Count, 1));
								}
							}
							catch (Exception ex2)
							{
								num++;
								log("Could not inspect player inventory stack: " + ex2.Message);
							}
						}
					}
					OwnedItemRow[] array = dictionary.Values.OrderBy<OwnedItemRow, string>((OwnedItemRow item) => item.AssetName, StringComparer.Ordinal).ThenBy((OwnedItemRow item) => item.ItemInstanceId).ToArray();
					int instanceID3 = ((Object)val4).GetInstanceID();
					string name = ((Object)gameObject).name;
					scene = gameObject.scene;
					list2.Add(new PlayerInventoryRow(instanceID3, name, ((Scene)(ref scene)).name, gameObject.activeInHierarchy, initialized, val4._money, array.Length, array.Sum((OwnedItemRow item) => item.Quantity), array));
				}
				catch (Exception ex3)
				{
					num++;
					log("Could not inspect player inventory: " + ex3.Message);
				}
			}
			return new
			{
				CapturedAt = DateTimeOffset.Now,
				Scope = "Currently loaded ItemType assets; not an exhaustive game catalog. Display text uses the game's current localization and may be unavailable.",
				Available = (((Il2CppArrayBase<Object>)(object)val).Length > 0),
				Skipped = num,
				Count = list.Count,
				Items = list.OrderBy<ItemRow, string>((ItemRow item) => item.AssetName, StringComparer.Ordinal).ThenBy((ItemRow item) => item.InstanceId).ToArray(),
				InventoryScope = "Existing PlayerInventory components in loaded scenes, including inactive components; excludes venue, shop, and other storage containers. MoneyRaw and BasePriceRaw preserve the native stored units.",
				InventoryAvailable = list2.Any((PlayerInventoryRow inventory) => inventory.Initialized),
				InventoryCount = list2.Count,
				PlayerInventories = list2.OrderBy((PlayerInventoryRow inventory) => inventory.InstanceId).ToArray()
			};
		}
	}
	public sealed record NpcFacts(int InstanceId, string ObjectName, string Scene, float X, float Y, float Z, string? PersonGuid, string? PersonAsset, string? TechnicalName, bool HasNameDisplay, bool HasHead, bool HasStory, bool Vendor, bool InConversation, bool HasDialogueInteraction, bool Working = false)
	{
		public string PrefabKey => CrowdEligibility.PrefabKey(ObjectName);
	}
	public static class CrowdEligibility
	{
		public static string? Rejection(bool hasNameDisplay, bool hasStory, bool vendor, bool inConversation, bool hasHead, bool working = false)
		{
			if (vendor)
			{
				return "vendor";
			}
			if (working)
			{
				return "working";
			}
			if (!hasNameDisplay)
			{
				return "no-name-display";
			}
			if (hasStory)
			{
				return "has-story";
			}
			if (inConversation)
			{
				return "in-conversation";
			}
			if (!hasHead)
			{
				return "no-head";
			}
			return null;
		}

		public static string? Rejection(NpcFacts npc)
		{
			return Rejection(npc.HasNameDisplay, npc.HasStory, npc.Vendor, npc.InConversation, npc.HasHead, npc.Working);
		}

		public static string? QuestRoleRejection(NpcFacts npc)
		{
			return Rejection(npc.HasNameDisplay, npc.HasStory, npc.Vendor, npc.InConversation, npc.HasHead);
		}

		public static string PrefabKey(string objectName)
		{
			string text = objectName.Trim();
			while (text.EndsWith("(Clone)", StringComparison.Ordinal))
			{
				string text2 = text;
				int length = "(Clone)".Length;
				text = text2.Substring(0, text2.Length - length).TrimEnd();
			}
			return text;
		}
	}
	internal static class NpcReader
	{
		public static NpcSnapshot Capture(bool includeInactive, Action<string> log)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0223: Unknown result type (might be due to invalid IL or missing references)
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: 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: 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_011c: 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)
			List<NpcRow> list = new List<NpcRow>();
			Camera main = Camera.main;
			int num = 0;
			foreach (Object item in (Il2CppArrayBase<Object>)(object)Resources.FindObjectsOfTypeAll(Il2CppType.Of<Character>()))
			{
				Character val = ((Il2CppObjectBase)item).Cast<Character>();
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				GameObject gameObject = ((Component)val).gameObject;
				Scene scene = gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && ((Scene)(ref scene)).isLoaded && (includeInactive || gameObject.activeInHierarchy))
				{
					try
					{
						Vector3 position = ((Component)val).transform.position;
						CharacterCommunication communication = val.Communication;
						Transform val2 = (((Object)(object)communication == (Object)null) ? null : communication.Head);
						list.Add(new NpcRow(((Object)val).GetInstanceID(), ((Object)gameObject).name, ((Scene)(ref scene)).name, ((Scene)(ref scene)).handle, HierarchyPath(((Component)val).transform), ((object)val.Type/*cast due to .constrained prefix*/).ToString(), gameObject.activeInHierarchy, ((Behaviour)val).enabled, new Point(position.x, position.y, position.z), ((Object)(object)main == (Object)null) ? ((float?)null) : new float?(Vector3.Distance(((Component)main).transform.position, position)), (Object)(object)val.DialogueInteraction != (Object)null, ((Object)(object)val2 == (Object)null) ? null : HierarchyPath(val2)));
					}
					catch (Exception ex)
					{
						num++;
						log("Could not inspect NPC " + ((Object)gameObject).name + ": " + ex.Message);
					}
				}
			}
			NpcRow[] array = (from row in list
				orderby row.DistanceFromCamera ?? float.MaxValue, row.Scene, row.InstanceId
				select row).ToArray();
			DateTimeOffset now = DateTimeOffset.Now;
			Scene activeScene = SceneManager.GetActiveScene();
			return new NpcSnapshot(now, ((Scene)(ref activeScene)).name, "Nivalis.Character objects in all loaded scenes, including persistent objects; prefab assets excluded", includeInactive, num, array.Length, array);
		}

		private static string HierarchyPath(Transform transform)
		{
			List<string> list = new List<string>();
			Transform val = transform;
			while ((Object)(object)val != (Object)null)
			{
				list.Add($"{((Object)val).name}[{val.GetSiblingIndex()}]");
				val = val.parent;
			}
			list.Reverse();
			return string.Join("/", list);
		}
	}
	public sealed record Point(float X, float Y, float Z);
	public sealed record NpcRow(int InstanceId, string ObjectName, string Scene, int SceneHandle, string HierarchyPath, string CharacterType, bool Active, bool ComponentEnabled, Point Position, float? DistanceFromCamera, bool HasDialogueInteraction, string? HeadTransformPath);
	public sealed record NpcSnapshot(DateTimeOffset CapturedAt, string ActiveScene, string Scope, bool IncludeInactive, int Skipped, int Count, NpcRow[] Npcs);
	internal sealed class ModQuestCatalog
	{
		private const float StaleSeconds = 5f;

		private readonly QuestNpcResolver resolver = new QuestNpcResolver();

		private int scene;

		private static string Folder => DeployedQuest.Folder(ToolkitPaths.Data);

		public object Capture(Action<string> log)
		{
			//IL_000d: 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)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			Scene activeScene = SceneManager.GetActiveScene();
			int handle = ((Scene)(ref activeScene)).handle;
			if (handle != scene)
			{
				resolver.Clear();
				scene = handle;
			}
			int skipped;
			List<NpcFacts> loaded = QuestCandidates.Read(log, out skipped);
			JsonDocument runtime = Runtime();
			try
			{
				object[] array = (from quest in DeployedQuest.LoadAll(Folder, log)
					select Describe(quest, loaded, runtime?.RootElement)).ToArray();
				DateTimeOffset now = DateTimeOffset.Now;
				activeScene = SceneManager.GetActiveScene();
				return new
				{
					CapturedAt = now,
					ActiveScene = ((Scene)(ref activeScene)).name,
					Folder = Folder,
					FolderExists = Directory.Exists(Folder),
					Scope = "Spec = authored input. Roles = this endpoint's live resolution. Runtime = Click-to-Hello session playback state.",
					SkippedNpcs = skipped,
					Count = array.Length,
					Runtime = (object)((runtime == null) ? null : new
					{
						Running = true,
						Epoch = Get(runtime.RootElement, "Epoch"),
						InGameplay = Get(runtime.RootElement, "InGameplay"),
						Suppressed = Get(runtime.RootElement, "Suppressed"),
						Persistence = Get(runtime.RootElement, "Persistence"),
						LastEvent = Get(runtime.RootElement, "LastEvent"),
						LastCommand = Get(runtime.RootElement, "LastCommand"),
						Menu = Get(runtime.RootElement, "Menu"),
						Bubble = Get(runtime.RootElement, "Bubble"),
						Marker = Get(runtime.RootElement, "Marker"),
						Hold = Get(runtime.RootElement, "Hold")
					}),
					Quests = array
				};
			}
			finally
			{
				if (runtime != null)
				{
					((IDisposable)runtime).Dispose();
				}
			}
		}

		private object Describe(DeployedQuest quest, IReadOnlyList<NpcFacts> loaded, JsonElement? runtime)
		{
			QuestSpec spec = quest.Spec;
			Dictionary<string, NpcResolution> dictionary = ((!quest.Valid) ? null : spec.Npcs.ToDictionary<KeyValuePair<string, QuestNpc>, string, NpcResolution>((KeyValuePair<string, QuestNpc> pair) => pair.Key, (KeyValuePair<string, QuestNpc> pair) => resolver.Resolve(spec.Id + "/" + pair.Key, pair.Value.Identity, loaded)));
			JsonElement? runtime2 = null;
			ref JsonElement? reference = ref runtime;
			if (reference.HasValue && reference.GetValueOrDefault().TryGetProperty("Quests", out var value))
			{
				foreach (JsonElement item in value.EnumerateArray())
				{
					if (item.TryGetProperty("Id", out var value2) && value2.ValueKind == JsonValueKind.String && value2.GetString() == spec?.Id)
					{
						runtime2 = item.Clone();
					}
				}
			}
			Dictionary<string, string> capabilities = (spec?.Capabilities ?? Array.Empty<string>()).Distinct().ToDictionary((string c) => c, (string c) => Capability(c, runtime.HasValue));
			string text = ((!quest.Valid) ? "Spec is invalid; see Errors." : ((!runtime.HasValue) ? "Playback runtime is not running: enable Click-to-Hello in Settings → Modules (or it is loading/suspended)." : ((!runtime2.HasValue) ? "Playback runtime has not loaded this spec yet; retry in a few seconds." : (runtime2.Value.GetProperty("Playable").GetBoolean() ? null : Get(runtime2.Value, "Reason")?.ToString()))));
			return new
			{
				File = quest.File,
				Id = spec?.Id,
				Title = spec?.Title,
				Valid = quest.Valid,
				Errors = quest.Errors,
				Roles = dictionary,
				AllRolesResolved = (dictionary?.Values.All((NpcResolution r) => r.Status == "resolved") ?? false),
				Capabilities = capabilities,
				Playable = (quest.Valid && text == null),
				PlayabilityReason = text,
				Runtime = runtime2
			};
		}

		private static string Capability(string capability, bool running)
		{
			return capability switch
			{
				"dialogue-menu" => running ? "implemented: native dialogue menu with mod text (Click-to-Hello)" : "unavailable: Click-to-Hello is not running", 
				"session-progress" => running ? "implemented: session-only playback (Click-to-Hello)" : "unavailable: Click-to-Hello is not running", 
				"mod-progress" => "gated: no verified loaded-save identity (Quests/PHASE0.md G2)", 
				_ => "rejected", 
			};
		}

		public static object Send(NameValueCollection query)
		{
			string error;
			QuestCommand questCommand = QuestCommand.Parse(query, out error) ?? throw new ApiFailure(400, error);
			using (JsonDocument jsonDocument = Runtime())
			{
				if (jsonDocument == null)
				{
					throw new ApiFailure(409, "Playback runtime is not running: enable Click-to-Hello.");
				}
			}
			if (!QuestRuntimeChannel.TrySend(questCommand.ToLine()))
			{
				throw new ApiFailure(409, "Another quest action is still pending; retry.");
			}
			return new
			{
				Queued = true,
				Nonce = questCommand.Nonce,
				Action = questCommand.Action,
				Quest = questCommand.Quest,
				Role = questCommand.Role,
				Check = "GET /mod-quests: Runtime.LastCommand with this Nonce, then the quest's Runtime."
			};
		}

		private static JsonDocument? Runtime()
		{
			string text = QuestRuntimeChannel.ReadStatus();
			if (text == null)
			{
				return null;
			}
			JsonDocument jsonDocument = JsonDocument.Parse(text);
			if (jsonDocument.RootElement.TryGetProperty("PublishedAt", out var value) && Time.realtimeSinceStartup - value.GetSingle() <= 5f)
			{
				return jsonDocument;
			}
			jsonDocument.Dispose();
			return null;
		}

		private static object? Get(JsonElement element, string name)
		{
			if (!element.TryGetProperty(name, out var value) || value.ValueKind == JsonValueKind.Null)
			{
				return null;
			}
			return value.Clone();
		}
	}
	internal static class QuestCandidates
	{
		public static List<NpcFacts> Read(Action<string> log, out int skipped)
		{
			//IL_003f: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			List<NpcFacts> list = new List<NpcFacts>();
			skipped = 0;
			if (Character.instances == null)
			{
				return list;
			}
			Enumerator<Character> enumerator = Character.instances.GetEnumerator();
			while (enumerator.MoveNext())
			{
				Character current = enumerator.Current;
				if ((Object)(object)current == (Object)null)
				{
					continue;
				}
				GameObject gameObject = ((Component)current).gameObject;
				if (!gameObject.activeInHierarchy)
				{
					continue;
				}
				Scene scene = gameObject.scene;
				if (!((Scene)(ref scene)).IsValid())
				{
					continue;
				}
				scene = gameObject.scene;
				if (((Scene)(ref scene)).isLoaded)
				{
					try
					{
						list.Add(Facts(current));
					}
					catch (Exception ex)
					{
						skipped++;
						log("Could not read quest facts for " + ((Object)gameObject).name + ": " + ex.Message);
					}
				}
			}
			return list;
		}

		public static object Capture(Action<string> log)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: 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_00c2: Unknown result type (might be due to invalid IL or missing references)
			int skipped;
			List<NpcFacts> source = Read(log, out skipped);
			Vector3? player = PlayerPosition();
			var array = (from npc in source
				select new
				{
					InstanceId = npc.InstanceId,
					ObjectName = npc.ObjectName,
					PrefabKey = npc.PrefabKey,
					Scene = npc.Scene,
					Position = new QuestPoint(npc.X, npc.Y, npc.Z),
					DistanceFromPlayer = ((!player.HasValue) ? ((float?)null) : new float?(Vector3.Distance(player.Value, new Vector3(npc.X, npc.Y, npc.Z)))),
					Identity = ((npc.PersonGuid != null) ? new
					{
						Kind = "person",
						PersonGuid = npc.PersonGuid,
						Prefab = (string)null,
						Scene = (string)null
					} : new
					{
						Kind = "selector",
						PersonGuid = (string)null,
						Prefab = npc.PrefabKey,
						Scene = npc.Scene
					}),
					PersonAsset = npc.PersonAsset,
					TechnicalName = npc.TechnicalName,
					HasStory = npc.HasStory,
					Vendor = npc.Vendor,
					InConversation = npc.InConversation,
					HasDialogueInteraction = npc.HasDialogueInteraction,
					Working = npc.Working,
					Eligible = (CrowdEligibility.QuestRoleRejection(npc) == null),
					Rejection = CrowdEligibility.QuestRoleRejection(npc)
				} into row
				orderby row.DistanceFromPlayer ?? float.MaxValue, row.InstanceId
				select row).ToArray();
			DateTimeOffset now = DateTimeOffset.Now;
			Scene activeScene = SceneManager.GetActiveScene();
			return new
			{
				CapturedAt = now,
				ActiveScene = ((Scene)(ref activeScene)).name,
				Scope = "Active Nivalis.Character objects in loaded scenes. InstanceId is session-local diagnostics only; persist Identity. Eligibility uses the Click-to-Hello crowd rule.",
				PlayerPosition = ((!player.HasValue) ? null : new QuestPoint(player.Value.x, player.Value.y, player.Value.z)),
				Skipped = skipped,
				Count = array.Length,
				EligibleCount = array.Count(row => row.Eligible),
				PersonCount = array.Count(row => row.Identity.Kind == "person"),
				Npcs = array
			};
		}

		private static NpcFacts Facts(Character npc)
		{
			//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_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_0066: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			CharacterNameDisplay nameDisplay = npc.NameDisplay;
			Person val = (((Object)(object)nameDisplay == (Object)null) ? null : nameDisplay.person);
			CharacterCommunication communication = npc.Communication;
			string text = (((Object)(object)val == (Object)null) ? null : val.Guid);
			Vector3 position = ((Component)npc).transform.position;
			int instanceID = ((Object)npc).GetInstanceID();
			string name = ((Object)((Component)npc).gameObject).name;
			Scene scene = ((Component)npc).gameObject.scene;
			return new NpcFacts(instanceID, name, ((Scene)(ref scene)).name, position.x, position.y, position.z, string.IsNullOrWhiteSpace(text) ? null : text, ((Object)(object)val == (Object)null) ? null : ((Object)val).name, ((Object)(object)val == (Object)null) ? null : val.articyTechnicalName, (Object)(object)nameDisplay != (Object)null, (Object)(object)communication != (Object)null && (Object)(object)communication.Head != (Object)null, (Object)(object)nameDisplay != (Object)null && nameDisplay.hasStory, (Object)(object)npc.Vendor != (Object)null || (Object)(object)npc.PooledVendor != (Object)null, (Object)(object)communication != (Object)null && (communication.IsConversation || communication.IsPlayerDialogue), (Object)(object)npc.DialogueInteraction != (Object)null, (Object)(object)nameDisplay != (Object)null && nameDisplay.IsWorking());
		}

		internal static Vector3? PlayerPosition()
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			PlayerManager val = default(PlayerManager);
			if (!Singleton<PlayerManager>.InstanceExist(ref val))
			{
				return null;
			}
			Player localPlayer = val.LocalPlayer;
			PlayerCharacter val2 = ((localPlayer != null) ? localPlayer.Character : null);
			if (!((Object)(object)val2 == (Object)null))
			{
				return ((Component)val2).transform.position;
			}
			return null;
		}
	}
	public sealed record DialoguePage(string Text, IReadOnlyList<string> Choices);
	public enum DialogueSignal
	{
		None,
		Picked,
		Closed
	}
	public readonly record struct DialogueInput(DialogueSignal Signal, int Choice = -1);
	public interface IDialoguePresenter
	{
		bool Rendered { get; }

		object? Diagnostics => null;

		string? Unavailable();

		bool Show(object? speaker, DialoguePage page);

		DialogueInput Poll();

		void Close();
	}
	public interface ISpeakerHold : IDisposable
	{
		bool Hold(object? speaker);

		void Speak(string line);

		void Release();

		void Tick();

		object? Describe();
	}
	public sealed class NoSpeakerHold : ISpeakerHold, IDisposable
	{
		public static readonly NoSpeakerHold Instance = new NoSpeakerHold();

		public bool Hold(object? speaker)
		{
			return false;
		}

		public void Speak(string line)
		{
		}

		public void Release()
		{
		}

		public void Tick()
		{
		}

		public object? Describe()
		{
			return null;
		}

		public void Dispose()
		{
		}
	}
	public sealed class QuestConversationRunner
	{
		private readonly IDialoguePresenter presenter;

		private readonly Func<QuestConversation, string> finish;

		private readonly ISpeakerHold hold;

		private object? speaker;

		private int spokenLine = -1;

		public QuestConversation? Active { get; private set; }

		public int Line { get; private set; }

		public bool Open => Active != null;

		public QuestConversationRunner(IDialoguePresenter presenter, Func<QuestConversation, string> finish, ISpeakerHold? hold = null)
		{
			this.presenter = presenter;
			this.finish = finish;
			this.hold = hold ?? NoSpeakerHold.Instance;
		}

		public string? Start(QuestConversation conversation, object? speaker)
		{
			if (Active != null)
			{
				return "conversation-open";
			}
			if (conversation.Lines.Count == 0)
			{
				return conversation.Kind;
			}
			string text = presenter.Unavailable();
			if (text != null)
			{
				return text;
			}
			if (!presenter.Show(speaker, Page(conversation, 0)))
			{
				presenter.Close();
				return "menu-not-shown";
			}
			Active = conversation;
			this.speaker = speaker;
			Line = 0;
			spokenLine = -1;
			hold.Hold(speaker);
			return null;
		}

		public string? Update()
		{
			hold.Tick();
			QuestConversation active = Active;
			if ((object)active == null)
			{
				return null;
			}
			DialogueInput dialogueInput = presenter.Poll();
			if (dialogueInput.Signal == DialogueSignal.Closed)
			{
				Stop(close: false);
				return "interrupted";
			}
			SpeakOnceRendered(active);
			if (dialogueInput.Signal == DialogueSignal.None)
			{
				return null;
			}
			if (!presenter.Rendered)
			{
				Stop(close: true);
				return "unrendered";
			}
			if (Line + 1 < active.Lines.Count)
			{
				return NextLine(active);
			}
			Stop(close: true);
			return finish(active);
		}

		private string NextLine(QuestConversation conversation)
		{
			Line++;
			if (presenter.Show(speaker, Page(conversation, Line)))
			{
				return "line";
			}
			Stop(close: true);
			return "interrupted";
		}

		private void SpeakOnceRendered(QuestConversation conversation)
		{
			if (spokenLine != Line && presenter.Rendered)
			{
				spokenLine = Line;
				hold.Speak(conversation.Lines[Line]);
			}
		}

		public void Abort()
		{
			if (Active != null)
			{
				Stop(close: true);
			}
		}

		private void Stop(bool close)
		{
			try
			{
				hold.Release();
			}
			finally
			{
				if (close)
				{
					presenter.Close();
				}
				Active = null;
				speaker = null;
				Line = 0;
				spokenLine = -1;
			}
		}

		private static DialoguePage Page(QuestConversation conversation, int line)
		{
			string text = conversation.Lines[line];
			IReadOnlyList<string> choices;
			if (line + 1 != conversation.Lines.Count)
			{
				IReadOnlyList<string> readOnlyList = Array.Empty<string>();
				choices = readOnlyList;
			}
			else
			{
				choices = conversation.Replies;
			}
			return new DialoguePage(text, choices);
		}

		public object? Describe()
		{
			QuestConversation active = Active;
			if ((object)active != null)
			{
				return new
				{
					MenuOpen = true,
					Quest = active.QuestId,
					Step = active.StepId,
					Role = active.Role,
					Kind = active.Kind,
					CurrentLine = Line + 1,
					LineCount = active.Lines.Count,
					Text = active.Lines[Line],
					Choices = Page(active, Line).Choices,
					Rendered = presenter.Rendered,
					Diagnostics = presenter.Diagnostics
				};
			}
			return null;
		}

		public object? DescribeHold()
		{
			return hold.Describe();
		}
	}
	public sealed record QuestTarget(string QuestId, string StepId, string Role, int InstanceId);
	public interface IQuestMarker
	{
		void Show(IReadOnlyList<QuestTarget> targets);

		void Clear();

		object? Describe();
	}
	public sealed class QuestGuide
	{
		private readonly IQuestMarker marker;

		public IReadOnlyList<QuestTarget> Targets { get; private set; } = Array.Empty<QuestTarget>();

		public QuestGuide(IQuestMarker marker)
		{
			this.marker = marker;
		}

		public void Update(bool inGameplay, QuestSession session, IEnumerable<(QuestRoleMatch Match, NpcResolution Resolution)> bindings)
		{
			Targets = Select(inGameplay, session, bindings);
			marker.Show(Targets);
		}

		public void Refresh()
		{
			marker.Show(Targets);
		}

		public void Clear()
		{
			Targets = Array.Empty<QuestTarget>();
			marker.Clear();
		}

		public object? Describe()
		{
			return marker.Describe();
		}

		public static IReadOnlyList<QuestTarget> Select(bool inGameplay, QuestSession session, IEnumerable<(QuestRoleMatch Match, NpcResolution Resolution)> bindings)
		{
			if (!inGameplay || session.Epoch == null

plugins/modules/NoClip.Feature.module

Decompiled an hour ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppSystem;
using Microsoft.CodeAnalysis;
using Nivalis;
using Nivalis.Dialogue;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("NoClip.Feature")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("NoClip.Feature")]
[assembly: AssemblyTitle("NoClip.Feature")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	internal sealed class NativeNoClipBody : INoClipBody
	{
		private Object? owner;

		private OverrideLock? saveLock;

		public IntPtr Controller
		{
			get
			{
				PlayerCharacterController? obj = Current();
				if (obj == null)
				{
					return IntPtr.Zero;
				}
				return ((Il2CppObjectBase)obj).Pointer;
			}
		}

		public string? Refusal
		{
			get
			{
				DialogueUI instance = DialogueUI._instance;
				if ((Object)(object)instance != (Object)null && ((UIWindow)instance)._isOpen)
				{
					return "dialogue is open";
				}
				PlayerCharacter? obj = Player();
				if (!((Object)(object)((obj != null) ? obj.DrivenBoat : null) != (Object)null))
				{
					return null;
				}
				return "driving a boat";
			}
		}

		public bool Flying
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Invalid comparison between Unknown and I4
				PlayerCharacterController? obj = Current();
				if (obj == null)
				{
					return false;
				}
				return (int)obj.State == 1;
			}
		}

		public void SetFlying(bool on)
		{
			PlayerCharacterController? obj = Current() ?? throw new InvalidOperationException("No player controller.");
			obj.StopMovement();
			obj.State = (ControllerState)(on ? 1 : 0);
		}

		public bool LockSaving()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			if (saveLock != null)
			{
				return true;
			}
			PlayerInputManager val = default(PlayerInputManager);
			if (!Singleton<PlayerInputManager>.InstanceExist(ref val) || val.PreventSaving == null)
			{
				return false;
			}
			if (owner == null)
			{
				owner = new Object(IL2CPP.ManagedStringToIl2Cpp("nivalis-modding-toolkit:no-clip"));
			}
			saveLock = val.PreventSaving.Override(owner);
			return saveLock != null;
		}

		public void UnlockSaving()
		{
			try
			{
				OverrideLock? obj = saveLock;
				if (obj != null)
				{
					obj.Release();
				}
			}
			finally
			{
				saveLock = null;
			}
		}

		private static PlayerCharacter? Player()
		{
			PlayerManager val = default(PlayerManager);
			if (!Singleton<PlayerManager>.InstanceExist(ref val))
			{
				return null;
			}
			Player localPlayer = val.LocalPlayer;
			PlayerCharacter val2 = ((localPlayer != null) ? localPlayer.Character : null);
			if (!((Object)(object)val2 != (Object)null) || !((Component)val2).gameObject.activeInHierarchy)
			{
				return null;
			}
			return val2;
		}

		private static PlayerCharacterController? Current()
		{
			PlayerCharacter? obj = Player();
			PlayerCharacterController val = ((obj != null) ? obj.Controller : null);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return val;
		}
	}
	public sealed class NoClipModule : IFeatureModule, IReloadableModule, IDisposable
	{
		private NoClipSession? session;

		private GUIStyle? style;

		private Action<string> log = delegate
		{
		};

		public void Configure(ModuleServices services)
		{
		}

		public void Initialize(Action<string> log, string? state)
		{
			this.log = log;
			session = new NoClipSession(new NativeNoClipBody(), log, state == "on");
			log("No-clip ready. F5 toggles it; E/Q move up/down while flying.");
		}

		public string? CaptureState()
		{
			NoClipSession? noClipSession = session;
			if (noClipSession == null || !noClipSession.Active)
			{
				return null;
			}
			return "on";
		}

		public void Update()
		{
			Guarded(delegate
			{
				session.Update();
				Keyboard current = Keyboard.current;
				if (current != null && ((ButtonControl)current.f5Key).wasPressedThisFrame)
				{
					session.Toggle();
				}
			});
		}

		public void OnGUI()
		{
			Guarded(delegate
			{
				//IL_0054: Unknown result type (might be due to invalid IL or missing references)
				//IL_0021: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Unknown result type (might be due to invalid IL or missing references)
				//IL_0033: Expected O, but got Unknown
				if (session.Active)
				{
					if (style == null)
					{
						style = new GUIStyle(GUI.skin.label)
						{
							fontSize = 16
						};
					}
					GUI.Label(new Rect((float)Screen.width / 2f - 220f, 8f, 440f, 24f), "NO-CLIP (F5 off) | E up, Q down | saving blocked", style);
				}
			});
		}

		public void Dispose()
		{
			session?.Dispose();
			session = null;
		}

		private void Guarded(Action callback)
		{
			if (session == null)
			{
				return;
			}
			try
			{
				callback();
			}
			catch (Exception value)
			{
				log($"No-clip failed; landing the player: {value}");
				try
				{
					session.Dispose();
				}
				catch (Exception value2)
				{
					log($"No-clip could not land the player: {value2}");
				}
				throw;
			}
		}
	}
	public interface INoClipBody
	{
		IntPtr Controller { get; }

		string? Refusal { get; }

		bool Flying { get; }

		void SetFlying(bool on);

		bool LockSaving();

		void UnlockSaving();
	}
	public sealed class NoClipSession : IDisposable
	{
		private readonly INoClipBody body;

		private readonly Action<string> log;

		private IntPtr owned;

		private bool resume;

		public bool Active => owned != IntPtr.Zero;

		public string Status { get; private set; } = "off";

		public NoClipSession(INoClipBody body, Action<string> log, bool resume = false)
		{
			this.body = body;
			this.log = log;
			this.resume = resume;
		}

		public void Toggle()
		{
			resume = false;
			if (Active)
			{
				Stop("off");
			}
			else
			{
				Start();
			}
		}

		public void Update()
		{
			if (body.Controller == IntPtr.Zero)
			{
				return;
			}
			if (Active && (body.Controller != owned || !body.Flying))
			{
				Release();
				Status = "off (ended by the game)";
				log("No-clip ended by the game.");
			}
			if (Active)
			{
				string refusal = body.Refusal;
				if (refusal != null)
				{
					Stop("off (" + refusal + ")");
				}
			}
			if (resume && !Active)
			{
				resume = false;
				Start();
			}
		}

		public void Dispose()
		{
			Stop("off");
		}

		private void Start()
		{
			IntPtr controller = body.Controller;
			if (controller == IntPtr.Zero)
			{
				Refuse("no on-foot player");
				return;
			}
			string refusal = body.Refusal;
			if (refusal != null)
			{
				Refuse(refusal);
				return;
			}
			if (!body.LockSaving())
			{
				Refuse("save lock unavailable");
				return;
			}
			try
			{
				body.SetFlying(on: true);
			}
			catch
			{
				body.UnlockSaving();
				throw;
			}
			owned = controller;
			Status = "on";
			log("No-clip on; saving is blocked until it is turned off.");
		}

		private void Stop(string status)
		{
			if (!Active)
			{
				return;
			}
			try
			{
				if (body.Controller == owned && body.Flying)
				{
					body.SetFlying(on: false);
				}
			}
			finally
			{
				Release();
				Status = status;
			}
			log("No-clip off.");
		}

		private void Release()
		{
			owned = IntPtr.Zero;
			body.UnlockSaving();
		}

		private void Refuse(string reason)
		{
			Status = "off (" + reason + ")";
			log("No-clip refused: " + reason + ".");
		}
	}
}

plugins/NivalisModdingToolkit.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using BepInEx;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("NivalisModdingToolkit")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.0.2.0")]
[assembly: AssemblyInformationalVersion("0.0.2")]
[assembly: AssemblyProduct("NivalisModdingToolkit")]
[assembly: AssemblyTitle("NivalisModdingToolkit")]
[assembly: AssemblyVersion("0.0.2.0")]
[module: RefSafetyRules(11)]
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 NivalisModdingToolkit
{
	public interface IFeatureModule : IReloadableModule, IDisposable
	{
		void Configure(ModuleServices services);
	}
	public sealed class ModuleServices
	{
		public bool InspectorOpen { get; set; }

		public Func<string> HealthJson { get; set; } = () => "{}";
	}
	public sealed record NumberSetting(string Id, string Label, string Unit, float Value, float Minimum, float Maximum, float Step);
	public interface IModuleSettings
	{
		IReadOnlyList<NumberSetting> ReadSettings();

		void ApplySettings(IReadOnlyDictionary<string, float> values);
	}
	public interface IReloadableModule : IDisposable
	{
		void Initialize(Action<string> log, string? state);

		string? CaptureState();

		void Update();

		void OnGUI();
	}
	[BepInPlugin("garrettluskey.nivalis-modding-toolkit", "Nivalis Modding Toolkit", "0.0.2")]
	public sealed class Plugin : BasePlugin
	{
		internal static ManualLogSource Logger;

		public override void Load()
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			((BasePlugin)this).AddComponent<ToolkitHost>();
			ManualLogSource log = ((BasePlugin)this).Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(75, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Nivalis Modding Toolkit host ready; modules load from ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ToolkitPaths.Modules);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(". F7 forces a reload.");
			}
			log.LogInfo(val);
		}
	}
	public sealed class ToolkitHost : MonoBehaviour
	{
		private readonly ReloadController loader = new ReloadController(delegate(string message)
		{
			Plugin.Logger.LogInfo((object)message);
		});

		private static readonly string ModulePath = Path.Combine(ToolkitPaths.Modules, "NivalisModdingToolkit.Runtime.module");

		private float nextCheck;

		private string? lastReadError;

		public ToolkitHost(IntPtr pointer)
			: base(pointer)
		{
		}

		public void Update()
		{
			PollRuntimeFile();
			loader.Update();
		}

		private void PollRuntimeFile()
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Expected O, but got Unknown
			bool flag = Keyboard.current != null && ((ButtonControl)Keyboard.current.f7Key).wasPressedThisFrame;
			if (!flag && Time.realtimeSinceStartup < nextCheck)
			{
				return;
			}
			nextCheck = Time.realtimeSinceStartup + 1f;
			try
			{
				loader.Reload(File.ReadAllBytes(ModulePath), flag);
				lastReadError = null;
			}
			catch (Exception ex)
			{
				if (lastReadError != ex.Message)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag2 = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(59, 1, ref flag2);
					if (flag2)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot read the toolkit runtime; retaining current module: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
					}
					logger.LogError(val);
				}
				lastReadError = ex.Message;
			}
		}

		public void OnGUI()
		{
			loader.OnGUI();
		}

		public void OnDestroy()
		{
			loader.Dispose();
		}
	}
	public sealed class ReloadController : IDisposable
	{
		private sealed class ModuleContext : AssemblyLoadContext
		{
			public ModuleContext()
				: base(isCollectible: true)
			{
			}

			protected override Assembly? Load(AssemblyName name)
			{
				Assembly assembly = typeof(IReloadableModule).Assembly;
				if (AssemblyName.ReferenceMatchesDefinition(name, assembly.GetName()))
				{
					return assembly;
				}
				return AssemblyLoadContext.Default.LoadFromAssemblyName(name);
			}
		}

		private readonly Action<string> log;

		private readonly Action<IReloadableModule>? configure;

		private ModuleContext? context;

		private IReloadableModule? module;

		private string? attemptedHash;

		private bool faulted;

		public WeakReference? RetiredContext { get; private set; }

		public string? BuildId { get; private set; }

		public IModuleSettings? Settings => module as IModuleSettings;

		public ReloadController(Action<string> log, Action<IReloadableModule>? configure = null)
		{
			this.log = log;
			this.configure = configure;
		}

		public void Reload(byte[] bytes, bool force = false)
		{
			string text = Convert.ToHexString(SHA256.HashData(bytes));
			if (!force && text == attemptedHash)
			{
				return;
			}
			attemptedHash = text;
			ModuleContext moduleContext = new ModuleContext();
			IReloadableModule reloadableModule = null;
			string text2;
			try
			{
				using MemoryStream assembly = new MemoryStream(bytes, writable: false);
				Assembly assembly2 = moduleContext.LoadFromStream(assembly);
				reloadableModule = (IReloadableModule)Activator.CreateInstance(assembly2.GetTypes().Single((Type type) => !type.IsAbstract && typeof(IReloadableModule).IsAssignableFrom(type)));
				configure?.Invoke(reloadableModule);
				reloadableModule.Initialize(log, module?.CaptureState());
				text2 = assembly2.ManifestModule.ModuleVersionId.ToString().Substring(0, 8);
			}
			catch (Exception value)
			{
				Release(reloadableModule, moduleContext);
				log($"Module rejected; previous module retained: {value}");
				return;
			}
			RetireCurrent();
			context = moduleContext;
			module = reloadableModule;
			BuildId = text2;
			faulted = false;
			log($"Hotloaded module {text2} (SHA256 {text.Substring(0, 12)}).");
		}

		public void Update()
		{
			Invoke(gui: false);
		}

		public void OnGUI()
		{
			Invoke(gui: true);
		}

		private void Invoke(bool gui)
		{
			if (module == null || faulted)
			{
				return;
			}
			try
			{
				if (gui)
				{
					module.OnGUI();
				}
				else
				{
					module.Update();
				}
			}
			catch (Exception value)
			{
				faulted = true;
				log($"Module suspended after callback failure; rebuild or press F7 to retry: {value}");
			}
		}

		private void RetireCurrent()
		{
			if (context != null)
			{
				RetiredContext = new WeakReference(context);
				Release(module, context);
			}
		}

		private void Release(IReloadableModule? retiring, ModuleContext retiringContext)
		{
			try
			{
				retiring?.Dispose();
			}
			catch (Exception value)
			{
				log($"Module cleanup failed: {value}");
			}
			finally
			{
				retiringContext.Unload();
			}
		}

		public void Dispose()
		{
			RetireCurrent();
			module = null;
			context = null;
			attemptedHash = null;
			BuildId = null;
		}
	}
	public static class ToolkitPaths
	{
		public const string Name = "NivalisModdingToolkit";

		public static string Modules { get; } = Path.Combine(HostDirectory(), "modules");

		public static string Data => Path.Combine(Paths.BepInExRootPath, "NivalisModdingToolkit");

		public static string Config(string fileName)
		{
			return Path.Combine(Paths.ConfigPath, "NivalisModdingToolkit", fileName);
		}

		private static string HostDirectory()
		{
			string location = typeof(ToolkitPaths).Assembly.Location;
			if (string.IsNullOrEmpty(location))
			{
				return Path.Combine(Paths.PluginPath, "NivalisModdingToolkit");
			}
			return Path.GetDirectoryName(location);
		}
	}
	internal static class PluginVersion
	{
		public const string Value = "0.0.2";
	}
}