Decompiled source of BepisDynamicVariablePowerTools v1.0.4

plugins/BepisDynamicVariablePowerTools/BepisDynamicVariablePowerTools.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.NET.Common;
using BepInExResoniteShim;
using BepisDynamicVariablePowerTools.Extensions;
using BepisDynamicVariablePowerTools.Helpers;
using Elements.Core;
using FrooxEngine;
using FrooxEngine.FrooxEngine.ProtoFlux.CoreNodes;
using FrooxEngine.ProtoFlux;
using FrooxEngine.UIX;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v10.0", FrameworkDisplayName = ".NET 10.0")]
[assembly: AssemblyCompany("BowenArrows2K")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.4.0")]
[assembly: AssemblyInformationalVersion("1.0.4+4fcecfaa5dda239728ce3cd7957f33be6b8c11ce")]
[assembly: AssemblyProduct("BepisDynamicVariablePowerTools")]
[assembly: AssemblyTitle("BepisDynamicVariablePowerTools")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/BowenArrows2K/BepisDynamicVariablePowerTools")]
[assembly: AssemblyVersion("1.0.4.0")]
[module: RefSafetyRules(11)]
namespace BepisDynamicVariablePowerTools
{
	[ResonitePlugin("net.bowenarrows2k.BepisDynamicVariablePowerTools", "BepisDynamicVariablePowerTools", "1.0.4", "BowenArrows2K", "https://github.com/BowenArrows2K/BepisDynamicVariablePowerTools")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class BepisDynamicVariablePowerTools : BasePlugin
	{
		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Mod_Enabled;

		internal static ConfigEntry<bool> ChangeProtoFluxStringInputs;

		internal static ConfigEntry<bool> RenameDynvarSources;

		internal static ConfigEntry<bool> DebugInfo_Enabled;

		internal static ConfigEntry<bool> DebugInfo_LinkedVars;

		internal static ConfigEntry<bool> DebugInfo_CompHierarchy;

		internal static ConfigEntry<bool> DebugInfo_OutputInPopoutUI;

		public override void Load()
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			Log = ((BasePlugin)this).Log;
			ManualLogSource log = Log;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(18, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("net.bowenarrows2k.BepisDynamicVariablePowerTools");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is loaded!");
			}
			log.LogInfo(val);
			((BasePlugin)this).HarmonyInstance.PatchAll();
			Mod_Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, (ConfigDescription)null);
			ChangeProtoFluxStringInputs = ((BasePlugin)this).Config.Bind<bool>("General", "Change ProtoFlux String Inputs on Rename", false, (ConfigDescription)null);
			RenameDynvarSources = ((BasePlugin)this).Config.Bind<bool>("General", "Rename DynVar Sources", true, (ConfigDescription)null);
			DebugInfo_Enabled = ((BasePlugin)this).Config.Bind<bool>("Debug Info", "Enabled", true, (ConfigDescription)null);
			DebugInfo_LinkedVars = ((BasePlugin)this).Config.Bind<bool>("Debug Info", "Output Linked Variables", true, (ConfigDescription)null);
			DebugInfo_CompHierarchy = ((BasePlugin)this).Config.Bind<bool>("Debug Info", "Output Component Hierarchy", true, (ConfigDescription)null);
			DebugInfo_OutputInPopoutUI = ((BasePlugin)this).Config.Bind<bool>("Debug Info", "Output debug info in Pop-Out UI", true, new ConfigDescription("When this setting is True the DynamicVariableSpace Debug Info will pop-out a Text Display when pressed.\nWhen False the Output will be displayed in a string value field on the component.", (AcceptableValueBase)null, global::System.Array.Empty<object>()));
		}
	}
	internal sealed class DebugInfoGenerator
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass1_0
		{
			[StructLayout((LayoutKind)3)]
			private struct <<OutputComponentHierarchy>b__0>d : IAsyncStateMachine
			{
				public int <>1__state;

				public AsyncTaskMethodBuilder <>t__builder;

				public <>c__DisplayClass1_0 <>4__this;

				private string <output>5__2;

				private ToBackground <>u__1;

				private ToWorld <>u__2;

				private void MoveNext()
				{
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_0059: Unknown result type (might be due to invalid IL or missing references)
					//IL_0060: Unknown result type (might be due to invalid IL or missing references)
					//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
					//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00e9: 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_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_003a: 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_00a1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
					//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
					//IL_0138: Unknown result type (might be due to invalid IL or missing references)
					//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
					int num = <>1__state;
					<>c__DisplayClass1_0 <>c__DisplayClass1_ = <>4__this;
					try
					{
						ToWorld val;
						ToBackground val3;
						if (num != 0)
						{
							if (num == 1)
							{
								val = <>u__2;
								<>u__2 = default(ToWorld);
								num = (<>1__state = -1);
								goto IL_00f8;
							}
							ToBackground val2 = default(ToBackground);
							val3 = ((ToBackground)(ref val2)).GetAwaiter();
							if (!((ToBackground)(ref val3)).IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = val3;
								((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitOnCompleted<ToBackground, <<OutputComponentHierarchy>b__0>d>(ref val3, ref this);
								return;
							}
						}
						else
						{
							val3 = <>u__1;
							<>u__1 = default(ToBackground);
							num = (<>1__state = -1);
						}
						((ToBackground)(ref val3)).GetResult();
						SpaceTree spaceTree = new SpaceTree(<>c__DisplayClass1_.space);
						<output>5__2 = (spaceTree.Process() ? ((object)spaceTree).ToString() : "");
						ToWorld val4 = default(ToWorld);
						val = ((ToWorld)(ref val4)).GetAwaiter();
						if (!((ToWorld)(ref val)).IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = val;
							((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitOnCompleted<ToWorld, <<OutputComponentHierarchy>b__0>d>(ref val, ref this);
							return;
						}
						goto IL_00f8;
						IL_00f8:
						((ToWorld)(ref val)).GetResult();
						((SyncField<string>)(object)<>c__DisplayClass1_.target).Value = <output>5__2;
						if (BepisDynamicVariablePowerTools.DebugInfo_OutputInPopoutUI.Value)
						{
							Slot obj = ((Worker)<>c__DisplayClass1_.space).LocalUserSpace.AddSlot("DynVarSpaceInfo", true);
							SlotPositioning.PositionInFrontOfUser(obj, (float3?)float3.Backward, (float3?)null, 1f, (User)null, true, true, true);
							UniversalImporter.SpawnText(obj, $"Hierarchy of linked dynamic variable components of Namespace {<>c__DisplayClass1_.space.SpaceName} on {((Component)<>c__DisplayClass1_.space).Slot.Name}", <output>5__2, 16f, (float2?)null, true);
						}
					}
					catch (global::System.Exception exception)
					{
						<>1__state = -2;
						<output>5__2 = null;
						((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception);
						return;
					}
					<>1__state = -2;
					<output>5__2 = null;
					((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult();
				}

				[DebuggerHidden]
				private void SetStateMachine(IAsyncStateMachine stateMachine)
				{
					((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine);
				}
			}

			public DynamicVariableSpace space;

			public Sync<string> target;

			[AsyncStateMachine(typeof(<<OutputComponentHierarchy>b__0>d))]
			internal global::System.Threading.Tasks.Task <OutputComponentHierarchy>b__0()
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				<<OutputComponentHierarchy>b__0>d <<OutputComponentHierarchy>b__0>d = default(<<OutputComponentHierarchy>b__0>d);
				<<OutputComponentHierarchy>b__0>d.<>t__builder = AsyncTaskMethodBuilder.Create();
				<<OutputComponentHierarchy>b__0>d.<>4__this = this;
				<<OutputComponentHierarchy>b__0>d.<>1__state = -1;
				((AsyncTaskMethodBuilder)(ref <<OutputComponentHierarchy>b__0>d.<>t__builder)).Start<<<OutputComponentHierarchy>b__0>d>(ref <<OutputComponentHierarchy>b__0>d);
				return ((AsyncTaskMethodBuilder)(ref <<OutputComponentHierarchy>b__0>d.<>t__builder)).Task;
			}
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass2_0
		{
			[StructLayout((LayoutKind)3)]
			private struct <<OutputLinkedVariables>b__0>d : IAsyncStateMachine
			{
				public int <>1__state;

				public AsyncTaskMethodBuilder <>t__builder;

				public <>c__DisplayClass2_0 <>4__this;

				private StringBuilder <names>5__2;

				private ToBackground <>u__1;

				private ToWorld <>u__2;

				private void MoveNext()
				{
					//IL_0054: Unknown result type (might be due to invalid IL or missing references)
					//IL_0059: Unknown result type (might be due to invalid IL or missing references)
					//IL_0060: Unknown result type (might be due to invalid IL or missing references)
					//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
					//IL_00d3: Expected O, but got Unknown
					//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
					//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
					//IL_0281: Unknown result type (might be due to invalid IL or missing references)
					//IL_0286: Unknown result type (might be due to invalid IL or missing references)
					//IL_028e: 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_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_003a: 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_02e2: Unknown result type (might be due to invalid IL or missing references)
					//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
					//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
					//IL_0246: Unknown result type (might be due to invalid IL or missing references)
					//IL_024c: Unknown result type (might be due to invalid IL or missing references)
					//IL_0251: 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_0268: Unknown result type (might be due to invalid IL or missing references)
					int num = <>1__state;
					<>c__DisplayClass2_0 <>c__DisplayClass2_ = <>4__this;
					try
					{
						ToWorld val;
						ToBackground val3;
						if (num != 0)
						{
							if (num == 1)
							{
								val = <>u__2;
								<>u__2 = default(ToWorld);
								num = (<>1__state = -1);
								goto IL_029d;
							}
							ToBackground val2 = default(ToBackground);
							val3 = ((ToBackground)(ref val2)).GetAwaiter();
							if (!((ToBackground)(ref val3)).IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = val3;
								((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitOnCompleted<ToBackground, <<OutputLinkedVariables>b__0>d>(ref val3, ref this);
								return;
							}
						}
						else
						{
							val3 = <>u__1;
							<>u__1 = default(ToBackground);
							num = (<>1__state = -1);
						}
						((ToBackground)(ref val3)).GetResult();
						<names>5__2 = new StringBuilder($"Variables linked to Namespace [{<>c__DisplayClass2_.space.SpaceName}] on {((Component)<>c__DisplayClass2_.space).Slot.Name}");
						StringBuilder val4 = <names>5__2;
						StringBuilder obj = val4;
						AppendInterpolatedStringHandler val5 = new AppendInterpolatedStringHandler(1, 1, val4);
						((AppendInterpolatedStringHandler)(ref val5)).AppendFormatted<Sync<string>>(<>c__DisplayClass2_.space.SpaceName);
						((AppendInterpolatedStringHandler)(ref val5)).AppendLiteral(":");
						obj.AppendLine(ref val5);
						FieldInfo dynamicValueDict = _dynamicValueDict;
						global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)((dynamicValueDict != null) ? dynamicValueDict.GetValue((object)<>c__DisplayClass2_.space) : null)).GetEnumerator();
						try
						{
							while (enumerator.MoveNext())
							{
								object current = enumerator.Current;
								object value = current.GetType().GetProperty("Key").GetValue(current);
								global::System.Type type = value.GetType();
								string text = (string)type.GetField("name", (BindingFlags)52).GetValue(value);
								global::System.Type type2 = (global::System.Type)type.GetField("type", (BindingFlags)52).GetValue(value);
								val4 = <names>5__2;
								StringBuilder obj2 = val4;
								val5 = new AppendInterpolatedStringHandler(3, 2, val4);
								((AppendInterpolatedStringHandler)(ref val5)).AppendFormatted(text);
								((AppendInterpolatedStringHandler)(ref val5)).AppendLiteral(" (");
								((AppendInterpolatedStringHandler)(ref val5)).AppendFormatted(ReflectionExtensions.GetNiceName(type2, "<", ">", "+"));
								((AppendInterpolatedStringHandler)(ref val5)).AppendLiteral(")");
								obj2.AppendLine(ref val5);
							}
						}
						finally
						{
							if (num < 0 && enumerator is global::System.IDisposable disposable)
							{
								disposable.Dispose();
							}
						}
						<names>5__2.Remove(<names>5__2.Length - Environment.NewLine.Length, Environment.NewLine.Length);
						ToWorld val6 = default(ToWorld);
						val = ((ToWorld)(ref val6)).GetAwaiter();
						if (!((ToWorld)(ref val)).IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = val;
							((AsyncTaskMethodBuilder)(ref <>t__builder)).AwaitOnCompleted<ToWorld, <<OutputLinkedVariables>b__0>d>(ref val, ref this);
							return;
						}
						goto IL_029d;
						IL_029d:
						((ToWorld)(ref val)).GetResult();
						((SyncField<string>)(object)<>c__DisplayClass2_.target).Value = ((object)<names>5__2).ToString();
						if (BepisDynamicVariablePowerTools.DebugInfo_OutputInPopoutUI.Value)
						{
							Slot obj3 = ((Worker)<>c__DisplayClass2_.space).LocalUserSpace.AddSlot("DynVarSpaceInfo", true);
							SlotPositioning.PositionInFrontOfUser(obj3, (float3?)float3.Backward, (float3?)null, 1f, (User)null, true, true, true);
							UniversalImporter.SpawnText(obj3, $"Variables linked to Namespace [{<>c__DisplayClass2_.space.SpaceName}] on {((Component)<>c__DisplayClass2_.space).Slot.Name}", ((object)<names>5__2).ToString(), 16f, (float2?)null, true);
						}
					}
					catch (global::System.Exception exception)
					{
						<>1__state = -2;
						<names>5__2 = null;
						((AsyncTaskMethodBuilder)(ref <>t__builder)).SetException(exception);
						return;
					}
					<>1__state = -2;
					<names>5__2 = null;
					((AsyncTaskMethodBuilder)(ref <>t__builder)).SetResult();
				}

				[DebuggerHidden]
				private void SetStateMachine(IAsyncStateMachine stateMachine)
				{
					((AsyncTaskMethodBuilder)(ref <>t__builder)).SetStateMachine(stateMachine);
				}
			}

			public DynamicVariableSpace space;

			public Sync<string> target;

			[AsyncStateMachine(typeof(<<OutputLinkedVariables>b__0>d))]
			internal global::System.Threading.Tasks.Task <OutputLinkedVariables>b__0()
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				<<OutputLinkedVariables>b__0>d <<OutputLinkedVariables>b__0>d = default(<<OutputLinkedVariables>b__0>d);
				<<OutputLinkedVariables>b__0>d.<>t__builder = AsyncTaskMethodBuilder.Create();
				<<OutputLinkedVariables>b__0>d.<>4__this = this;
				<<OutputLinkedVariables>b__0>d.<>1__state = -1;
				((AsyncTaskMethodBuilder)(ref <<OutputLinkedVariables>b__0>d.<>t__builder)).Start<<<OutputLinkedVariables>b__0>d>(ref <<OutputLinkedVariables>b__0>d);
				return ((AsyncTaskMethodBuilder)(ref <<OutputLinkedVariables>b__0>d.<>t__builder)).Task;
			}
		}

		private static readonly FieldInfo _dynamicValueDict = typeof(DynamicVariableSpace).GetField("_dynamicValues", (BindingFlags)36);

		internal static void OutputComponentHierarchy(DynamicVariableSpace space, Sync<string> target)
		{
			<>c__DisplayClass1_0 CS$<>8__locals4 = new <>c__DisplayClass1_0();
			CS$<>8__locals4.space = space;
			CS$<>8__locals4.target = target;
			((Worker)CS$<>8__locals4.space).StartTask((Func<global::System.Threading.Tasks.Task>)([AsyncStateMachine(typeof(<>c__DisplayClass1_0.<<OutputComponentHierarchy>b__0>d))] () =>
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				<>c__DisplayClass1_0.<<OutputComponentHierarchy>b__0>d <<OutputComponentHierarchy>b__0>d = default(<>c__DisplayClass1_0.<<OutputComponentHierarchy>b__0>d);
				<<OutputComponentHierarchy>b__0>d.<>t__builder = AsyncTaskMethodBuilder.Create();
				<<OutputComponentHierarchy>b__0>d.<>4__this = CS$<>8__locals4;
				<<OutputComponentHierarchy>b__0>d.<>1__state = -1;
				((AsyncTaskMethodBuilder)(ref <<OutputComponentHierarchy>b__0>d.<>t__builder)).Start<<>c__DisplayClass1_0.<<OutputComponentHierarchy>b__0>d>(ref <<OutputComponentHierarchy>b__0>d);
				return ((AsyncTaskMethodBuilder)(ref <<OutputComponentHierarchy>b__0>d.<>t__builder)).Task;
			}));
		}

		internal static void OutputLinkedVariables(DynamicVariableSpace space, Sync<string> target)
		{
			<>c__DisplayClass2_0 CS$<>8__locals4 = new <>c__DisplayClass2_0();
			CS$<>8__locals4.space = space;
			CS$<>8__locals4.target = target;
			((Worker)CS$<>8__locals4.space).StartTask((Func<global::System.Threading.Tasks.Task>)([AsyncStateMachine(typeof(<>c__DisplayClass2_0.<<OutputLinkedVariables>b__0>d))] () =>
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				<>c__DisplayClass2_0.<<OutputLinkedVariables>b__0>d <<OutputLinkedVariables>b__0>d = default(<>c__DisplayClass2_0.<<OutputLinkedVariables>b__0>d);
				<<OutputLinkedVariables>b__0>d.<>t__builder = AsyncTaskMethodBuilder.Create();
				<<OutputLinkedVariables>b__0>d.<>4__this = CS$<>8__locals4;
				<<OutputLinkedVariables>b__0>d.<>1__state = -1;
				((AsyncTaskMethodBuilder)(ref <<OutputLinkedVariables>b__0>d.<>t__builder)).Start<<>c__DisplayClass2_0.<<OutputLinkedVariables>b__0>d>(ref <<OutputLinkedVariables>b__0>d);
				return ((AsyncTaskMethodBuilder)(ref <<OutputLinkedVariables>b__0>d.<>t__builder)).Task;
			}));
		}
	}
	internal sealed class RenameDirectlyLinkedVariables
	{
		internal static void RenameSpace(DynamicVariableSpace space, string newName)
		{
			newName = DynamicVariableHelper.ProcessName(newName);
			string currentName = ((SyncField<string>)(object)space.SpaceName).Value;
			string prefixName = currentName + "/";
			((Component)space).Slot.ForeachComponentInChildren<IDynamicVariable>((Action<IDynamicVariable>)delegate(IDynamicVariable dynVar)
			{
				//IL_003b: 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)
				string text = default(string);
				string text2 = default(string);
				DynamicVariableHelper.ParsePath(dynVar.VariableName, ref text, ref text2);
				if (text != null && Traverse.Create((object)dynVar).Field("handler").Field("_currentSpace")
					.GetValue() == space)
				{
					IField<string> val = ((Worker)dynVar).TryGetField<string>("VariableName") ?? ((Worker)dynVar).TryGetField<string>("_variableName");
					if (val != null && ((IValue<string>)(object)val).Value.StartsWith(prefixName))
					{
						((IValue<string>)(object)val).Value = newName + "/" + text2;
					}
					else
					{
						ProtoFluxEngineProxy val2 = (ProtoFluxEngineProxy)(object)((dynVar is ProtoFluxEngineProxy) ? dynVar : null);
						if (val2 != null)
						{
							SyncRef<IProtoFluxNode> node = val2.Node;
							if (node != null)
							{
								IProtoFluxNode target = node.Target;
								if (target != null && ((IWorker)target).TryGetField("VariableName") is SyncRef<IGlobalValueProxy<string>> val3 && val3.Target is GlobalValue<string> val4 && ((SyncField<string>)(object)val4.Value).Value.StartsWith(prefixName))
								{
									((SyncField<string>)(object)val4.Value).Value = newName + "/" + text2;
								}
							}
						}
					}
				}
			}, true, true);
			if (BepisDynamicVariablePowerTools.ChangeProtoFluxStringInputs.Value)
			{
				((Component)space).Slot.ForeachComponentInChildren<IInput<string>>((Action<IInput<string>>)delegate(IInput<string> stringInput)
				{
					string text = default(string);
					string text2 = default(string);
					DynamicVariableHelper.ParsePath(stringInput.Value, ref text, ref text2);
					if (text != null && !(text != currentName))
					{
						stringInput.Value = stringInput.Value.Replace(text, newName);
					}
				}, true, true);
			}
			((SyncField<string>)(object)space.SpaceName).Value = newName;
		}
	}
	internal sealed class RenameDynamicVariables
	{
		private static global::System.Type GetDynVarType(IDynamicVariable dynVar)
		{
			return ReflectionExtensions.GetGenericArgumentsFromInterface(((object)dynVar).GetType(), typeof(IDynamicVariable<>))[0];
		}

		private static bool IsDynVarOfType(IDynamicVariable dynVar, global::System.Type innerType)
		{
			return GetDynVarType(dynVar) == innerType;
		}

		internal static void RenameDynamicVariable(IDynamicVariable dynVar, string newName)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: 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)
			if (!dynVar.TryGetLinkedSpace(out DynamicVariableSpace linkedSpace))
			{
				((IValue<string>)(object)((Worker)dynVar).TryGetField<string>("VariableName")).Value = newName;
				return;
			}
			global::System.Type dynVarType = GetDynVarType(dynVar);
			string currentFullName = dynVar.VariableName;
			string text = default(string);
			string currentVariableName = default(string);
			DynamicVariableHelper.ParsePath(currentFullName, ref text, ref currentVariableName);
			Predicate<IDynamicVariable> filter = (Sync<bool>.op_Implicit(linkedSpace.OnlyDirectBinding) ? ((Predicate<IDynamicVariable>)((IDynamicVariable it) => it.VariableName == currentFullName && IsDynVarOfType(it, dynVarType))) : ((Predicate<IDynamicVariable>)((IDynamicVariable it) => (it.VariableName == currentFullName || it.VariableName == currentVariableName) && IsDynVarOfType(it, dynVarType))));
			global::System.Collections.Generic.IEnumerator<IDynamicVariable> enumerator = linkedSpace.GetLinkedVariables(filter, includeLocal: true).GetEnumerator();
			try
			{
				while (((global::System.Collections.IEnumerator)enumerator).MoveNext())
				{
					IDynamicVariable current = enumerator.Current;
					IField<string> val = ((Worker)current).TryGetField<string>("VariableName") ?? ((Worker)current).TryGetField<string>("_variableName");
					if (val != null)
					{
						((IValue<string>)(object)val).Value = newName;
						continue;
					}
					ProtoFluxEngineProxy val2 = (ProtoFluxEngineProxy)(object)((current is ProtoFluxEngineProxy) ? current : null);
					if (val2 == null)
					{
						continue;
					}
					SyncRef<IProtoFluxNode> node = val2.Node;
					if (node != null)
					{
						IProtoFluxNode target = node.Target;
						if (target != null && ((IWorker)target).TryGetField("VariableName") is SyncRef<IGlobalValueProxy<string>> val3 && val3.Target is GlobalValue<string> val4)
						{
							((SyncField<string>)(object)val4.Value).Value = newName;
						}
					}
				}
			}
			finally
			{
				((global::System.IDisposable)enumerator)?.Dispose();
			}
			if (!BepisDynamicVariablePowerTools.ChangeProtoFluxStringInputs.Value || text == null)
			{
				return;
			}
			((Component)linkedSpace).Slot.ForeachComponentInChildren<IInput<string>>((Action<IInput<string>>)delegate(IInput<string> stringInput)
			{
				if (!(stringInput.Value != currentFullName))
				{
					stringInput.Value = newName;
				}
			}, true, true);
		}
	}
	internal sealed class SpaceTree
	{
		private readonly Slot _slot;

		private readonly DynamicVariableSpace _space;

		private SpaceTree[] _children = global::System.Array.Empty<SpaceTree>();

		private IDynamicVariable[] _dynVars = global::System.Array.Empty<IDynamicVariable>();

		public SpaceTree(DynamicVariableSpace space, Slot? slot = null)
		{
			_space = space;
			_slot = slot ?? ((Component)space).Slot;
		}

		public bool Process()
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			_dynVars = ((ContainerWorker<Component>)(object)_slot).GetComponents<IDynamicVariable>((Predicate<IDynamicVariable>)([CompilerGenerated] (IDynamicVariable dynVar) => dynVar.IsLinkedToSpace(_space)), false).ToArray();
			_children = Enumerable.ToArray<SpaceTree>(Enumerable.Where<SpaceTree>(Enumerable.Select<Slot, SpaceTree>((global::System.Collections.Generic.IEnumerable<Slot>)(object)_slot.Children, (Func<Slot, SpaceTree>)([CompilerGenerated] (Slot child) => new SpaceTree(_space, child))), (Func<SpaceTree, bool>)((SpaceTree tree) => tree.Process())));
			if (_dynVars.Length == 0)
			{
				return _children.Length != 0;
			}
			return true;
		}

		public string ToString()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			StringBuilder val = new StringBuilder($"Hierarchy of linked dynamic variable components of Namespace [{_space.SpaceName}] on {((Component)_space).Slot.Name}");
			val.AppendLine();
			BuildString(val, "");
			val.Remove(val.Length - Environment.NewLine.Length, Environment.NewLine.Length);
			return ((object)val).ToString();
		}

		private static void AppendDynVar(StringBuilder builder, string indent, IDynamicVariable dynVar, bool last = false)
		{
			builder.Append(indent);
			builder.Append(last ? "└─" : "├─");
			builder.Append(dynVar.VariableName);
			builder.Append(" (");
			builder.Append(ReflectionExtensions.GetNiceName(((object)dynVar).GetType(), "<", ">", "+"));
			builder.AppendLine(")");
		}

		private static void AppendSlot(StringBuilder builder, string indent, SpaceTree child, bool first, bool last)
		{
			if (!first)
			{
				builder.Append(indent);
				builder.AppendLine("│");
			}
			builder.Append(indent);
			builder.Append(last ? "└─" : "├─");
			AppendInterpolatedStringHandler val = default(AppendInterpolatedStringHandler);
			((AppendInterpolatedStringHandler)(ref val))..ctor(20, 1, builder);
			((AppendInterpolatedStringHandler)(ref val)).AppendFormatted(child._slot.Name);
			((AppendInterpolatedStringHandler)(ref val)).AppendLiteral("<noparse></closeall>");
			builder.AppendLine(ref val);
			child.BuildString(builder, indent + (last ? "  " : "│ "));
		}

		private void BuildString(StringBuilder builder, string indent)
		{
			if (_dynVars.Length != 0)
			{
				for (int i = 0; i < _dynVars.Length - 1; i++)
				{
					AppendDynVar(builder, indent, _dynVars[i]);
				}
				bool flag = _children.Length == 0;
				IDynamicVariable[] dynVars = _dynVars;
				AppendDynVar(builder, indent, dynVars[dynVars.Length - 1], flag);
				if (!flag)
				{
					builder.Append(indent);
					builder.AppendLine("│");
				}
			}
			if (_children.Length != 0)
			{
				for (int j = 0; j < _children.Length; j++)
				{
					AppendSlot(builder, indent, _children[j], j == 0, j == _children.Length - 1);
				}
			}
		}
	}
	public static class PluginMetadata
	{
		public const string GUID = "net.bowenarrows2k.BepisDynamicVariablePowerTools";

		public const string NAME = "BepisDynamicVariablePowerTools";

		public const string VERSION = "1.0.4";

		public const string AUTHORS = "BowenArrows2K";

		public const string REPOSITORY_URL = "https://github.com/BowenArrows2K/BepisDynamicVariablePowerTools";
	}
}
namespace BepisDynamicVariablePowerTools.Patches
{
	[HarmonyPatch]
	public static class RenameDynvarSources
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(ProtoFluxNodeVisual), "BuildUI")]
		public static void RenameSource(ProtoFluxNodeVisual __instance)
		{
			if (BepisDynamicVariablePowerTools.RenameDynvarSources.Value)
			{
				ProtoFluxNode target = ((SyncRef<ProtoFluxNode>)(object)__instance.Node).Target;
				global::System.Type type = ((object)target).GetType();
				global::System.Type type2 = (type.IsGenericType ? type.GetGenericTypeDefinition() : type);
				global::System.Type type3 = (type.IsGenericType ? type.GenericTypeArguments[0] : type);
				if (type2 == typeof(ValueSource<>))
				{
					((MethodBase)ReflectionExtensions.GetGenericMethod(typeof(RenameDynvarSources), "HandleValueSource", (BindingFlags)24, new global::System.Type[1] { type3 })).Invoke((object)null, new object[2] { __instance, target });
				}
				if (type2 == typeof(ReferenceSource<>))
				{
					((MethodBase)ReflectionExtensions.GetGenericMethod(typeof(RenameDynvarSources), "HandleReferenceSource", (BindingFlags)24, new global::System.Type[1] { type3 })).Invoke((object)null, new object[2] { __instance, target });
				}
			}
		}

		public static void HandleValueSource<T>(ProtoFluxNodeVisual visual, ValueSource<T> source) where T : unmanaged
		{
			IWorldElement parent = ((IWorldElement)(IValue<T>)(object)source.RootSourceReference.Target).Parent;
			Component val = (Component)(object)((parent is Component) ? parent : null);
			if (val != null)
			{
				global::System.Type type = ((object)val).GetType();
				if (type.IsGenericType && type == typeof(DynamicValueVariable<T>))
				{
					string variableName = Sync<string>.op_Implicit(Traverse.Create((object)parent).Field<Sync<string>>("VariableName").Value);
					ReplaceNodeText(visual, val, variableName);
				}
			}
		}

		public static void HandleReferenceSource<T>(ProtoFluxNodeVisual visual, ReferenceSource<T> source) where T : class, IWorldElement
		{
			IWorldElement parent = ((SyncElement)(SyncRef<T>)(object)source.RootSourceReference.Target).Parent;
			Component val = (Component)(object)((parent is Component) ? parent : null);
			if (val != null)
			{
				global::System.Type type = ((object)val).GetType();
				if (type.IsGenericType && type == typeof(DynamicReferenceVariable<T>))
				{
					string variableName = Sync<string>.op_Implicit(Traverse.Create((object)parent).Field<Sync<string>>("VariableName").Value);
					ReplaceNodeText(visual, val, variableName);
				}
			}
		}

		public static void ReplaceNodeText(ProtoFluxNodeVisual visual, Component component, string VariableName)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			((SyncField<string>)(object)((ContainerWorker<Component>)(object)Enumerable.First<Slot>((global::System.Collections.Generic.IEnumerable<Slot>)(object)((Component)visual).Slot.FindChildInHierarchy("Overlapping Layout").FindChild("Horizontal Layout").Children)).GetComponent<Text>((Predicate<Text>)null, false).Content).Value = $"<size=60%>Dynamic Variable:</size>\n<i>{VariableName}</i><size=75%>\n(On: {component.Slot.Name})</size>";
		}
	}
	[HarmonyPatch]
	public class WorkerInspector_Patch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(WorkerInspector), "BuildInspectorUI")]
		public static void BuildInspectorUI_Postfix(Worker worker, UIBuilder ui)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			if (!BepisDynamicVariablePowerTools.Mod_Enabled.Value)
			{
				return;
			}
			DynamicVariableSpace val = (DynamicVariableSpace)(object)((worker is DynamicVariableSpace) ? worker : null);
			if (val == null)
			{
				IDynamicVariable val2 = (IDynamicVariable)(object)((worker is IDynamicVariable) ? worker : null);
				if (val2 != null)
				{
					IField<string> nameField = ((Worker)val2).TryGetField<string>("VariableName");
					bool num = val2.IsLinkedToSpace();
					ui.Style.MinHeight = 24f;
					if (num)
					{
						ui.HorizontalLayout(4f, 0f, (Alignment?)null);
						ui.Style.MinWidth = 256f;
						val2.TryGetLinkedSpace(out DynamicVariableSpace linkedSpace);
						LocaleString val3 = LocaleString.op_Implicit($"DynamicVariableSpace: {linkedSpace.SpaceName}");
						ui.Button(ref val3);
						ui.BuildOpenReference<DynamicVariableSpace>(linkedSpace);
						ui.NestOut();
					}
					ui.BuildRenameUI(nameField, delegate(string newName)
					{
						RenameDynamicVariables.RenameDynamicVariable(val2, newName);
					});
				}
				return;
			}
			ui.BuildRenameUI((IField<string>)(object)val.SpaceName, delegate(string newName)
			{
				RenameDirectlyLinkedVariables.RenameSpace(val, newName);
			});
			if (BepisDynamicVariablePowerTools.DebugInfo_Enabled.Value)
			{
				ui.BuildOutputUI(delegate(Sync<string> target)
				{
					DebugInfoGenerator.OutputLinkedVariables(val, target);
				}, delegate(Sync<string> target)
				{
					DebugInfoGenerator.OutputComponentHierarchy(val, target);
				});
			}
		}
	}
}
namespace BepisDynamicVariablePowerTools.Helpers
{
	internal static class BAUIHelper
	{
		private static readonly FieldInfo _refTarget = typeof(RefEditor).GetField("_targetRef", (BindingFlags)36);

