Decompiled source of UnityHelper v1.1.0

UnityHelper.dll

Decompiled 3 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using WavLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("UnityHelper")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0+e6e90372d65e9f8d23d2cc56ff4d2191352aeff1")]
[assembly: AssemblyProduct("UnityHelper")]
[assembly: AssemblyTitle("UnityHelper")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/silksong-modding/Silksong.UnityHelper")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace Silksong.UnityHelper
{
	[BepInPlugin("org.silksong-modding.unityhelper", "UnityHelper", "1.1.0")]
	public class UnityHelperPlugin : BaseUnityPlugin
	{
		public const string Id = "org.silksong-modding.unityhelper";

		public static string Name => "UnityHelper";

		public static string Version => "1.1.0";

		private void Awake()
		{
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin " + Name + " (org.silksong-modding.unityhelper) has loaded!"));
		}
	}
}
namespace Silksong.UnityHelper.Util
{
	public static class SpriteUtil
	{
		public static Sprite LoadEmbeddedSprite(Assembly asm, string path, float pixelsPerUnit = 64f, Vector2? pivot = null, bool makeUnreadable = false)
		{
			Sprite obj = LoadSpriteFromArray(GetEmbeddedImageData(asm, path), pixelsPerUnit, pivot, makeUnreadable);
			string name = (((Object)obj.texture).name = path);
			((Object)obj).name = name;
			return obj;
		}

		public static Sprite LoadEmbeddedSprite(Assembly asm, string path, float pixelsPerUnit)
		{
			return LoadEmbeddedSprite(asm, path, pixelsPerUnit, null, makeUnreadable: false);
		}

		public static Sprite LoadSpriteFromFile(string fileName, float pixelsPerUnit = 64f, Vector2? pivot = null, bool makeUnreadable = false)
		{
			Sprite obj = LoadSpriteFromArray(GetFileImageData(fileName), pixelsPerUnit, pivot, makeUnreadable);
			string name = (((Object)obj.texture).name = Path.GetFileNameWithoutExtension(fileName));
			((Object)obj).name = name;
			return obj;
		}

		public static Sprite LoadSpriteFromFile(string fileName, float pixelsPerUnit)
		{
			return LoadSpriteFromFile(fileName, pixelsPerUnit, null, makeUnreadable: false);
		}

		public static Sprite LoadSpriteFromArray(byte[] buffer, float pixelsPerUnit = 64f, Vector2? pivot = null, bool makeUnreadable = false)
		{
			//IL_0021: 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_0031: 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)
			Texture2D val = LoadTextureFromArray(buffer, makeUnreadable);
			return Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), (Vector2)(((??)pivot) ?? (Vector2.one * 0.5f)), pixelsPerUnit);
		}

		public static Sprite LoadSpriteFromArray(byte[] buffer, float pixelsPerUnit)
		{
			return LoadSpriteFromArray(buffer, pixelsPerUnit, null, makeUnreadable: false);
		}

		public static Texture2D LoadEmbeddedTexture(Assembly asm, string path, bool makeUnreadable = false)
		{
			Texture2D obj = LoadTextureFromArray(GetEmbeddedImageData(asm, path), makeUnreadable);
			((Object)obj).name = path;
			return obj;
		}

		public static Texture2D LoadTextureFromFile(string fileName, bool makeUnreadable = false)
		{
			Texture2D obj = LoadTextureFromArray(GetFileImageData(fileName), makeUnreadable);
			((Object)obj).name = Path.GetFileNameWithoutExtension(fileName);
			return obj;
		}

		public static Texture2D LoadTextureFromArray(byte[] buffer, bool makeUnreadable = false)
		{
			//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)
			//IL_000f: Expected O, but got Unknown
			//IL_0011: Expected O, but got Unknown
			Texture2D val = new Texture2D(2, 2);
			ImageConversion.LoadImage(val, buffer, makeUnreadable);
			return val;
		}

		public static Texture2D GetReadableTexture(Texture2D tex)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			if (((Texture)tex).isReadable)
			{
				return tex;
			}
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)tex).width, ((Texture)tex).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)1);
			Graphics.Blit((Texture)(object)tex, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(((Texture)tex).width, ((Texture)tex).height);
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		private static byte[] GetEmbeddedImageData(Assembly asm, string path)
		{
			using Stream stream = asm.GetManifestResourceStream(path);
			byte[] array = new byte[stream.Length];
			int num = stream.Read(array, 0, array.Length);
			if (num != array.Length)
			{
				throw new IOException($"Failed to read the entire resource stream for path '{path}' in assembly '{asm.FullName}'.\nExpected {stream.Length} bytes, but read {num}.");
			}
			return array;
		}

		private static byte[] GetFileImageData(string fileName)
		{
			if (string.IsNullOrWhiteSpace(fileName))
			{
				throw new ArgumentException("Filename cannot be empty", "fileName");
			}
			if (!File.Exists(fileName))
			{
				throw new ArgumentException("File " + fileName + " not found", "fileName");
			}
			return File.ReadAllBytes(fileName);
		}
	}
	public static class Tk2dUtil
	{
		public static tk2dSpriteAnimationClip CreateTk2dAnimationClip(string name, int fps, IEnumerable<Texture2D> frames, WrapMode wrapMode = 2, int loopStart = 0, float pixelsPerUnit = 64f)
		{
			//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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			tk2dSpriteCollectionData collection = CreateTk2dSpriteCollection(frames, null, null, pixelsPerUnit);
			return new tk2dSpriteAnimationClip
			{
				name = name,
				fps = fps,
				wrapMode = wrapMode,
				loopStart = loopStart,
				frames = collection.CreateFrames(frames.Select((Texture2D x) => ((Object)x).name))
			};
		}

		public static tk2dSpriteAnimationClip CreateTk2dAnimationClip(string name, int fps, IEnumerable<Sprite> frames, WrapMode wrapMode = 2, int loopStart = 0, float pixelsPerUnit = 64f)
		{
			//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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			tk2dSpriteCollectionData collection = CreateTk2dSpriteCollection(frames, null, null, pixelsPerUnit);
			return new tk2dSpriteAnimationClip
			{
				name = name,
				fps = fps,
				wrapMode = wrapMode,
				loopStart = loopStart,
				frames = collection.CreateFrames(frames.Select((Sprite x) => ((Object)x).name))
			};
		}

		public static tk2dSpriteCollectionData CreateTk2dSpriteCollection(IEnumerable<Texture2D> sprites, IEnumerable<string>? spriteNames = null, IEnumerable<Vector2>? spriteCenters = null, float pixelsPerUnit = 64f)
		{
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Expected O, but got Unknown
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			if (spriteNames == null)
			{
				spriteNames = sprites.Select((Texture2D x) => ((Object)x).name);
			}
			if (spriteCenters == null)
			{
				spriteCenters = sprites.Select((Func<Texture2D, Vector2>)((Texture2D x) => new Vector2((float)((Texture)x).width / 2f, (float)((Texture)x).height / 2f)));
			}
			int num = sprites.Count();
			if (num != spriteNames.Count())
			{
				throw new ArgumentException("Number of spriteNames does not match number of sprites", "spriteNames");
			}
			if (num != spriteCenters.Count())
			{
				throw new ArgumentException("Number of spriteCenters does not match number of sprites", "spriteCenters");
			}
			if (spriteNames.Distinct().Count() < num)
			{
				throw new ArgumentException("Sprites in the same collection must have unique names.", "spriteNames");
			}
			Texture2D[] array = sprites.Select(SpriteUtil.GetReadableTexture).ToArray();
			Texture2D val = new Texture2D(1, 1);
			Rect[] array2 = val.PackTextures(array, 2);
			val.Apply(false, true);
			for (int i = 0; i < array2.Length; i++)
			{
				Rect val2 = array2[i];
				((Rect)(ref val2)).x = ((Rect)(ref val2)).x * (float)((Texture)val).width;
				((Rect)(ref val2)).y = ((Rect)(ref val2)).y * (float)((Texture)val).height;
				((Rect)(ref val2)).width = ((Rect)(ref val2)).width * (float)((Texture)val).width;
				((Rect)(ref val2)).height = ((Rect)(ref val2)).height * (float)((Texture)val).height;
				((Rect)(ref val2)).y = (float)((Texture)val).height - ((Rect)(ref val2)).yMax;
				array2[i] = val2;
			}
			tk2dSpriteCollectionData obj = tk2dSpriteCollectionData.CreateFromTexture((Texture)(object)val, tk2dSpriteCollectionSize.PixelsPerMeter(pixelsPerUnit), spriteNames.ToArray(), array2, spriteCenters.ToArray());
			Object.DontDestroyOnLoad((Object)(object)obj);
			return obj;
		}

		public static tk2dSpriteCollectionData CreateTk2dSpriteCollection(IEnumerable<Sprite> sprites, IEnumerable<string>? spriteNames = null, IEnumerable<Vector2>? spriteCenters = null, float pixelsPerUnit = 64f)
		{
			return CreateTk2dSpriteCollection(sprites.Select((Sprite x) => x.texture), spriteNames ?? sprites.Select((Sprite x) => ((Object)x).name), spriteCenters ?? sprites.Select((Sprite x) => x.pivot), pixelsPerUnit);
		}

		public static tk2dSpriteAnimationFrame CreateFrame(this tk2dSpriteCollectionData collection, string spriteName, bool triggerEvent = false)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			return new tk2dSpriteAnimationFrame
			{
				spriteCollection = collection,
				spriteId = collection.GetSpriteIdByName(spriteName),
				triggerEvent = triggerEvent
			};
		}

		public static tk2dSpriteAnimationFrame[] CreateFrames(this tk2dSpriteCollectionData collection, params string[] spriteNames)
		{
			tk2dSpriteCollectionData collection2 = collection;
			return spriteNames.Select((string x) => collection2.CreateFrame(x)).ToArray();
		}

		public static tk2dSpriteAnimationFrame[] CreateFrames(this tk2dSpriteCollectionData collection, IEnumerable<string> spriteNames)
		{
			tk2dSpriteCollectionData collection2 = collection;
			return spriteNames.Select((string x) => collection2.CreateFrame(x)).ToArray();
		}
	}
	public static class WavUtil
	{
		public static AudioClip AudioClipFromEmbeddedResource(string path, Assembly asm, string? name = null)
		{
			if (name == null)
			{
				name = path;
			}
			using Stream dataStream = asm.GetManifestResourceStream(path);
			return AudioClipFromStream(dataStream, name);
		}

		public static AudioClip AudioClipFromFile(string fileName, string? name = null)
		{
			if (name == null)
			{
				name = Path.GetFileNameWithoutExtension(fileName);
			}
			if (string.IsNullOrWhiteSpace(fileName))
			{
				throw new ArgumentException("Filename cannot be empty", "fileName");
			}
			if (!File.Exists(fileName))
			{
				throw new ArgumentException("File " + fileName + " not found", "fileName");
			}
			using Stream dataStream = File.Open(fileName, FileMode.Open);
			return AudioClipFromStream(dataStream, name);
		}

		public static AudioClip AudioClipFromStream(Stream dataStream, string origName = "")
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Expected O, but got Unknown
			WavData val = new WavData();
			val.Parse(dataStream, (Action<string>)null);
			float[] samples = val.GetSamples();
			AudioClip obj = AudioClip.Create(origName, samples.Length / val.FormatChunk.NumChannels, (int)val.FormatChunk.NumChannels, (int)val.FormatChunk.SampleRate, false);
			obj.SetData(samples, 0);
			return obj;
		}
	}
}
namespace Silksong.UnityHelper.Extensions
{
	public static class UnityExtensions
	{
		[CompilerGenerated]
		private sealed class <>c__DisplayClass6_0
		{
			public float seconds;

