Decompiled source of Afterimages v2.0.152

rewind.rwafterimages.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Reptile;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: AssemblyCompany("rewind")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("[rw]Afterimages")]
[assembly: AssemblyTitle("rewind.rwafterimages")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[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;
		}
	}
}
internal static class Gscope
{
	public static Player? Player;
}
namespace Plugin
{
	public static class AfterimageManager
	{
		public struct AfterimageStyle
		{
			public readonly Shader? Shader;

			public readonly Texture2D? GradientTexture;

			public readonly float Interval;

			public readonly float Lifetime;

			public readonly float FadeSpeed;

			public readonly int Priority;

			public readonly long Sequence;

			public AfterimageStyle(Shader? shader, Texture2D? gradientTexture = null, float interval = 0.07f, float lifetime = 0.55f, float fadeSpeed = 8f, int priority = 0, long sequence = 0L)
			{
				Shader = shader;
				GradientTexture = gradientTexture;
				Interval = interval;
				Lifetime = lifetime;
				FadeSpeed = fadeSpeed;
				Priority = priority;
				Sequence = sequence;
			}

			public AfterimageStyle WithSequence(long sequence)
			{
				return new AfterimageStyle(Shader, GradientTexture, Interval, Lifetime, FadeSpeed, Priority, sequence);
			}
		}

		private class VisualState
		{
			public readonly Dictionary<string, AfterimageStyle> Requests = new Dictionary<string, AfterimageStyle>();

			public Coroutine? ActiveTrailCoroutine;

			public AfterimageStyle? ActiveStyle;
		}

		private sealed class CapturedRenderer(Renderer renderer, Material[] materials, Mesh mesh)
		{
			public readonly Renderer Renderer = renderer;

			public readonly Material[] Materials = materials;

			public readonly Mesh Mesh = mesh;

			public readonly ShaderParameterBinder[] Binders = Array.ConvertAll(materials, (Material material) => new ShaderParameterBinder(material));
		}

		private sealed class RendererCandidate(Renderer renderer, bool isCharacterMesh, bool isMoveStyleMesh, bool isExcluded)
		{
			public readonly Renderer Renderer = renderer;

			public bool IsCharacterMesh = isCharacterMesh;

			public bool IsMoveStyleMesh = isMoveStyleMesh;

			public readonly bool IsExcluded = isExcluded;
		}

		private sealed class CandidateSet(RendererCandidate[] character, RendererCandidate[] moveStyle)
		{
			public readonly RendererCandidate[] Character = character;

			public readonly RendererCandidate[] MoveStyle = moveStyle;
		}

		private sealed class ActiveAfterimage(GameObject gameObject, List<CapturedRenderer> renderers, Bounds cullBounds)
		{
			public readonly GameObject GameObject = gameObject;

			public readonly List<CapturedRenderer> Renderers = renderers;

			public readonly Bounds CullBounds = cullBounds;

			public LinkedListNode<ActiveAfterimage>? Node;

			public bool IsActive = true;
		}

		private sealed class AfterimageCoroutineRunner : MonoBehaviour
		{
			public Coroutine Run(IEnumerator coroutine)
			{
				return ((MonoBehaviour)this).StartCoroutine(coroutine);
			}
		}

		private const float CullPadding = 0.5f;

		private static readonly Dictionary<CharacterVisual, VisualState> VisualStates = new Dictionary<CharacterVisual, VisualState>();

		private static readonly LinkedList<ActiveAfterimage> ActiveAfterimages = new LinkedList<ActiveAfterimage>();

		private static readonly Dictionary<CharacterVisual, CandidateSet> RendererCandidatesByVisual = new Dictionary<CharacterVisual, CandidateSet>();

		private static readonly List<Renderer> SourceRendererBuffer = new List<Renderer>();

		private static long NextStyleSequence;

		private static readonly Random Rng = new Random();

		private static long NextAfterimageIndex;

		private static int PlayerStateFrame = -1;

		private static bool HasPlayerState;

		private static Vector3 PlayerPos;

		private static Vector3 PlayerSegBottom;

		private static Vector3 PlayerSegTop;

		private static int CameraStateFrame = -1;

		private static bool HasCameraFrustum;

		private static bool WarnedNoCamera;

		private static readonly Plane[] MainCameraFrustum = (Plane[])(object)new Plane[6];

		public static void ReleaseVisual(CharacterVisual? visual)
		{
			if (visual == null)
			{
				return;
			}
			RendererCandidatesByVisual.Remove(visual);
			if (VisualStates.TryGetValue(visual, out VisualState value))
			{
				if ((Object)(object)visual != (Object)null && value.ActiveTrailCoroutine != null)
				{
					((MonoBehaviour)visual).StopCoroutine(value.ActiveTrailCoroutine);
				}
				VisualStates.Remove(visual);
			}
		}

		public static void Clear()
		{
			CharacterVisual[] array = VisualStates.Keys.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				ReleaseVisual(array[i]);
			}
			ActiveAfterimage[] array2 = ActiveAfterimages.ToArray();
			for (int i = 0; i < array2.Length; i++)
			{
				DestroyAfterimage(array2[i]);
			}
			RendererCandidatesByVisual.Clear();
		}

		public static void Request(CharacterVisual visual, string requesterId, bool enabled, AfterimageStyle style = default(AfterimageStyle))
		{
			if ((Object)(object)visual == (Object)null)
			{
				return;
			}
			if (!VisualStates.TryGetValue(visual, out VisualState value))
			{
				value = new VisualState();
				VisualStates[visual] = value;
			}
			if (enabled)
			{
				value.Requests[requesterId] = style.WithSequence(++NextStyleSequence);
			}
			else
			{
				value.Requests.Remove(requesterId);
			}
			AfterimageStyle? afterimageStyle = null;
			foreach (AfterimageStyle value2 in value.Requests.Values)
			{
				if (!afterimageStyle.HasValue || value2.Priority > afterimageStyle.Value.Priority || (value2.Priority == afterimageStyle.Value.Priority && value2.Sequence > afterimageStyle.Value.Sequence))
				{
					afterimageStyle = value2;
				}
			}
			if (!AreStylesEqual(afterimageStyle, value.ActiveStyle))
			{
				value.ActiveStyle = afterimageStyle;
				if (value.ActiveTrailCoroutine != null)
				{
					((MonoBehaviour)visual).StopCoroutine(value.ActiveTrailCoroutine);
					value.ActiveTrailCoroutine = null;
				}
				if ((Object)(object)afterimageStyle?.Shader != (Object)null)
				{
					value.ActiveTrailCoroutine = ((MonoBehaviour)visual).StartCoroutine(TrailRoutine(visual, afterimageStyle.Value));
				}
			}
		}

		private static IEnumerator TrailRoutine(CharacterVisual visual, AfterimageStyle style)
		{
			float interval = Mathf.Max(0.0001f, style.Interval);
			while (true)
			{
				SpawnAfterimage(visual, style);
				yield return (object)new WaitForSeconds(interval);
			}
		}