		private static readonly MethodInfo _openInspectorButton = typeof(RefEditor).GetMethod("OpenInspectorButton", (BindingFlags)36);

		private static readonly MethodInfo _openWorkerInspectorButton = typeof(RefEditor).GetMethod("OpenWorkerInspectorButton", (BindingFlags)36);

		internal static void BuildRenameUI(this UIBuilder builder, IField<string> nameField, Action<string> onRename)
		{
			//IL_005b: 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_00b0: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected O, but got Unknown
			DestroyOnUserLeave val = ((Component)builder.HorizontalLayout(4f, 0f, (Alignment?)null)).Slot.DestroyWhenLocalUserLeaves();
			UIStyle style = builder.Style;
			style.FlexibleWidth = 1f;
			TextField newNameField = builder.TextField(((IValue<string>)(object)nameField).Value, false, (string)null, false, default(LocaleString));
			((IChangeable)nameField).Changed += ChangedListener;
			((ComponentBase<Component>)(object)val).Destroyed += delegate
			{
				((IChangeable)nameField).Changed -= ChangedListener;
			};
			style.FlexibleWidth = -1f;
			style.MinWidth = 256f;
			LocaleString val2 = LocaleString.op_Implicit("Rename");
			builder.Button(ref val2).LocalPressed += (ButtonEventHandler)delegate
			{
				onRename.Invoke(((SyncField<string>)(object)newNameField.Text.Content).Value);
			};
			builder.NestOut();
			void ChangedListener(object _)
			{
				((SyncField<string>)(object)newNameField.Text.Content).Value = ((IValue<string>)(object)nameField).Value;
			}
		}