			public Action toInvoke;
		}

		[CompilerGenerated]
		private sealed class <>c__DisplayClass7_0
		{
			public int numFrames;

			public Action toInvoke;
		}

		private static readonly ManualLogSource Log = Logger.CreateLogSource("UnityHelperPlugin.UnityExtensions");

		public static T GetOrAddComponent<T>(this GameObject go) where T : Component
		{
			T val = go.GetComponent<T>();
			if ((Object)(object)val == (Object)null)
			{
				val = go.AddComponent<T>();
			}
			return val;
		}

		public static string GetNameInHierarchy(this GameObject go)
		{
			return go.transform.GetNameInHierarchy();
		}

		public static string GetNameInHierarchy(this Transform t)
		{
			List<string> list = new List<string>(1) { ((Object)((Component)t).gameObject).name };
			while ((Object)(object)t.parent != (Object)null)
			{
				t = t.parent;
				list.Add(((Object)t).name);
			}
			list.Reverse();
			return string.Join('/', list);
		}

		public static GameObject? FindChild(this GameObject go, string path)
		{
			Transform val = go.transform.Find(path);
			if (!((Object)(object)val != (Object)null))
			{
				return null;
			}
			return ((Component)val).gameObject;
		}

		public static GameObject? FindGameObject(this Scene scene, string path)
		{
			if (string.IsNullOrEmpty(path))
			{
				return null;
			}
			string[] array = path.Split('/', 2);
			string rootName = array[0];
			GameObject val = ((IEnumerable<GameObject>)((Scene)(ref scene)).GetRootGameObjects()).FirstOrDefault((Func<GameObject, bool>)((GameObject x) => ((Object)x).name == rootName));
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			if (array.Length == 1)
			{
				return val;
			}
			return val.FindChild(array[1]);
		}