		private static void RefreshPlayerState()
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: 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_003e: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: 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_008d: 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_009c: 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_00af: 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_00c5: 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)
			if (PlayerStateFrame == Time.frameCount)
			{
				return;
			}
			PlayerStateFrame = Time.frameCount;
			HasPlayerState = false;
			Player player = Gscope.Player;
			if (!((Object)(object)player == (Object)null))
			{
				PlayerPos = (PlayerSegBottom = (PlayerSegTop = ((Component)player).transform.position));
				CharacterVisual characterVisual = player.characterVisual;
				SkinnedMeshRenderer val = (((Object)(object)characterVisual != (Object)null) ? characterVisual.mainRenderer : null);
				if ((Object)(object)val != (Object)null)
				{
					Bounds bounds = ((Renderer)val).bounds;
					PlayerSegBottom = new Vector3(((Bounds)(ref bounds)).center.x, ((Bounds)(ref bounds)).min.y, ((Bounds)(ref bounds)).center.z);
					PlayerSegTop = new Vector3(((Bounds)(ref bounds)).center.x, ((Bounds)(ref bounds)).max.y, ((Bounds)(ref bounds)).center.z);
				}
				HasPlayerState = true;
			}
		}

		private static void SpawnAfterimage(CharacterVisual visual, AfterimageStyle style)
		{
			//IL_0058: 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_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			//IL_0164: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Expected O, but got Unknown
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e6: 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_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: Expected O, but got Unknown
			SkinnedMeshRenderer mainRenderer = visual.mainRenderer;
			Shader shader = style.Shader;
			if ((Object)(object)shader == (Object)null)
			{
				return;
			}
			if (!RendererCandidatesByVisual.TryGetValue(visual, out CandidateSet value))
			{
				List<RendererCandidate> list = DiscoverRendererCandidates(visual, mainRenderer);
				LogRendererCandidates(visual, list);
				value = BuildCandidateSet(list);
				RendererCandidatesByVisual[visual] = value;
			}
			SourceRendererBuffer.Clear();
			Bounds bounds = default(Bounds);
			bool hasBounds = false;
			CollectSources(value.character, ref bounds, ref hasBounds);
			if (Plugin.CFG.CaptureMoveStyleMeshes.Value)
			{
				CollectSources(value.moveStyle, ref bounds, ref hasBounds);
			}
			if (SourceRendererBuffer.Count == 0)
			{
				Debug.LogWarning((object)("[AfterimageManager] No enabled character meshes found for '" + ((Object)visual).name + "'"));
				return;
			}
			((Bounds)(ref bounds)).Expand(1f);
			if (Plugin.CFG.CullOffscreenAfterimages.Value && IsOffscreen(bounds))
			{
				return;
			}
			int num = Math.Max(1, Plugin.CFG.MaxAfterimages.Value);
			while (ActiveAfterimages.Count >= num)
			{
				LinkedListNode<ActiveAfterimage> first = ActiveAfterimages.First;
				if (first == null)
				{
					break;
				}
				DestroyAfterimage(first.Value);
			}
			GameObject val = new GameObject("afterimage");
			List<CapturedRenderer> list2 = new List<CapturedRenderer>(SourceRendererBuffer.Count);
			foreach (Renderer item in SourceRendererBuffer)
			{
				SkinnedMeshRenderer val2 = (SkinnedMeshRenderer)(object)((item is SkinnedMeshRenderer) ? item : null);
				Mesh val3;
				if (val2 != null)
				{
					val3 = new Mesh();
					val2.BakeMesh(val3);
				}
				else
				{
					MeshRenderer val4 = (MeshRenderer)(object)((item is MeshRenderer) ? item : null);
					if (val4 == null)
					{
						continue;
					}
					MeshFilter component = ((Component)val4).GetComponent<MeshFilter>();
					if (component == null || component.sharedMesh == null)
					{
						continue;
					}
					val3 = Object.Instantiate<Mesh>(component.sharedMesh);
				}
				GameObject val5 = new GameObject("afterimage mesh");
				val5.transform.SetParent(val.transform, true);
				val5.transform.SetPositionAndRotation(((Component)item).transform.position, ((Component)item).transform.rotation);
				val5.transform.localScale = ((Component)item).transform.lossyScale;
				val5.AddComponent<MeshFilter>().sharedMesh = val3;
				MeshRenderer val6 = val5.AddComponent<MeshRenderer>();
				Material[] sharedMaterials = item.sharedMaterials;
				Material[] array = (Material[])(object)new Material[Mathf.Max(1, val3.subMeshCount)];
				for (int i = 0; i < array.Length; i++)
				{
					Material val7 = new Material(shader);
					ShaderSettings.Apply(shader, val7);
					Material sourceMaterial = ((sharedMaterials.Length != 0) ? sharedMaterials[Math.Min(i, sharedMaterials.Length - 1)] : null);
					BindCharacterTexture(val7, sourceMaterial);
					array[i] = val7;
				}
				((Renderer)val6).sharedMaterials = array;
				list2.Add(new CapturedRenderer((Renderer)(object)val6, array, val3));
			}
			if (list2.Count == 0)
			{
				Object.Destroy((Object)(object)val);
				return;
			}
			float seed = (float)Rng.NextDouble();
			float index = NextAfterimageIndex++ % 100000;
			ActiveAfterimage activeAfterimage = new ActiveAfterimage(val, list2, bounds);
			activeAfterimage.Node = ActiveAfterimages.AddLast(activeAfterimage);
			IEnumerator enumerator2 = FadeAndDestroy(activeAfterimage, style, seed, index);
			if (Plugin.CFG.FixPersistentAfterimages.Value)
			{
				val.AddComponent<AfterimageCoroutineRunner>().Run(enumerator2);
			}
			else
			{
				((MonoBehaviour)visual).StartCoroutine(enumerator2);
			}
		}

		private static void CollectSources(RendererCandidate[] candidates, ref Bounds bounds, ref bool hasBounds)
		{
			//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_004e: 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)
			for (int i = 0; i < candidates.Length; i++)
			{
				Renderer renderer = candidates[i].renderer;
				if (!((Object)(object)renderer == (Object)null) && renderer.enabled && ((Component)renderer).gameObject.activeInHierarchy)
				{
					SourceRendererBuffer.Add(renderer);
					Bounds bounds2 = renderer.bounds;
					if (hasBounds)
					{
						((Bounds)(ref bounds)).Encapsulate(bounds2);
						continue;
					}
					bounds = bounds2;
					hasBounds = true;
				}
			}
		}

		private static CandidateSet BuildCandidateSet(List<RendererCandidate> discovered)
		{
			List<RendererCandidate> list = new List<RendererCandidate>();
			List<RendererCandidate> list2 = new List<RendererCandidate>();
			foreach (RendererCandidate item in discovered)
			{
				if (!item.isExcluded)
				{
					if (item.isCharacterMesh)
					{
						list.Add(item);
					}
					else if (item.isMoveStyleMesh)
					{
						list2.Add(item);
					}
				}
			}
			return new CandidateSet(list.ToArray(), list2.ToArray());
		}

		private static List<RendererCandidate> DiscoverRendererCandidates(CharacterVisual visual, SkinnedMeshRenderer? mainRenderer)
		{
			Dictionary<Renderer, RendererCandidate> dictionary = new Dictionary<Renderer, RendererCandidate>();
			if ((Object)(object)visual.root != (Object)null)
			{
				AddRendererCandidates(((Component)visual.root).gameObject, visual.root, isCharacterHierarchy: true, isMoveStyleRoot: false, dictionary);
			}
			if ((Object)(object)mainRenderer != (Object)null)
			{
				AddRendererCandidate((Renderer)(object)mainRenderer, mainRenderer != null, isMoveStyleMesh: false, visual.root, dictionary);
			}
			GameObject[] moveStyleRoots = GetMoveStyleRoots(visual.moveStyleProps);
			for (int i = 0; i < moveStyleRoots.Length; i++)
			{
				AddRendererCandidates(moveStyleRoots[i], visual.root, isCharacterHierarchy: false, isMoveStyleRoot: true, dictionary);
			}
			return dictionary.Values.ToList();
		}

		private static GameObject?[] GetMoveStyleRoots(PlayerMoveStyleProps? props)
		{
			if (props == null)
			{
				return Array.Empty<GameObject>();
			}
			return (GameObject?[])(object)new GameObject[11]
			{
				props.bmxFrame, props.bmxHandlebars, props.bmxWheelF, props.bmxWheelR, props.bmxGear, props.bmxPedalL, props.bmxPedalR, props.skateboard, props.skateR, props.skateL,
				props.specialSkateBoard
			};
		}

		private static void LogRendererCandidates(CharacterVisual visual, List<RendererCandidate> candidates)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			Debug.Log((object)$"[AfterimageManager] Renderer candidates discovered for '{((Object)visual).name}' (movestyle: {visual.moveStyle}):");
			foreach (RendererCandidate item in candidates.OrderBy((RendererCandidate candidate) => GetHierarchyPath(((Component)candidate.renderer).transform)))
			{
				Renderer renderer = item.renderer;
				SkinnedMeshRenderer val = (SkinnedMeshRenderer)(object)((renderer is SkinnedMeshRenderer) ? renderer : null);
				Mesh val3;
				if (val == null)
				{
					MeshRenderer val2 = (MeshRenderer)(object)((renderer is MeshRenderer) ? renderer : null);
					if (val2 != null)
					{
						MeshFilter component = ((Component)val2).GetComponent<MeshFilter>();
						val3 = ((component != null) ? component.sharedMesh : null);
					}
					else
					{
						val3 = null;
					}
				}
				else
				{
					val3 = val.sharedMesh;
				}
				Mesh val4 = val3;
				string arg = string.Join(", ", from material in renderer.sharedMaterials
					where (Object)(object)material != (Object)null
					select ((Object)material).name);
				bool flag = Plugin.CFG.CaptureMoveStyleMeshes.Value && item.isMoveStyleMesh;
				Debug.Log((object)("[AfterimageManager] - " + ((object)renderer).GetType().Name + " '" + GetHierarchyPath(((Component)renderer).transform) + "' " + string.Format("(mesh: {0}; submeshes: {1}; ", ((val4 != null) ? ((Object)val4).name : null) ?? "none", (val4 != null) ? val4.subMeshCount : 0) + $"materials: [{arg}]; enabled: {renderer.enabled}; active: {((Component)renderer).gameObject.activeInHierarchy}; " + $"character mesh: {item.isCharacterMesh}; movestyle mesh: {item.isMoveStyleMesh}; " + $"boostpack excluded: {item.isExcluded}; " + $"capture selected: {!item.isExcluded && (item.isCharacterMesh || flag)})"));
			}
		}

		private static void AddRendererCandidates(GameObject? root, Transform? characterRoot, bool isCharacterHierarchy, bool isMoveStyleRoot, Dictionary<Renderer, RendererCandidate> detected)
		{
			if (!((Object)(object)root == (Object)null))
			{
				Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true);
				foreach (Renderer val in componentsInChildren)
				{
					AddRendererCandidate(val, isCharacterHierarchy && val is SkinnedMeshRenderer, isMoveStyleRoot && (val is SkinnedMeshRenderer || val is MeshRenderer), characterRoot, detected);
				}
			}
		}

		private static void AddRendererCandidate(Renderer renderer, bool isCharacterMesh, bool isMoveStyleMesh, Transform? characterRoot, Dictionary<Renderer, RendererCandidate> detected)
		{
			if (detected.TryGetValue(renderer, out RendererCandidate value))
			{
				value.isCharacterMesh |= isCharacterMesh;
				value.isMoveStyleMesh |= isMoveStyleMesh;
			}
			else
			{
				detected.Add(renderer, new RendererCandidate(renderer, isCharacterMesh, isMoveStyleMesh, IsWithinJetpackBoostPath(((Component)renderer).transform, characterRoot)));
			}
		}

		private static string GetHierarchyPath(Transform transform)
		{
			string text = ((Object)transform).name;
			while ((Object)(object)transform.parent != (Object)null)
			{
				transform = transform.parent;
				text = ((Object)transform).name + "/" + text;
			}
			return text;
		}

		private static bool IsWithinJetpackBoostPath(Transform rendererTransform, Transform? characterRoot)
		{
			Transform val = rendererTransform;
			while ((Object)(object)val != (Object)null)
			{
				if (IsNamed(val, "boost") && IsNamed(val.parent, "boostPos"))
				{
					Transform parent = val.parent;
					if (IsNamed((parent != null) ? parent.parent : null, "jetpack"))
					{
						Transform parent2 = val.parent;
						object transform;
						if (parent2 == null)
						{
							transform = null;
						}
						else
						{
							Transform parent3 = parent2.parent;
							transform = ((parent3 != null) ? parent3.parent : null);
						}
						if (IsNamed((Transform?)transform, "jetpackPos"))
						{
							return true;
						}
					}
				}
				if ((Object)(object)val == (Object)(object)characterRoot)
				{
					break;
				}
				val = val.parent;
			}
			return false;
		}

		private static bool IsNamed(Transform? transform, string expectedName)
		{
			if ((Object)(object)transform == (Object)null)
			{
				return false;
			}
			return string.Equals(((Object)transform).name.Replace("(Clone)", string.Empty), expectedName, StringComparison.OrdinalIgnoreCase);
		}

		private static void BindCharacterTexture(Material material, Material? sourceMaterial)
		{
			//IL_003e: 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)
			if (material.HasProperty("_CharacterTex") && !((Object)(object)sourceMaterial == (Object)null) && !((Object)(object)sourceMaterial.mainTexture == (Object)null))
			{
				material.SetTexture("_CharacterTex", sourceMaterial.mainTexture);
				material.SetTextureScale("_CharacterTex", sourceMaterial.mainTextureScale);
				material.SetTextureOffset("_CharacterTex", sourceMaterial.mainTextureOffset);
			}
		}

		private static IEnumerator FadeAndDestroy(ActiveAfterimage afterimage, AfterimageStyle style, float seed, float index)
		{
			foreach (CapturedRenderer renderer in afterimage.renderers)
			{
				ShaderParameterBinder[] binders = renderer.Binders;
				foreach (ShaderParameterBinder shaderParameterBinder in binders)
				{
					if ((Object)(object)style.GradientTexture != (Object)null)
					{
						shaderParameterBinder.BindTexture((Texture)(object)style.GradientTexture);
					}
					shaderParameterBinder.BindSpawnInfo(style.Lifetime, style.FadeSpeed, seed, index);
				}
			}
			float elapsed = 0f;
			while (afterimage.IsActive)
			{
				if (!Plugin.CFG.CullOffscreenAfterimages.Value || !IsOffscreen(afterimage.cullBounds))
				{
					float fadeProgress = ((style.Lifetime > 0f) ? Mathf.Clamp01(elapsed / style.Lifetime) : 1f);
					RefreshPlayerState();
					foreach (CapturedRenderer renderer2 in afterimage.renderers)
					{
						ShaderParameterBinder[] binders = renderer2.Binders;
						foreach (ShaderParameterBinder shaderParameterBinder2 in binders)
						{
							shaderParameterBinder2.BindFadeProgress(fadeProgress);
							shaderParameterBinder2.BindAge(elapsed);
							if (HasPlayerState)
							{
								shaderParameterBinder2.BindPlayer(PlayerPos, PlayerSegBottom, PlayerSegTop);
							}
						}
					}
				}
				if (elapsed >= style.Lifetime)
				{
					break;
				}
				yield return null;
				elapsed += Time.deltaTime;
			}
			DestroyAfterimage(afterimage);
		}

		private static void DestroyAfterimage(ActiveAfterimage afterimage)
		{
			if (!afterimage.IsActive)
			{
				return;
			}
			afterimage.IsActive = false;
			if (afterimage.Node != null)
			{
				ActiveAfterimages.Remove(afterimage.Node);
				afterimage.Node = null;
			}
			foreach (CapturedRenderer renderer in afterimage.renderers)
			{
				Material[] materials = renderer.materials;
				for (int i = 0; i < materials.Length; i++)
				{
					Object.Destroy((Object)(object)materials[i]);
				}
				renderer.mesh.Clear();
				Object.Destroy((Object)(object)renderer.mesh);
			}
			Object.Destroy((Object)(object)afterimage.gameObject);
		}

		private static bool RefreshCameraState()
		{
			if (CameraStateFrame == Time.frameCount)
			{
				return HasCameraFrustum;
			}
			CameraStateFrame = Time.frameCount;
			Camera main = Camera.main;
			if ((Object)(object)main != (Object)null)
			{
				GeometryUtility.CalculateFrustumPlanes(main, MainCameraFrustum);
				HasCameraFrustum = true;
				return true;
			}
			HasCameraFrustum = false;
			if (!WarnedNoCamera)
			{
				WarnedNoCamera = true;
				Debug.LogWarning((object)"[AfterimageManager] Camera.main is null; offscreen culling is inactive until one exists");
			}
			return false;
		}

		private static bool IsOffscreen(Bounds bounds)
		{
			//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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			//IL_0035: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: 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_0079: 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_0087: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			if (!RefreshCameraState())
			{
				return false;
			}
			Vector3 center = ((Bounds)(ref bounds)).center;
			Vector3 extents = ((Bounds)(ref bounds)).extents;
			for (int i = 0; i < MainCameraFrustum.Length; i++)
			{
				Plane val = MainCameraFrustum[i];
				Vector3 normal = ((Plane)(ref val)).normal;
				float num = extents.x * Mathf.Abs(normal.x) + extents.y * Mathf.Abs(normal.y) + extents.z * Mathf.Abs(normal.z);
				if (normal.x * center.x + normal.y * center.y + normal.z * center.z + ((Plane)(ref val)).distance < 0f - num)
				{
					return true;
				}
			}
			return false;
		}

		private static bool AreStylesEqual(AfterimageStyle? a, AfterimageStyle? b)
		{
			if (!a.HasValue && !b.HasValue)
			{
				return true;
			}
			if (!a.HasValue || !b.HasValue)
			{
				return false;
			}
			if ((Object)(object)a.Value.Shader == (Object)(object)b.Value.Shader && (Object)(object)a.Value.GradientTexture == (Object)(object)b.Value.GradientTexture && Mathf.Approximately(a.Value.Interval, b.Value.Interval) && Mathf.Approximately(a.Value.Lifetime, b.Value.Lifetime) && Mathf.Approximately(a.Value.FadeSpeed, b.Value.FadeSpeed))
			{
				return a.Value.Priority == b.Value.Priority;
			}
			return false;
		}
	}
	public class Config
	{
		public class MovementStateConfig
		{
			public ConfigEntry<bool> Enabled { get; }

			public ConfigEntry<string> ShaderName { get; }

			public ConfigEntry<string> GradientTextureFile { get; }

			public ConfigEntry<float> FadeSpeed { get; }

			public ConfigEntry<float> Interval { get; }

			public ConfigEntry<float> Lifetime { get; }

			public ConfigEntry<int> Priority { get; }

			public AfterimageManager.AfterimageStyle CurrentData { get; private set; }

			public MovementStateConfig(ConfigFile config, string name, bool enabled, string shaderName, float interval, float lifetime, float fadeSpeed, int priority)
			{
				string text = "Afterimage: " + name;
				Enabled = config.Bind<bool>(text, "Enabled", enabled, "Enable this state");
				ShaderName = config.Bind<string>(text, "ShaderName", shaderName, "ShaderLab name from a .shaderbundle, or a built-in Unity shader. No afterimages appear if it isn't found.");
				GradientTextureFile = config.Bind<string>(text, "GradientTextureFile", "Default.png", "Texture file for the shader. Searches the config folder, then the plugin's gradients folder. Leave blank for none.");
				FadeSpeed = config.Bind<float>(text, "FadeSpeed", fadeSpeed, "Fade curve exponent. Former presets: Linear = 1, Smooth = 2, FastStart = 4, SlowStart = 0.5. Higher values fade faster at first; lower values fade slower.");
				Interval = config.Bind<float>(text, "Interval", interval, "Time between afterimages");
				Lifetime = config.Bind<float>(text, "Lifetime", lifetime, "Afterimage lifetime");
				Priority = config.Bind<int>(text, "Priority", priority, "Higher values take precedence");
				UpdateCurrentData();
				ConfigEntryBase[] array = (ConfigEntryBase[])(object)new ConfigEntryBase[7]
				{
					(ConfigEntryBase)Enabled,
					(ConfigEntryBase)ShaderName,
					(ConfigEntryBase)GradientTextureFile,
					(ConfigEntryBase)FadeSpeed,
					(ConfigEntryBase)Interval,
					(ConfigEntryBase)Lifetime,
					(ConfigEntryBase)Priority
				};
				foreach (ConfigEntryBase entry in array)
				{
					entry.ConfigFile.SettingChanged += delegate(object _, SettingChangedEventArgs e)
					{
						if (e.ChangedSetting == entry)
						{
							UpdateCurrentData();
						}
					};
				}
			}

			internal void UpdateCurrentData()
			{
				Shader shader = ShaderManager.GetShader(ShaderName.Value);
				Texture2D texture = TextureManager.GetTexture(GradientTextureFile.Value);
				CurrentData = new AfterimageManager.AfterimageStyle(shader, texture, Interval.Value, Lifetime.Value, Math.Max(0.01f, FadeSpeed.Value), Priority.Value, 0L);
			}
		}

		public MovementStateConfig staticaf;

		public MovementStateConfig speed;

		public MovementStateConfig boost;

		public MovementStateConfig trick;

		public MovementStateConfig boosttrick;

		public MovementStateConfig airtrick;

		public MovementStateConfig airboosttrick;

		public MovementStateConfig slidenormal;

		public MovementStateConfig slideslope;

		public MovementStateConfig slidesuper;

		public MovementStateConfig airDash;

		public MovementStateConfig grindnormal;

		public MovementStateConfig grindtrick;

		public MovementStateConfig grindboosttrick;

		public MovementStateConfig grindcorner;

		public ConfigEntry<float> SpeedThreshold { get; }

		public ConfigEntry<bool> FixPersistentAfterimages { get; }

		public ConfigEntry<bool> CaptureMoveStyleMeshes { get; }

		public ConfigEntry<bool> CullOffscreenAfterimages { get; }

		public ConfigEntry<int> MaxAfterimages { get; }

		public static string ConfigDirectory => Path.Combine(Paths.ConfigPath, "rewind.rwafterimages");

		public Config(ConfigFile config)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			EnsureConfigDirectory();
			SpeedThreshold = config.Bind<float>("Afterimage: Speed", "ActivationSpeed", 32f, "Minimum speed (world units/s) for the Speed state");
			FixPersistentAfterimages = config.Bind<bool>("Afterimages", "FixPersistentAfterimages", true, "Keep afterimages expiring when their source character visual is destroyed");
			CaptureMoveStyleMeshes = config.Bind<bool>("Afterimages", "CaptureMoveStyleMeshes", false, "Include enabled movestyle prop renderers in afterimages");
			CullOffscreenAfterimages = config.Bind<bool>("Optimization", "CullOffscreenAfterimages", false, "Destroy afterimages outside the main camera view");
			MaxAfterimages = config.Bind<int>("Optimization", "MaxAfterimages", 500, new ConfigDescription("Maximum number of active afterimages; the oldest are removed first.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10000), Array.Empty<object>()));
			staticaf = new MovementStateConfig(config, "Static", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 0);
			speed = new MovementStateConfig(config, "Speed", enabled: false, "Afterimage/Default", 0.045f, 0.55f, 1f, 1);
			boost = new MovementStateConfig(config, "Boost", enabled: true, "Afterimage/Default", 0.07f, 0.7f, 1f, 1);
			trick = new MovementStateConfig(config, "Trick", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 3);
			boosttrick = new MovementStateConfig(config, "Trick (Boost)", enabled: true, "Afterimage/Default", 0.07f, 0.65f, 1f, 4);
			airtrick = new MovementStateConfig(config, "Air Trick", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 3);
			airboosttrick = new MovementStateConfig(config, "Air Trick (Boost)", enabled: true, "Afterimage/Default", 0.07f, 0.65f, 1f, 4);
			slidenormal = new MovementStateConfig(config, "Slide (Normal)", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 2);
			slideslope = new MovementStateConfig(config, "Slide (Slope)", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 2);
			slidesuper = new MovementStateConfig(config, "Slide (Super)", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 2);
			airDash = new MovementStateConfig(config, "Air Dash", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 5);
			grindnormal = new MovementStateConfig(config, "Grind (Normal)", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 6);
			grindtrick = new MovementStateConfig(config, "Grind Trick", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 7);
			grindboosttrick = new MovementStateConfig(config, "Grind Trick (Boost)", enabled: true, "Afterimage/Default", 0.07f, 0.65f, 1f, 8);
			grindcorner = new MovementStateConfig(config, "Grind Corner", enabled: false, "Afterimage/Default", 0.07f, 0.55f, 1f, 9);
		}

		private static void EnsureConfigDirectory()
		{
			Directory.CreateDirectory(ConfigDirectory);
		}
	}
	[BepInPlugin("rewind.rwafterimages", "[rw]Afterimages", "1.0.0")]
	[BepInProcess("Bomb Rush Cyberfunk.exe")]
	public class Plugin : BaseUnityPlugin
	{
		public static Harmony harmony { get; private set; }

		public static Config CFG { get; private set; }

		public static string? PluginDirectory { get; private set; }

		private void Awake()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			PluginDirectory = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			ShaderSettings.Initialize(((BaseUnityPlugin)this).Config);
			ShaderManager.Initialize(PluginDirectory);
			CFG = new Config(((BaseUnityPlugin)this).Config);
			harmony = new Harmony("rewind.rwafterimages");
			harmony.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"v1.0.0 loaded :3");
		}

		private void OnDestroy()
		{
			AfterimageManager.Clear();
			ShaderManager.ClearCache();
			TextureManager.ClearCache();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin unloaded");
		}
	}
	public static class ShaderManager
	{
		public const string BundlePattern = "*.shaderbundle";

		private static readonly Dictionary<string, Shader> ShaderLookup = new Dictionary<string, Shader>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, AssetBundle> LoadedBundles = new Dictionary<string, AssetBundle>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, string> LoadedBundlePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, string> ShaderOrigin = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> WarnedDuplicates = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> FailedBundles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static string? pluginDirectory;

		public static void Initialize(string? pluginDir)
		{
			pluginDirectory = pluginDir;
			ScanForBundles();
		}

		public static Shader? GetShader(string shaderName)
		{
			if (string.IsNullOrWhiteSpace(shaderName))
			{
				return null;
			}
			shaderName = shaderName.Trim();
			if (TryResolve(shaderName, out Shader shader))
			{
				return shader;
			}
			ScanForBundles();
			if (TryResolve(shaderName, out shader))
			{
				return shader;
			}
			return null;
		}

		private static bool TryResolve(string name, out Shader? shader)
		{
			if (ShaderLookup.TryGetValue(name, out Shader value) && (Object)(object)value != (Object)null)
			{
				shader = value;
				return true;
			}
			Shader val = Shader.Find(name);
			if ((Object)(object)val != (Object)null)
			{
				shader = val;
				return true;
			}
			shader = null;
			return false;
		}

		public static void ScanForBundles()
		{
			ScanDirectory(Config.ConfigDirectory);
			ScanDirectory(pluginDirectory);
			ScanDirectory(Paths.PluginPath);
		}

		private static void ScanDirectory(string? directory)
		{
			if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
			{
				string[] files;
				try
				{
					files = Directory.GetFiles(directory, "*.shaderbundle", SearchOption.AllDirectories);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("[ShaderManager] Could not list '" + directory + "': " + ex.Message));
					return;
				}
				Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
				string[] array = files;
				for (int i = 0; i < array.Length; i++)
				{
					LoadBundle(array[i]);
				}
			}
		}

		private static void LoadBundle(string path)
		{
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			string fileName = Path.GetFileName(path);
			if (FailedBundles.Contains(path))
			{
				return;
			}
			if (LoadedBundlePaths.TryGetValue(fileName, out string value))
			{
				if (!string.Equals(value, path, StringComparison.OrdinalIgnoreCase) && WarnedDuplicates.Add(path))
				{
					Debug.LogWarning((object)("[ShaderManager] Skipping '" + path + "': a bundle named '" + fileName + "' is already loaded from '" + value + "'. Rename one of them."));
				}
				return;
			}
			AssetBundle val;
			try
			{
				val = AssetBundle.LoadFromFile(path);
			}
			catch (Exception ex)
			{
				FailedBundles.Add(path);
				Debug.LogError((object)("[ShaderManager] Exception while loading bundle '" + path + "': " + ex.Message));
				return;
			}
			if ((Object)(object)val == (Object)null)
			{
				FailedBundles.Add(path);
				Debug.LogError((object)("[ShaderManager] Failed to load bundle '" + path + "'. Check its Unity version and platform (StandaloneWindows64); a bundle with the same name may already be loaded."));
				return;
			}
			LoadedBundles[fileName] = val;
			LoadedBundlePaths[fileName] = path;
			List<string> list = new List<string>();
			string[] allAssetNames = val.GetAllAssetNames();
			foreach (string text in allAssetNames)
			{
				if (!text.EndsWith(".shader", StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				Shader val2 = val.LoadAsset<Shader>(text);
				if (!((Object)(object)val2 == (Object)null))
				{
					((Object)val2).hideFlags = (HideFlags)(((Object)val2).hideFlags | 0x20);
					RegisterShader(val2, fileName);
					list.Add(((Object)val2).name);
					ShaderSettings.Register(val2);
					if (!val2.isSupported)
					{
						Debug.LogWarning((object)("[ShaderManager] Shader '" + ((Object)val2).name + "' in '" + fileName + "' is not supported on this GPU/platform (or it failed to compile). It will render pink or not at all."));
					}
				}
			}
			if (list.Count == 0)
			{
				Debug.LogWarning((object)("[ShaderManager] Bundle '" + fileName + "' loaded but contains no shaders."));
			}
			else
			{
				Debug.Log((object)string.Format("[ShaderManager] Loaded {0} shader(s) from '{1}': {2}", list.Count, fileName, string.Join(", ", list)));
			}
		}

		private static void RegisterShader(Shader shader, string bundleName)
		{
			string name = ((Object)shader).name;
			if (ShaderLookup.TryGetValue(name, out Shader value) && (Object)(object)value != (Object)null && (Object)(object)value != (Object)(object)shader)
			{
				if (WarnedDuplicates.Add(name + "|" + bundleName))
				{
					Debug.LogWarning((object)("[ShaderManager] Shader name '" + name + "' in '" + bundleName + "' is already provided by '" + ShaderOrigin[name] + "'; the first one is used. Rename the ShaderLab name to use both."));
				}
			}
			else
			{
				ShaderLookup[name] = shader;
				ShaderOrigin[name] = bundleName;
			}
		}

		public static void ClearCache()
		{
			foreach (AssetBundle value in LoadedBundles.Values)
			{
				if (value != null)
				{
					value.Unload(false);
				}
			}
			LoadedBundles.Clear();
			LoadedBundlePaths.Clear();
			ShaderOrigin.Clear();
			WarnedDuplicates.Clear();
			FailedBundles.Clear();
			ShaderLookup.Clear();
		}
	}
	public class ShaderParameterBinder
	{
		private Material _material;

		public ShaderParameterBinder(Material material)
		{
			_material = material;
		}

		public void SetMaterial(Material material)
		{
			_material = material;
		}

		public void BindTexture(Texture texture)
		{
			if ((Object)(object)_material != (Object)null && (Object)(object)texture != (Object)null)
			{
				_material.SetTexture("_MainTex", texture);
			}
		}

		public void BindFadeProgress(float fadeProgress)
		{
			if ((Object)(object)_material != (Object)null)
			{
				_material.SetFloat("_FadeProgress", Mathf.Clamp01(fadeProgress));
			}
		}

		public void BindFloat(string propertyName, float value)
		{
			if ((Object)(object)_material != (Object)null && !string.IsNullOrWhiteSpace(propertyName))
			{
				_material.SetFloat(propertyName, value);
			}
		}

		public void BindColor(string propertyName, Color color)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_material != (Object)null && !string.IsNullOrWhiteSpace(propertyName))
			{
				_material.SetColor(propertyName, color);
			}
		}

		public void BindCustomTexture(string propertyName, Texture texture)
		{
			if ((Object)(object)_material != (Object)null && !string.IsNullOrWhiteSpace(propertyName) && (Object)(object)texture != (Object)null)
			{
				_material.SetTexture(propertyName, texture);
			}
		}

		public void BindVector(string propertyName, Vector4 value)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_material != (Object)null && !string.IsNullOrWhiteSpace(propertyName))
			{
				_material.SetVector(propertyName, value);
			}
		}

		public void BindStandardParameters(Texture? gradientTexture, float fadeProgress)
		{
			if (!((Object)(object)_material == (Object)null))
			{
				if ((Object)(object)gradientTexture != (Object)null)
				{
					BindTexture(gradientTexture);
				}
				BindFadeProgress(fadeProgress);
			}
		}

		public void BindPlayer(Vector3 position, Vector3 segmentBottom, Vector3 segmentTop)
		{
			//IL_001a: 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_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_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_material == (Object)null))
			{
				_material.SetVector("_PlayerWorldPos", Vector4.op_Implicit(position));
				_material.SetVector("_PlayerSegA", Vector4.op_Implicit(segmentBottom));
				_material.SetVector("_PlayerSegB", Vector4.op_Implicit(segmentTop));
			}
		}

		public void BindAge(float seconds)
		{
			if ((Object)(object)_material != (Object)null)
			{
				_material.SetFloat("_Age", seconds);
			}
		}

		public void BindSpawnInfo(float lifetime, float fadeSpeed, float seed, float index)
		{
			if (!((Object)(object)_material == (Object)null))
			{
				_material.SetFloat("_Lifetime", lifetime);
				_material.SetFloat("_FadeSpeed", fadeSpeed);
				_material.SetFloat("_Seed", seed);
				_material.SetFloat("_Index", index);
			}
		}
	}
	public static class ShaderSettings
	{
		private enum Kind
		{
			Float,
			Toggle,
			ColorHex,
			Vector
		}

		private sealed class Setting
		{
			public string PropertyName = "";

			public Kind Kind;

			public ConfigEntry<float>? FloatEntry;

			public ConfigEntry<bool>? ToggleEntry;

			public ConfigEntry<string>? TextEntry;

			public float FloatValue;

			public Color ColorValue;

			public Vector4 VectorValue;

			public void Refresh()
			{
				//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_00e1: 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)
				switch (Kind)
				{
				case Kind.Float:
					if (FloatEntry != null)
					{
						FloatValue = FloatEntry.Value;
					}
					break;
				case Kind.Toggle:
					if (ToggleEntry != null)
					{
						FloatValue = (ToggleEntry.Value ? 1f : 0f);
					}
					break;
				case Kind.ColorHex:
				{
					Color colorValue = default(Color);
					if (TextEntry != null && ColorUtility.TryParseHtmlString("#" + TextEntry.Value.Trim().TrimStart(new char[1] { '#' }), ref colorValue))
					{
						ColorValue = colorValue;
					}
					else
					{
						Debug.LogWarning((object)("[ShaderSettings] '" + PropertyName + "': expected a colour like 4DA6FFCC, keeping the previous value."));
					}
					break;
				}
				case Kind.Vector:
				{
					if (TextEntry != null && TryParseVector(TextEntry.Value, out var result))
					{
						VectorValue = result;
					}
					else
					{
						Debug.LogWarning((object)("[ShaderSettings] '" + PropertyName + "': expected up to four numbers like 1, 0.5, 0, 1, keeping the previous value."));
					}
					break;
				}
				}
			}
		}

		private static readonly HashSet<string> PluginDriven = new HashSet<string>(StringComparer.Ordinal)
		{
			"_MainTex", "_FadeProgress", "_Age", "_Lifetime", "_FadeSpeed", "_AfterimageTime", "_Seed", "_Index", "_PlayerWorldPos", "_PlayerSegA",
			"_PlayerSegB"
		};

		private static readonly Dictionary<Shader, List<Setting>> Registered = new Dictionary<Shader, List<Setting>>();

		private static readonly Dictionary<ConfigEntryBase, Setting> ByEntry = new Dictionary<ConfigEntryBase, Setting>();

		private static ConfigFile? configFile;

		public static void Initialize(ConfigFile config)
		{
			if (configFile != null)
			{
				return;
			}
			configFile = config;
			configFile.SettingChanged += delegate(object _, SettingChangedEventArgs e)
			{
				if (e.ChangedSetting != null && ByEntry.TryGetValue(e.ChangedSetting, out Setting value))
				{
					value.Refresh();
				}
			};
		}

		public static void Register(Shader shader)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: 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_00f0: Expected I4, but got Unknown
			//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0203: Unknown result type (might be due to invalid IL or missing references)
			//IL_0205: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: 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_01bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Expected O, but got Unknown
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_024e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			if (configFile == null || (Object)(object)shader == (Object)null || Registered.ContainsKey(shader))
			{
				return;
			}
			List<Setting> list = new List<Setting>();
			Registered[shader] = list;
			string text = "Shader: " + ((Object)shader).name;
			HashSet<string> used = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			bool saveOnConfigSet = configFile.SaveOnConfigSet;
			configFile.SaveOnConfigSet = false;
			try
			{
				int propertyCount = shader.GetPropertyCount();
				Color val = default(Color);
				for (int i = 0; i < propertyCount; i++)
				{
					string propertyName = shader.GetPropertyName(i);
					if (PluginDriven.Contains(propertyName))
					{
						continue;
					}
					ShaderPropertyFlags propertyFlags = shader.GetPropertyFlags(i);
					if ((propertyFlags & 1) != 0)
					{
						continue;
					}
					string text2 = MakeKey(shader.GetPropertyDescription(i), propertyName, used);
					string text3 = "Shader property " + propertyName;
					Setting setting = new Setting
					{
						PropertyName = propertyName
					};
					ShaderPropertyType propertyType = shader.GetPropertyType(i);
					switch ((int)propertyType)
					{
					case 2:
					{
						float propertyDefaultFloatValue = shader.GetPropertyDefaultFloatValue(i);
						if (HasToggleAttribute(shader, i))
						{
							setting.Kind = Kind.Toggle;
							setting.ToggleEntry = configFile.Bind<bool>(text, text2, propertyDefaultFloatValue != 0f, text3);
							ByEntry[(ConfigEntryBase)(object)setting.ToggleEntry] = setting;
						}
						else
						{
							setting.Kind = Kind.Float;
							setting.FloatEntry = configFile.Bind<float>(text, text2, propertyDefaultFloatValue, text3);
							ByEntry[(ConfigEntryBase)(object)setting.FloatEntry] = setting;
						}
						break;
					}
					case 3:
					{
						Vector2 propertyRangeLimits = shader.GetPropertyRangeLimits(i);
						setting.Kind = Kind.Float;
						setting.FloatEntry = configFile.Bind<float>(text, text2, Mathf.Clamp(shader.GetPropertyDefaultFloatValue(i), propertyRangeLimits.x, propertyRangeLimits.y), new ConfigDescription(text3, (AcceptableValueBase)(object)new AcceptableValueRange<float>(propertyRangeLimits.x, propertyRangeLimits.y), Array.Empty<object>()));
						ByEntry[(ConfigEntryBase)(object)setting.FloatEntry] = setting;
						break;
					}
					case 0:
					{
						Vector4 propertyDefaultVectorValue = shader.GetPropertyDefaultVectorValue(i);
						if ((propertyFlags & 0x10) != 0)
						{
							setting.Kind = Kind.Vector;
							setting.TextEntry = configFile.Bind<string>(text, text2, FormatVector(propertyDefaultVectorValue), text3 + " (HDR colour as r, g, b, a: values above 1 are allowed)");
						}
						else
						{
							setting.Kind = Kind.ColorHex;
							((Color)(ref val))..ctor(propertyDefaultVectorValue.x, propertyDefaultVectorValue.y, propertyDefaultVectorValue.z, propertyDefaultVectorValue.w);
							setting.TextEntry = configFile.Bind<string>(text, text2, ColorUtility.ToHtmlStringRGBA(val), text3 + " (colour as RRGGBBAA hex)");
						}
						ByEntry[(ConfigEntryBase)(object)setting.TextEntry] = setting;
						break;
					}
					case 1:
						setting.Kind = Kind.Vector;
						setting.TextEntry = configFile.Bind<string>(text, text2, FormatVector(shader.GetPropertyDefaultVectorValue(i)), text3 + " (x, y, z, w)");
						ByEntry[(ConfigEntryBase)(object)setting.TextEntry] = setting;
						break;
					default:
						continue;
					}
					setting.Refresh();
					list.Add(setting);
				}
			}
			finally
			{
				configFile.SaveOnConfigSet = saveOnConfigSet;
				if (saveOnConfigSet)
				{
					configFile.Save();
				}
			}
		}

		public static void Apply(Shader shader, Material material)
		{
			//IL_0083: 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)
			if ((Object)(object)shader == (Object)null || (Object)(object)material == (Object)null || !Registered.TryGetValue(shader, out List<Setting> value))
			{
				return;
			}
			foreach (Setting item in value)
			{
				switch (item.Kind)
				{
				case Kind.Float:
					material.SetFloat(item.PropertyName, item.FloatValue);
					break;
				case Kind.Toggle:
					material.SetFloat(item.PropertyName, item.FloatValue);
					break;
				case Kind.ColorHex:
					material.SetColor(item.PropertyName, item.ColorValue);
					break;
				case Kind.Vector:
					material.SetVector(item.PropertyName, item.VectorValue);
					break;
				}
			}
		}

		private static bool HasToggleAttribute(Shader shader, int propertyIndex)
		{
			string[] propertyAttributes = shader.GetPropertyAttributes(propertyIndex);
			foreach (string text in propertyAttributes)
			{
				if (text == "Toggle" || text.StartsWith("Toggle ", StringComparison.Ordinal) || text.StartsWith("Toggle(", StringComparison.Ordinal))
				{
					return true;
				}
			}
			return false;
		}

		private static string MakeKey(string? description, string propertyName, HashSet<string> used)
		{
			string text = Sanitize(description);
			if (text.Length == 0)
			{
				text = propertyName;
			}
			if (!used.Add(text))
			{
				text = text + " (" + propertyName + ")";
				used.Add(text);
			}
			return text;
		}

		private static string Sanitize(string? text)
		{
			if (string.IsNullOrWhiteSpace(text))
			{
				return "";
			}
			List<char> list = new List<char>(text.Length);
			foreach (char c in text)
			{
				if (c != '=' && c != '\n' && c != '\r' && c != '\t' && c != '\\' && c != '"' && c != '\'' && c != '[' && c != ']')
				{
					list.Add(c);
				}
			}
			return new string(list.ToArray()).Trim();
		}

		private static string FormatVector(Vector4 v)
		{
			CultureInfo invariantCulture = CultureInfo.InvariantCulture;
			return string.Format(invariantCulture, "{0}, {1}, {2}, {3}", v.x.ToString("0.###", invariantCulture), v.y.ToString("0.###", invariantCulture), v.z.ToString("0.###", invariantCulture), v.w.ToString("0.###", invariantCulture));
		}

		private static bool TryParseVector(string text, out Vector4 result)
		{
			//IL_0001: 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_006e: Unknown result type (might be due to invalid IL or missing references)
			result = default(Vector4);
			string[] array = text.Split(new char[1] { ',' });
			if (array.Length == 0 || array.Length > 4)
			{
				return false;
			}
			float[] array2 = new float[4];
			for (int i = 0; i < array.Length; i++)
			{
				if (!float.TryParse(array[i].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out array2[i]))
				{
					return false;
				}
			}
			result = new Vector4(array2[0], array2[1], array2[2], array2[3]);
			return true;
		}
	}
	public static class TextureManager
	{
		private static readonly Dictionary<string, Texture2D?> TextureCache = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);

		private static readonly LinkedList<string> AccessOrder = new LinkedList<string>();

		private const int MaxCacheSize = 50;

		public static Texture2D? GetTexture(string fileName)
		{
			if (string.IsNullOrWhiteSpace(fileName))
			{
				return null;
			}
			if (TextureCache.TryGetValue(fileName, out Texture2D value))
			{
				LinkedListNode<string> linkedListNode = AccessOrder.Find(fileName);
				if (linkedListNode != null)
				{
					AccessOrder.Remove(linkedListNode);
					AccessOrder.AddLast(fileName);
				}
				return value;
			}
			Texture2D val = LoadTextureFromDisk(fileName);
			TextureCache[fileName] = val;
			AccessOrder.AddLast(fileName);
			EvictLRUIfNeeded();
			return val;
		}

		private static Texture2D? LoadTextureFromDisk(string fileName)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			string text = ResolvePath(fileName);
			if (text == null)
			{
				Debug.LogWarning((object)("[TextureManager] Texture file '" + fileName + "' not found in the config folder or the plugin's gradients folder."));
				return null;
			}
			try
			{
				byte[] array = File.ReadAllBytes(text);
				Texture2D val = new Texture2D(1, 1, (TextureFormat)4, false);
				if (!ImageConversion.LoadImage(val, array))
				{
					Object.DestroyImmediate((Object)(object)val);
					Debug.LogError((object)("[TextureManager] Failed to load texture: " + text));
					return null;
				}
				((Object)val).name = Path.GetFileName(text);
				((Texture)val).wrapMode = (TextureWrapMode)1;
				return val;
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("[TextureManager] Error loading texture '" + fileName + "': " + ex.Message));
				return null;
			}
		}

		private static IEnumerable<string> SearchDirectories()
		{
			yield return Config.ConfigDirectory;
			string pluginDir = Plugin.PluginDirectory;
			if (!string.IsNullOrEmpty(pluginDir))
			{
				yield return Path.Combine(pluginDir, "gradients");
				yield return pluginDir;
			}
		}

		private static string? ResolvePath(string fileName)
		{
			foreach (string item in SearchDirectories())
			{
				string text = Path.Combine(item, fileName);
				if (File.Exists(text))
				{
					return text;
				}
			}
			return null;
		}

		private static void EvictLRUIfNeeded()
		{
			while (TextureCache.Count > 50 && AccessOrder.Count > 0)
			{
				string text = AccessOrder.First?.Value;
				if (text != null)
				{
					if (TextureCache.TryGetValue(text, out Texture2D value) && (Object)(object)value != (Object)null)
					{
						Object.DestroyImmediate((Object)(object)value);
					}
					TextureCache.Remove(text);
					AccessOrder.RemoveFirst();
				}
			}
		}

		public static void ClearCache()
		{
			foreach (Texture2D value in TextureCache.Values)
			{
				if ((Object)(object)value != (Object)null)
				{
					Object.DestroyImmediate((Object)(object)value);
				}
			}
			TextureCache.Clear();
			AccessOrder.Clear();
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "rewind.rwafterimages";

		public const string PLUGIN_NAME = "[rw]Afterimages";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace Plugin.Patches
{
	[HarmonyPatch(typeof(Player))]
	internal static class PlayerPatch
	{
		private static readonly Config ConfigSettings = Plugin.CFG;

		private static float playerSpeed;

		private static CharacterVisual? currentVisual;

		private static readonly (string Key, Func<Player, bool> Condition, Config.MovementStateConfig Config)[] StateConfigs = new(string, Func<Player, bool>, Config.MovementStateConfig)[15]
		{
			("staticaf", (Player p) => playerSpeed > 0.01f, ConfigSettings.staticaf),
			("speedaf", (Player p) => playerSpeed > ConfigSettings.SpeedThreshold.Value, ConfigSettings.speed),
			("boostaf", (Player p) => p.boosting, ConfigSettings.boost),
			("boosttrickaf", delegate(Player p)
			{
				if ((object)p.ability == p.groundTrickAbility)
				{
					Ability ability = p.ability;
					GroundTrickAbility val = (GroundTrickAbility)(object)((ability is GroundTrickAbility) ? ability : null);
					if (val != null)
					{
						return val.boostTrick;
					}
				}
				return false;
			}, ConfigSettings.boosttrick),
			("trickaf", (Player p) => (object)p.ability == p.groundTrickAbility, ConfigSettings.trick),
			("airboosttrickaf", delegate(Player p)
			{
				//IL_001e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Invalid comparison between Unknown and I4
				if ((object)p.ability == p.airTrickAbility)
				{
					Ability ability = p.ability;
					AirTrickAbility val = (AirTrickAbility)(object)((ability is AirTrickAbility) ? ability : null);
					if (val != null)
					{
						return (int)val.trickType == 2;
					}
				}
				return false;
			}, ConfigSettings.airboosttrick),
			("airtrickaf", (Player p) => (object)p.ability == p.airTrickAbility, ConfigSettings.airtrick),
			("slidenormalaf", (Player p) => (object)p.ability == p.slideAbility && (int)p.slideAbility.slideState == 1, ConfigSettings.slidenormal),
			("slideslopeaf", (Player p) => (object)p.ability == p.slideAbility && (int)p.slideAbility.slideState == 2, ConfigSettings.slideslope),
			("slidesuperaf", (Player p) => (object)p.ability == p.slideAbility && (int)p.slideAbility.slideState == 3, ConfigSettings.slidesuper),
			("airDashaf", (Player p) => (object)p.ability == p.airDashAbility, ConfigSettings.airDash),
			("grindnormalaf", delegate(Player p)
			{
				if ((object)p.ability == p.grindAbility)
				{
					Ability ability = p.ability;
					GrindAbility val = (GrindAbility)(object)((ability is GrindAbility) ? ability : null);
					if (val != null && val.trickTimer <= 0f)
					{
						return !val.softCornerBoost;
					}
				}
				return false;
			}, ConfigSettings.grindnormal),
			("grindtrickaf", delegate(Player p)
			{
				if ((object)p.ability == p.grindAbility)
				{
					Ability ability = p.ability;
					GrindAbility val = (GrindAbility)(object)((ability is GrindAbility) ? ability : null);
					if (val != null && val.trickTimer > 0f)
					{
						return !val.curTrickBoost;
					}
				}
				return false;
			}, ConfigSettings.grindtrick),
			("grindboosttrickaf", delegate(Player p)
			{
				if ((object)p.ability == p.grindAbility)
				{
					Ability ability = p.ability;
					GrindAbility val = (GrindAbility)(object)((ability is GrindAbility) ? ability : null);
					if (val != null && val.curTrickBoost)
					{
						return val.trickTimer > 0f;
					}
				}
				return false;
			}, ConfigSettings.grindboosttrick),
			("grindcorneraf", delegate(Player p)
			{
				if ((object)p.ability == p.grindAbility)
				{
					Ability ability = p.ability;
					GrindAbility val = (GrindAbility)(object)((ability is GrindAbility) ? ability : null);
					if (val != null)
					{
						return val.softCornerBoost;
					}
				}
				return false;
			}, ConfigSettings.grindcorner)
		};

		[HarmonyPostfix]
		[HarmonyPatch("Init")]
		public static void Post_Init(Player __instance)
		{
			if (!__instance.isAI)
			{
				Gscope.Player = __instance;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("UpdatePlayer")]
		public static void Post_UpdatePlayer(Player __instance)
		{
			//IL_0029: 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)
			if (!__instance.isAI)
			{
				CharacterVisual characterVisual = __instance.characterVisual;
				if (currentVisual != characterVisual)
				{
					AfterimageManager.ReleaseVisual(currentVisual);
					currentVisual = characterVisual;
				}
				Vector3 flatVelocity = __instance.GetFlatVelocity();
				playerSpeed = ((Vector3)(ref flatVelocity)).magnitude;
				(string, Func<Player, bool>, Config.MovementStateConfig)[] stateConfigs = StateConfigs;
				for (int i = 0; i < stateConfigs.Length; i++)
				{
					var (requesterId, func, movementStateConfig) = stateConfigs[i];
					AfterimageManager.Request(characterVisual, requesterId, movementStateConfig.Enabled.Value && func(__instance), movementStateConfig.CurrentData);
				}
			}
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}