		internal static void BuildOutputUI(this UIBuilder builder, Action<Sync<string>> onOutLinkedVars, Action<Sync<string>> onOutCompHierarchy)
		{
			//IL_0039: 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_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			ValueField<string> outputfield = ((ContainerWorker<Component>)(object)builder.Current).AttachComponent<ValueField<string>>(true, (Action<ValueField<string>>)null);
			if (BepisDynamicVariablePowerTools.DebugInfo_LinkedVars.Value)
			{
				LocaleString val = LocaleString.op_Implicit("Output Variable Definitions");
				builder.Button(ref val).LocalPressed += (ButtonEventHandler)delegate
				{
					onOutLinkedVars.Invoke(outputfield.Value);
				};
			}
			if (BepisDynamicVariablePowerTools.DebugInfo_CompHierarchy.Value)
			{
				LocaleString val = LocaleString.op_Implicit("Output Component Hierarchy");
				builder.Button(ref val).LocalPressed += (ButtonEventHandler)delegate
				{
					onOutCompHierarchy.Invoke(outputfield.Value);
				};
			}
			if (!BepisDynamicVariablePowerTools.DebugInfo_OutputInPopoutUI.Value)
			{
				SyncMemberEditorBuilder.Build((ISyncMember)(object)outputfield.Value, "Output", ((Worker)outputfield).GetSyncMemberFieldInfo("Value"), builder, 0.3f);
			}
		}