		public static void InvokeAfterSeconds(this MonoBehaviour component, Action toInvoke, float seconds)
		{
			<>c__DisplayClass6_0 CS$<>8__locals0 = new <>c__DisplayClass6_0();
			CS$<>8__locals0.seconds = seconds;
			CS$<>8__locals0.toInvoke = toInvoke;
			component.StartCoroutine(doInvoke());
			[IteratorStateMachine(typeof(<>c__DisplayClass6_0.<<InvokeAfterSeconds>g__doInvoke|0>d))]
			IEnumerator doInvoke()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <>c__DisplayClass6_0.<<InvokeAfterSeconds>g__doInvoke|0>d(0)
				{
					<>4__this = CS$<>8__locals0
				};
			}
		}

		public static void InvokeAfterFrames(this MonoBehaviour component, Action toInvoke, int numFrames)
		{
			<>c__DisplayClass7_0 CS$<>8__locals0 = new <>c__DisplayClass7_0();
			CS$<>8__locals0.numFrames = numFrames;
			CS$<>8__locals0.toInvoke = toInvoke;
			component.StartCoroutine(doInvoke());
			[IteratorStateMachine(typeof(<>c__DisplayClass7_0.<<InvokeAfterFrames>g__doInvoke|0>d))]
			IEnumerator doInvoke()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <>c__DisplayClass7_0.<<InvokeAfterFrames>g__doInvoke|0>d(0)
				{
					<>4__this = CS$<>8__locals0
				};
			}
		}

		public static void InvokeNextFrame(this MonoBehaviour component, Action toInvoke)
		{
			component.InvokeAfterFrames(toInvoke, 1);
		}
	}
}