Decompiled source of CustomSkybox v1.0.2

plugins/CustomSkybox.dll

Decompiled 2 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.Configuration;
using BepInEx.Logging;
using ComputerysModdingUtilities;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: StraftatMod(true)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("CustomSkybox")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+0d63145ef04367cab65b222524ecaa1e3d906210")]
[assembly: AssemblyProduct("CustomSkybox")]
[assembly: AssemblyTitle("CustomSkybox")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CustomSkybox
{
	[BepInPlugin("com.modder.straftat.customskybox", "Custom Skybox", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class SkyboxPlugin : BaseUnityPlugin
	{
		[CompilerGenerated]
		private sealed class <DelayedReapply>d__16 : IEnumerator<object>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private object <>2__current;

			public SkyboxPlugin <>4__this;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <DelayedReapply>d__16(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Expected O, but got Unknown
				int num = <>1__state;
				SkyboxPlugin skyboxPlugin = <>4__this;
				switch (num)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<>2__current = (object)new WaitForSeconds(0.5f);
					<>1__state = 1;
					return true;
				case 1:
				{
					<>1__state = -1;
					Material skybox = RenderSettings.skybox;
					if ((Object)(object)skybox != (Object)null && !((Object)skybox).name.StartsWith("CustomSkybox_"))
					{
						skyboxPlugin._vanillaSkybox = skybox;
					}
					skyboxPlugin.ApplySelectedSkybox();
					skyboxPlugin._pendingApply = null;
					return false;
				}
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		public const string PluginGUID = "com.modder.straftat.customskybox";

		public const string PluginName = "Custom Skybox";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		private static SkyboxPlugin _instance;

		private const string DefaultOption = "Default";

		private ConfigEntry<string> _selectedSkybox;

		private string _skyboxFolder;

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

		private readonly Dictionary<string, Material> _materialCache = new Dictionary<string, Material>(StringComparer.OrdinalIgnoreCase);

		private Material _vanillaSkybox;

		private Coroutine _pendingApply;

		private void Awake()
		{
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ef: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			_instance = this;
			_skyboxFolder = Path.Combine(Paths.PluginPath, "CustomSkybox");
			try
			{
				if (!Directory.Exists(_skyboxFolder))
				{
					Directory.CreateDirectory(_skyboxFolder);
				}
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Could not create skybox folder '" + _skyboxFolder + "': " + ex.Message));
			}
			ScanSkyboxFolder();
			List<string> list = new List<string> { "Default" };
			list.AddRange(_skyboxFiles.Keys.OrderBy<string, string>((string k) => k, StringComparer.OrdinalIgnoreCase));
			_selectedSkybox = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Skybox", "Default", new ConfigDescription("Skybox to apply to every map. Drop equirectangular (360°) PNG/JPG files into BepInEx/plugins/SkyboxMod/ and restart the game to see them here.", (AcceptableValueBase)(object)new AcceptableValueList<string>(list.ToArray()), Array.Empty<object>()));
			_selectedSkybox.SettingChanged += delegate
			{
				ApplySelectedSkybox();
			};
			SceneManager.sceneLoaded += OnSceneLoaded;
			Log.LogInfo((object)$"Skybox Mod loaded. Found {_skyboxFiles.Count} skybox image(s) in {_skyboxFolder}");
			if (_skyboxFiles.Count == 0)
			{
				Log.LogInfo((object)"Drop equirectangular PNG/JPG files into that folder and restart to add options.");
			}
		}

		private void OnDestroy()
		{
			SceneManager.sceneLoaded -= OnSceneLoaded;
		}

		private void ScanSkyboxFolder()
		{
			_skyboxFiles.Clear();
			if (!Directory.Exists(_skyboxFolder))
			{
				return;
			}
			string[] array = new string[3] { "*.png", "*.jpg", "*.jpeg" };
			foreach (string searchPattern in array)
			{
				string[] files = Directory.GetFiles(_skyboxFolder, searchPattern, SearchOption.TopDirectoryOnly);
				foreach (string text in files)
				{
					string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
					if (!_skyboxFiles.ContainsKey(fileNameWithoutExtension))
					{
						_skyboxFiles[fileNameWithoutExtension] = text;
					}
				}
			}
		}

		private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			_vanillaSkybox = RenderSettings.skybox;
			ApplySelectedSkybox();
			if (_pendingApply != null)
			{
				((MonoBehaviour)this).StopCoroutine(_pendingApply);
			}
			_pendingApply = ((MonoBehaviour)this).StartCoroutine(DelayedReapply());
		}

		[IteratorStateMachine(typeof(<DelayedReapply>d__16))]
		private IEnumerator DelayedReapply()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <DelayedReapply>d__16(0)
			{
				<>4__this = this
			};
		}

		private void ApplySelectedSkybox()
		{
			string value = _selectedSkybox.Value;
			try
			{
				string value2;
				if (value == "Default" || string.IsNullOrEmpty(value))
				{
					RenderSettings.skybox = _vanillaSkybox;
				}
				else if (_skyboxFiles.TryGetValue(value, out value2))
				{
					Material orBuildMaterial = GetOrBuildMaterial(value, value2);
					if ((Object)(object)orBuildMaterial != (Object)null)
					{
						RenderSettings.skybox = orBuildMaterial;
					}
				}
				else
				{
					Log.LogWarning((object)("Selected skybox '" + value + "' was not found on disk — using map default."));
					RenderSettings.skybox = _vanillaSkybox;
				}
				DynamicGI.UpdateEnvironment();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Failed to apply skybox '{value}': {arg}");
			}
		}

		private Material GetOrBuildMaterial(string name, string path)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Expected O, but got Unknown
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_0193: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Expected O, but got Unknown
			if (_materialCache.TryGetValue(name, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			byte[] array = File.ReadAllBytes(path);
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, true, false);
			((Texture)val).wrapMode = (TextureWrapMode)0;
			((Texture)val).filterMode = (FilterMode)1;
			if (!ImageConversion.LoadImage(val, array))
			{
				Log.LogError((object)("Failed to decode image: " + path));
				Object.Destroy((Object)(object)val);
				return null;
			}
			((Object)val).name = "CustomSkybox_" + name;
			Material val2 = null;
			Shader val3 = Shader.Find("Skybox/Panoramic");
			if ((Object)(object)val3 != (Object)null)
			{
				val2 = new Material(val3);
				val2.SetTexture("_MainTex", (Texture)(object)val);
				if (val2.HasProperty("_Mapping"))
				{
					val2.SetFloat("_Mapping", 1f);
				}
				if (val2.HasProperty("_ImageType"))
				{
					val2.SetFloat("_ImageType", 0f);
				}
				if (val2.HasProperty("_MirrorOnBack"))
				{
					val2.SetFloat("_MirrorOnBack", 0f);
				}
				if (val2.HasProperty("_Layout"))
				{
					val2.SetFloat("_Layout", 0f);
				}
				if (val2.HasProperty("_Exposure"))
				{
					val2.SetFloat("_Exposure", 1f);
				}
				if (val2.HasProperty("_Rotation"))
				{
					val2.SetFloat("_Rotation", 0f);
				}
			}
			else
			{
				Shader val4 = Shader.Find("Skybox/Cubemap");
				if ((Object)(object)val4 == (Object)null)
				{
					Log.LogError((object)"Neither Skybox/Panoramic nor Skybox/Cubemap shaders are available in this build. Cannot apply custom skybox.");
					Object.Destroy((Object)(object)val);
					return null;
				}
				Cubemap val5 = EquirectangularToCubemap(val, 512);
				val2 = new Material(val4);
				val2.SetTexture("_Tex", (Texture)(object)val5);
				if (val2.HasProperty("_Exposure"))
				{
					val2.SetFloat("_Exposure", 1f);
				}
				if (val2.HasProperty("_Rotation"))
				{
					val2.SetFloat("_Rotation", 0f);
				}
				Object.Destroy((Object)(object)val);
			}
			((Object)val2).name = "CustomSkybox_" + name;
			_materialCache[name] = val2;
			return val2;
		}

		private static Cubemap EquirectangularToCubemap(Texture2D src, int faceSize)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			Cubemap val = new Cubemap(faceSize, (TextureFormat)4, true);
			int width = ((Texture)src).width;
			int height = ((Texture)src).height;
			Color[] pixels = src.GetPixels();
			Vector3 val2 = default(Vector3);
			for (int i = 0; i < 6; i++)
			{
				Color[] array = (Color[])(object)new Color[faceSize * faceSize];
				for (int j = 0; j < faceSize; j++)
				{
					for (int k = 0; k < faceSize; k++)
					{
						float num = 2f * ((float)k + 0.5f) / (float)faceSize - 1f;
						float num2 = 2f * ((float)j + 0.5f) / (float)faceSize - 1f;
						switch (i)
						{
						case 0:
							((Vector3)(ref val2))..ctor(1f, 0f - num2, 0f - num);
							break;
						case 1:
							((Vector3)(ref val2))..ctor(-1f, 0f - num2, num);
							break;
						case 2:
							((Vector3)(ref val2))..ctor(num, 1f, num2);
							break;
						case 3:
							((Vector3)(ref val2))..ctor(num, -1f, 0f - num2);
							break;
						case 4:
							((Vector3)(ref val2))..ctor(num, 0f - num2, 1f);
							break;
						default:
							((Vector3)(ref val2))..ctor(0f - num, 0f - num2, -1f);
							break;
						}
						((Vector3)(ref val2)).Normalize();
						float num3 = Mathf.Atan2(val2.z, val2.x);
						float num4 = Mathf.Asin(Mathf.Clamp(val2.y, -1f, 1f));
						float num5 = 0.5f + num3 / ((float)Math.PI * 2f);
						float num6 = 0.5f - num4 / (float)Math.PI;
						int num7 = Mathf.Clamp((int)(num5 * (float)width), 0, width - 1);
						int num8 = Mathf.Clamp((int)(num6 * (float)height), 0, height - 1);
						array[j * faceSize + k] = pixels[num8 * width + num7];
					}
				}
				val.SetPixels(array, (CubemapFace)i);
			}
			val.Apply(true, false);
			return val;
		}
	}
}