		internal static ReferenceField<TReference> BuildOpenReference<TReference>(this UIBuilder ui, TReference reference) where TReference : class, IWorldElement
		{
			//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_000d: 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_00bc: Expected O, but got Unknown
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Expected O, but got Unknown
			if (reference == null)
			{
				throw new ArgumentNullException("reference");
			}
			ui.PushStyle();
			ui.Style.FlexibleWidth = -1f;
			ui.Style.MinWidth = 40f;
			LocaleString val = LocaleString.op_Implicit("⤴");
			Button obj = ui.Button(ref val);
			ReferenceField<TReference> val2 = ((ContainerWorker<Component>)(object)((Component)obj).Slot).AttachComponent<ReferenceField<TReference>>(true, (Action<ReferenceField<TReference>>)null);
			val2.Reference.Target = reference;
			RefEditor val3 = ((ContainerWorker<Component>)(object)((Component)obj).Slot).AttachComponent<RefEditor>(true, (Action<RefEditor>)null);
			FieldInfo refTarget = _refTarget;
			ISyncRef val4 = (((SyncRef<ISyncRef>)(object)(RelayRef<ISyncRef>)((refTarget != null) ? refTarget.GetValue((object)val3) : null)).Target = (ISyncRef)(object)val2.Reference);
			obj.Pressed.Target = (ButtonEventHandler)global::System.Delegate.CreateDelegate(typeof(ButtonEventHandler), (object)val3, _openInspectorButton);
			val = LocaleString.op_Implicit("↑");
			ui.Button(ref val).Pressed.Target = (ButtonEventHandler)global::System.Delegate.CreateDelegate(typeof(ButtonEventHandler), (object)val3, _openWorkerInspectorButton);
			ui.PopStyle();
			return val2;
		}
	}
}
namespace BepisDynamicVariablePowerTools.Extensions
{
	internal static class DestroyOnUserLeaveExtensions
	{
		internal static DestroyOnUserLeave DestroyWhenLocalUserLeaves(this Slot slot)
		{
			slot.PersistentSelf = false;
			DestroyOnUserLeave val = Enumerable.FirstOrDefault<DestroyOnUserLeave>((global::System.Collections.Generic.IEnumerable<DestroyOnUserLeave>)((ContainerWorker<Component>)(object)slot).GetComponents<DestroyOnUserLeave>((Predicate<DestroyOnUserLeave>)null, false), (Func<DestroyOnUserLeave, bool>)((DestroyOnUserLeave destroy) => destroy.TargetUser.Target == ((Worker)slot).LocalUser));
			if (val != null)
			{
				return val;
			}
			return DestroyOnUserLeaveExtensions.DestroyWhenUserLeaves(slot, ((Worker)slot).LocalUser);
		}
	}
	public static class DynamicVariableExtensions
	{
		private static readonly FieldInfo _currentDynSpace = typeof(DynamicVariableHandler<dummy>).GetField("_currentSpace", (BindingFlags)36);

		private static readonly FieldInfo handler = typeof(DynamicVariableBase<dummy>).GetField("handler", (BindingFlags)36);

		public static global::System.Collections.Generic.IEnumerable<IDynamicVariable> GetLinkedVariables(this DynamicVariableSpace space, Predicate<IDynamicVariable>? filter = null, bool includeLocal = false, bool excludeDisabled = false, Predicate<Slot>? slotFilter = null)
		{
			if (filter == null)
			{
				filter = Filter;
			}
			return (global::System.Collections.Generic.IEnumerable<IDynamicVariable>)((Component)space).Slot.GetComponentsInChildren<IDynamicVariable>((Predicate<IDynamicVariable>)((IDynamicVariable variable) => variable.IsLinkedToSpace(space) && filter.Invoke(variable)), includeLocal, excludeDisabled, slotFilter);
		}

		public static bool IsLinkedToSpace(this IDynamicVariable dynamicVariable)
		{
			DynamicVariableSpace linkedSpace;
			return dynamicVariable.TryGetLinkedSpace(out linkedSpace);
		}

		public static bool IsLinkedToSpace(this IDynamicVariable dynamicVariable, DynamicVariableSpace space)
		{
			if (dynamicVariable.TryGetLinkedSpace(out DynamicVariableSpace linkedSpace))
			{
				return linkedSpace == space;
			}
			return false;
		}

		public static bool TryGetLinkedSpace(this IDynamicVariable dynamicVariable, [NotNullWhen(true)] out DynamicVariableSpace linkedSpace)
		{
			linkedSpace = Traverse.Create((object)dynamicVariable).Field(((MemberInfo)handler).Name).Field(((MemberInfo)_currentDynSpace).Name)
				.GetValue<DynamicVariableSpace>();
			return linkedSpace != null;
		}

		private static bool Filter(IDynamicVariable variable)
		{
			return true;
		}
	}
}