Decompiled source of DysonShellSkin v1.4.2

DysonShellSkin.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace DysonShellSkin;

internal static class NativeFileDialog
{
	[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
	private struct OPENFILENAMEW
	{
		public int lStructSize;

		public IntPtr hwndOwner;

		public IntPtr hInstance;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrFilter;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrCustomFilter;

		public int nMaxCustFilter;

		public int nFilterIndex;

		public IntPtr lpstrFile;

		public int nMaxFile;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrFileTitle;

		public int nMaxFileTitle;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrInitialDir;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrTitle;

		public int Flags;

		public ushort nFileOffset;

		public ushort nFileExtension;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpstrDefExt;

		public IntPtr lCustData;

		public IntPtr lpfnHook;

		[MarshalAs(UnmanagedType.LPWStr)]
		public string lpTemplateName;

		public IntPtr pvReserved;

		public int dwReserved;

		public int FlagsEx;
	}

	private const int OFN_HIDEREADONLY = 4;

	private const int OFN_NOCHANGEDIR = 8;

	private const int OFN_PATHMUSTEXIST = 2048;

	private const int OFN_FILEMUSTEXIST = 4096;

	private const int OFN_EXPLORER = 524288;

	[DllImport("comdlg32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
	[return: MarshalAs(UnmanagedType.Bool)]
	private static extern bool GetOpenFileNameW(ref OPENFILENAMEW ofn);

	[DllImport("comdlg32.dll")]
	private static extern uint CommDlgExtendedError();

	[DllImport("user32.dll")]
	private static extern IntPtr GetActiveWindow();

	[DllImport("user32.dll")]
	private static extern IntPtr GetForegroundWindow();

	[DllImport("user32.dll")]
	[return: MarshalAs(UnmanagedType.Bool)]
	private static extern bool SetForegroundWindow(IntPtr hWnd);

	public static string OpenImageDialog(string title)
	{
		IntPtr intPtr = Marshal.AllocHGlobal(65536);
		try
		{
			string lpstrFilter = "图片文件 (PNG/JPG)\0*.png;*.jpg;*.jpeg\0所有文件 (*.*)\0*.*\0\0";
			IntPtr intPtr2 = GetActiveWindow();
			if (intPtr2 == IntPtr.Zero)
			{
				intPtr2 = GetForegroundWindow();
			}
			if (intPtr2 != IntPtr.Zero)
			{
				SetForegroundWindow(intPtr2);
			}
			OPENFILENAMEW ofn = new OPENFILENAMEW
			{
				lStructSize = Marshal.SizeOf(typeof(OPENFILENAMEW)),
				hwndOwner = intPtr2,
				lpstrFilter = lpstrFilter,
				lpstrFile = intPtr,
				nMaxFile = 32768,
				lpstrTitle = (string.IsNullOrEmpty(title) ? "选择图片" : title)
			};
			try
			{
				ofn.lpstrInitialDir = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
			}
			catch (Exception)
			{
				ofn.lpstrInitialDir = null;
			}
			ofn.Flags = 530444;
			if (GetOpenFileNameW(ref ofn))
			{
				string text = Marshal.PtrToStringUni(intPtr);
				if (!string.IsNullOrEmpty(text))
				{
					ManualLogSource log = DysonShellSkinPlugin.Log;
					if (log != null)
					{
						log.LogInfo((object)("已选择图片: " + text));
					}
					return text;
				}
			}
			uint num = CommDlgExtendedError();
			if (num == 0)
			{
				ManualLogSource log2 = DysonShellSkinPlugin.Log;
				if (log2 != null)
				{
					log2.LogInfo((object)"文件对话框被取消(或未显示出来被游戏窗口遮挡)");
				}
			}
			else
			{
				ManualLogSource log3 = DysonShellSkinPlugin.Log;
				if (log3 != null)
				{
					log3.LogWarning((object)("文件对话框失败,CommDlgExtendedError=" + num));
				}
			}
			return null;
		}
		catch (Exception ex2)
		{
			ManualLogSource log4 = DysonShellSkinPlugin.Log;
			if (log4 != null)
			{
				log4.LogWarning((object)("打开文件对话框失败: " + ex2.Message));
			}
			return null;
		}
		finally
		{
			Marshal.FreeHGlobal(intPtr);
		}
	}
}
internal static class OverlaySkinRenderer
{
	private static readonly Dictionary<long, Material> _mats = new Dictionary<long, Material>();

	private static Texture2D[] _fbFrames;

	private static string _fbFolder = "";

	private static int _fbIndex;

	private static float _fbTimer;

	private static Mesh _bandMesh;

	private static bool _bandMeshDirty = true;

	private static Shader _shader;

	private static string _shaderUsed = "";

	private static bool _shaderWarned;

	private static readonly string[] ShaderCandidates = new string[4] { "UI/Default", "Sprites/Default", "Unlit/Texture", "Unlit/Color" };

	public static string ShaderUsed => _shaderUsed;

	internal static int LastDrawCount { get; private set; }

	public static Texture2D CurrentFlipbookFrame
	{
		get
		{
			if (_fbFrames == null || _fbFrames.Length == 0)
			{
				return null;
			}
			return _fbFrames[Mathf.Min(_fbIndex, _fbFrames.Length - 1)];
		}
	}

	private static bool EnsureShader()
	{
		if ((Object)(object)_shader != (Object)null)
		{
			return true;
		}
		string[] shaderCandidates = ShaderCandidates;
		foreach (string text in shaderCandidates)
		{
			Shader val = Shader.Find(text);
			if ((Object)(object)val != (Object)null)
			{
				_shader = val;
				_shaderUsed = text;
				ManualLogSource log = DysonShellSkinPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)("显示层使用内置着色器: " + text));
				}
				return true;
			}
		}
		if (!_shaderWarned)
		{
			_shaderWarned = true;
			ManualLogSource log2 = DysonShellSkinPlugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)"找不到可用的内置着色器(UI/Default 等),显示层不可用");
			}
		}
		return false;
	}

	internal static void EnsureFlipbook(string folder)
	{
		if (string.IsNullOrEmpty(folder) || (_fbFolder == folder && _fbFrames != null && _fbFrames.Length != 0))
		{
			return;
		}
		try
		{
			string[] files = Directory.GetFiles(folder, "*.png");
			Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
			if (files.Length == 0)
			{
				ManualLogSource log = DysonShellSkinPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("帧序列文件夹中没有 PNG: " + folder));
				}
				return;
			}
			List<Texture2D> list = new List<Texture2D>();
			string[] array = files;
			for (int i = 0; i < array.Length; i++)
			{
				string err;
				Texture2D val = ShellSkinApplier.LoadTexture(array[i], out err);
				if ((Object)(object)val != (Object)null)
				{
					list.Add(val);
				}
			}
			if (list.Count == 0)
			{
				ManualLogSource log2 = DysonShellSkinPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("帧序列全部加载失败: " + folder));
				}
				return;
			}
			_fbFrames = list.ToArray();
			_fbFolder = folder;
			_fbIndex = 0;
			_fbTimer = 0f;
			ManualLogSource log3 = DysonShellSkinPlugin.Log;
			if (log3 != null)
			{
				log3.LogInfo((object)$"帧序列已加载: {_fbFrames.Length} 帧 ({folder})");
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log4 = DysonShellSkinPlugin.Log;
			if (log4 != null)
			{
				log4.LogWarning((object)("帧序列加载异常: " + ex.Message));
			}
		}
	}

	public static void UpdateFlipbook(float fps)
	{
		if (_fbFrames != null && _fbFrames.Length != 0)
		{
			_fbTimer += Time.deltaTime;
			float num = 1f / Mathf.Max(1f, fps);
			while (_fbTimer >= num)
			{
				_fbTimer -= num;
				_fbIndex = (_fbIndex + 1) % _fbFrames.Length;
			}
		}
	}

	private static void EnsureBandMesh()
	{
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_021f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0224: Unknown result type (might be due to invalid IL or missing references)
		//IL_0234: Expected O, but got Unknown
		if ((Object)(object)_bandMesh != (Object)null && !_bandMeshDirty)
		{
			return;
		}
		float num = Mathf.Clamp((ShellSkinApplier.CfgBandMax != null) ? ShellSkinApplier.CfgBandMax.Value : 55f, 10f, 90f);
		float num2 = Mathf.Clamp((ShellSkinApplier.CfgBandMin != null) ? ShellSkinApplier.CfgBandMin.Value : (-55f), -90f, -10f);
		int num3 = Mathf.Clamp((ShellSkinApplier.CfgOverlaySegLon != null) ? ShellSkinApplier.CfgOverlaySegLon.Value : 384, 32, 1024);
		int num4 = Mathf.Clamp((ShellSkinApplier.CfgOverlaySegLat != null) ? ShellSkinApplier.CfgOverlaySegLat.Value : 192, 16, 512);
		int num5 = (num4 + 1) * (num3 + 1);
		Vector3[] array = (Vector3[])(object)new Vector3[num5];
		Vector2[] array2 = (Vector2[])(object)new Vector2[num5];
		int[] array3 = new int[num4 * num3 * 6];
		int num6 = 0;
		for (int i = 0; i <= num4; i++)
		{
			float num7 = (float)i / (float)num4;
			float num8 = Mathf.Lerp(num2, num, num7);
			float num9 = Mathf.Sin(num8 * ((float)Math.PI / 180f));
			float num10 = Mathf.Cos(num8 * ((float)Math.PI / 180f));
			for (int j = 0; j <= num3; j++)
			{
				float num11 = (float)j / (float)num3;
				float num12 = num11 * 2f * (float)Math.PI;
				array[num6] = new Vector3(num10 * Mathf.Cos(num12), num9, num10 * Mathf.Sin(num12));
				array2[num6] = new Vector2(1f - num11, num7);
				num6++;
			}
		}
		int num13 = 0;
		for (int k = 0; k < num4; k++)
		{
			for (int l = 0; l < num3; l++)
			{
				int num14 = k * (num3 + 1) + l;
				int num15 = num14 + 1;
				int num16 = num14 + (num3 + 1);
				int num17 = num16 + 1;
				array3[num13++] = num14;
				array3[num13++] = num16;
				array3[num13++] = num15;
				array3[num13++] = num15;
				array3[num13++] = num16;
				array3[num13++] = num17;
			}
		}
		if ((Object)(object)_bandMesh == (Object)null)
		{
			_bandMesh = new Mesh
			{
				name = "DysonShellSkin_Band"
			};
		}
		_bandMesh.Clear();
		_bandMesh.indexFormat = (IndexFormat)(num5 > 65535);
		_bandMesh.vertices = array;
		_bandMesh.uv = array2;
		_bandMesh.triangles = array3;
		_bandMesh.RecalculateBounds();
		_bandMesh.RecalculateNormals();
		_bandMeshDirty = false;
	}

	public static void OnDrawModels(DysonSphereSegmentRenderer renderer, ERenderPlace place)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Invalid comparison between Unknown and I4
		//IL_008f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Invalid comparison between Unknown and I4
		//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)
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_009e: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: 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_00b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f8: Invalid comparison between Unknown and I4
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_0135: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Unknown result type (might be due to invalid IL or missing references)
		//IL_0140: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0257: 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_027e: Expected O, but got Unknown
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Invalid comparison between Unknown and I4
		//IL_02c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02da: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
		LastDrawCount = 0;
		if ((int)place == 1 || (int)place == -1)
		{
			return;
		}
		DysonSphere val = renderer?.dysonSphere;
		StarData val2 = renderer?.starData;
		if (val == null || val.layersIdBased == null || val2 == null)
		{
			return;
		}
		GameData val3 = ((renderer.gameData != null) ? renderer.gameData : GameMain.data);
		if (val3 == null)
		{
			return;
		}
		EnsureShader();
		EnsureBandMesh();
		if ((Object)(object)_shader == (Object)null || (Object)(object)_bandMesh == (Object)null)
		{
			return;
		}
		Quaternion val4 = Quaternion.identity;
		PlanetData val5 = null;
		try
		{
			val5 = val3.localPlanet;
		}
		catch (Exception)
		{
		}
		Vector3 val6;
		if ((int)place == 0)
		{
			try
			{
				if (val5 != null)
				{
					val6 = VectorLF3.op_Implicit(Maths.QInvRotateLF(val5.runtimeRotation, val2.uPosition - val5.uPosition));
					val4 = val5.runtimeRotation;
				}
				else
				{
					val6 = Vector3.zero;
				}
			}
			catch (Exception)
			{
				val6 = Vector3.zero;
			}
		}
		else
		{
			val6 = Vector3.zero;
			val4 = Quaternion.identity;
		}
		int num = (((int)place == 0) ? 16 : (((int)place == 1) ? 20 : 21));
		uint num2 = (uint)(((int)place == 2) ? val.inEditorRenderMaskL : val.inGameRenderMaskL);
		float num3 = ((ShellSkinApplier.CfgLonOffset != null) ? ShellSkinApplier.CfgLonOffset.Value : 0f);
		Quaternion val7 = Quaternion.Euler(0f, num3, 0f);
		Quaternion val8 = default(Quaternion);
		((Quaternion)(ref val8))..ctor(val4.x, val4.y, val4.z, 0f - val4.w);
		foreach (SkinRecord item in SkinStore.ForStar(val2.index))
		{
			if (!item.isFrames || string.IsNullOrEmpty(item.framesPath) || item.layerId < 1 || item.layerId >= val.layersIdBased.Length)
			{
				continue;
			}
			DysonSphereLayer val9 = val.layersIdBased[item.layerId];
			if (val9 == null || ((num2 >> item.layerId) & 1) == 0)
			{
				continue;
			}
			float orbitRadius = val9.orbitRadius;
			if (orbitRadius <= 0f)
			{
				continue;
			}
			float num4 = orbitRadius * 1.001f + 2f;
			EnsureFlipbook(item.framesPath);
			Texture2D currentFlipbookFrame = CurrentFlipbookFrame;
			if ((Object)(object)currentFlipbookFrame == (Object)null)
			{
				continue;
			}
			if (!_mats.TryGetValue(item.Key, out var value) || (Object)(object)value == (Object)null)
			{
				if (!EnsureShader())
				{
					continue;
				}
				value = new Material(_shader)
				{
					name = "DysonShellSkin_" + item.Key
				};
				value.mainTexture = (Texture)(object)currentFlipbookFrame;
				_mats[item.Key] = value;
			}
			if ((Object)(object)value.mainTexture != (Object)(object)currentFlipbookFrame)
			{
				value.mainTexture = (Texture)(object)currentFlipbookFrame;
			}
			Quaternion val10 = (((int)place != 2) ? (val8 * val9.currentRotation) : (val7 * val9.currentRotation));
			Matrix4x4 val11 = Matrix4x4.TRS(val6, val10, new Vector3(num4, num4, num4));
			Graphics.DrawMesh(_bandMesh, val11, value, num, (Camera)null, 0, (MaterialPropertyBlock)null, false, false);
			LastDrawCount++;
		}
	}

	public static void Shutdown()
	{
		if ((Object)(object)_bandMesh != (Object)null)
		{
			Object.Destroy((Object)(object)_bandMesh);
		}
		_bandMesh = null;
		_bandMeshDirty = true;
		foreach (KeyValuePair<long, Material> mat in _mats)
		{
			if ((Object)(object)mat.Value != (Object)null)
			{
				Object.Destroy((Object)(object)mat.Value);
			}
		}
		_mats.Clear();
		_shader = null;
	}
}
internal static class PaintMapper
{
	private static bool _capWarned;

	private static bool _allDumped;

	internal static string LastPaintInfo = "";

	internal static string LastDirSource = "";

	internal static float BandLatMin = -55f;

	internal static float BandLatMax = 55f;

	public static bool ApplyToLayer(DysonSphereLayer layer, SkinRecord r)
	{
		//IL_026c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0271: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0278: Unknown result type (might be due to invalid IL or missing references)
		//IL_027a: Unknown result type (might be due to invalid IL or missing references)
		//IL_027f: Unknown result type (might be due to invalid IL or missing references)
		//IL_040a: Unknown result type (might be due to invalid IL or missing references)
		//IL_040c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02de: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_0452: Unknown result type (might be due to invalid IL or missing references)
		//IL_0457: Unknown result type (might be due to invalid IL or missing references)
		//IL_0420: Unknown result type (might be due to invalid IL or missing references)
		//IL_0439: Unknown result type (might be due to invalid IL or missing references)
		//IL_0468: Unknown result type (might be due to invalid IL or missing references)
		//IL_046c: Unknown result type (might be due to invalid IL or missing references)
		//IL_045e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0463: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0304: Unknown result type (might be due to invalid IL or missing references)
		//IL_0309: Unknown result type (might be due to invalid IL or missing references)
		//IL_031f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0325: Unknown result type (might be due to invalid IL or missing references)
		//IL_032a: Unknown result type (might be due to invalid IL or missing references)
		//IL_032f: Unknown result type (might be due to invalid IL or missing references)
		//IL_038f: Unknown result type (might be due to invalid IL or missing references)
		//IL_039f: Unknown result type (might be due to invalid IL or missing references)
		//IL_03a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_039a: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0503: Unknown result type (might be due to invalid IL or missing references)
		if (layer == null || r == null || string.IsNullOrEmpty(r.imagePath))
		{
			return false;
		}
		Texture2D runtimeTexture = ShellSkinApplier.GetRuntimeTexture(r);
		if ((Object)(object)runtimeTexture == (Object)null)
		{
			return false;
		}
		Mesh[] paintingOverlayMeshes = DysonSphereSegmentRenderer.paintingOverlayMeshes;
		if (paintingOverlayMeshes == null || paintingOverlayMeshes.Length == 0)
		{
			return false;
		}
		int num = ResolveMode(paintingOverlayMeshes);
		if (num < 0 || num >= paintingOverlayMeshes.Length || (Object)(object)paintingOverlayMeshes[num] == (Object)null)
		{
			return false;
		}
		Mesh val = paintingOverlayMeshes[num];
		int[] triangles;
		Vector3[] vertices;
		Vector2[] uv;
		Vector3[] normals;
		try
		{
			triangles = val.triangles;
			vertices = val.vertices;
			uv = val.uv;
			normals = val.normals;
		}
		catch (Exception)
		{
			return false;
		}
		if (triangles == null || vertices == null || triangles.Length < 3)
		{
			return false;
		}
		int num2 = triangles.Length / 3;
		int num3 = (num2 + 1) / 2;
		int num4 = ((ShellSkinApplier.CfgMaxPaintCells != null) ? ShellSkinApplier.CfgMaxPaintCells.Value : 200000);
		if (num3 > num4)
		{
			if (!_capWarned)
			{
				_capWarned = true;
				ManualLogSource log = DysonShellSkinPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)$"涂装网格 mode={num} 有 {num3} 格,超过上限 {num4},跳过涂装(可在配置调高『最大格子数』)");
				}
			}
			return false;
		}
		int num5 = DetectDirSource(val, vertices, normals, uv);
		LastDirSource = num5 switch
		{
			1 => "normal", 
			2 => "uv", 
			_ => "position", 
		};
		if (!_allDumped)
		{
			_allDumped = true;
			for (int i = 0; i < paintingOverlayMeshes.Length; i++)
			{
				if ((Object)(object)paintingOverlayMeshes[i] != (Object)null)
				{
					DumpGrid(i, paintingOverlayMeshes[i]);
				}
			}
		}
		if (ShellSkinApplier.CfgDebug != null && ShellSkinApplier.CfgDebug.Value)
		{
			DumpGrid(num, val);
		}
		float num6 = Mathf.Clamp((ShellSkinApplier.CfgBandMax != null) ? ShellSkinApplier.CfgBandMax.Value : 55f, 10f, 90f);
		float num7 = (BandLatMin = Mathf.Clamp((ShellSkinApplier.CfgBandMin != null) ? ShellSkinApplier.CfgBandMin.Value : (-55f), -90f, -10f));
		BandLatMax = num6;
		float num8 = Mathf.Sin(num6 * ((float)Math.PI / 180f));
		float num9 = Mathf.Sin(num7 * ((float)Math.PI / 180f));
		float num10 = 0.5f + num9 / 2f;
		float num11 = 0.5f + num8 / 2f;
		float num12 = 0.5f + ((ShellSkinApplier.CfgLonOffset != null) ? ShellSkinApplier.CfgLonOffset.Value : 0f) / 360f;
		Color32 val2 = default(Color32);
		((Color32)(ref val2))..ctor((byte)0, (byte)0, (byte)0, (byte)0);
		Color32[] array = (Color32[])(object)new Color32[num3];
		float[] array2 = new float[6];
		float[] array3 = new float[6];
		for (int j = 0; j < num3; j++)
		{
			Vector3 val3 = Vector3.zero;
			Vector3 val4 = Vector3.zero;
			Vector2 val5 = Vector2.zero;
			int num13 = 0;
			int num14 = 0;
			int num15 = 0;
			bool flag = true;
			bool flag2 = true;
			for (int k = 0; k < 2 && flag; k++)
			{
				int num16 = j * 2 + k;
				if (num16 >= num2)
				{
					break;
				}
				for (int l = 0; l < 3; l++)
				{
					int num17 = triangles[num16 * 3 + l];
					if (num17 < 0 || num17 >= vertices.Length)
					{
						flag = false;
						break;
					}
					val3 += vertices[num17];
					num13++;
					if (normals != null && normals.Length == vertices.Length)
					{
						val4 += normals[num17];
						num14++;
					}
					if (uv != null && uv.Length == vertices.Length)
					{
						val5 += uv[num17];
						num15++;
					}
					float x;
					float v;
					if (num5 == 2 && uv != null && uv.Length == vertices.Length)
					{
						x = uv[num17].x;
						x -= Mathf.Floor(x);
						v = uv[num17].y;
					}
					else
					{
						Vector3 val6 = ((num5 == 1 && normals != null && normals.Length == vertices.Length) ? normals[num17] : vertices[num17]);
						ShellSkinApplier.BaseUV(((Vector3)(ref val6)).normalized, out x, out v);
					}
					if (num13 - 1 < 6)
					{
						array2[num13 - 1] = x;
						array3[num13 - 1] = v;
					}
					if (v < num10 || v > num11)
					{
						flag2 = false;
					}
				}
			}
			if (!flag || num13 == 0 || !flag2)
			{
				array[j] = val2;
				continue;
			}
			float num18;
			float v2;
			if (num5 == 2 && num15 > 0)
			{
				num18 = val5.x / (float)num15;
				num18 -= Mathf.Floor(num18);
				v2 = val5.y / (float)num15;
			}
			else
			{
				Vector3 val7 = ((num5 == 1 && num14 > 0) ? (val4 / (float)num14) : (val3 / (float)num13));
				ShellSkinApplier.BaseUV(((Vector3)(ref val7)).normalized, out num18, out v2);
			}
			float num19 = num18 - num12;
			float num20 = ((num19 - Mathf.Floor(num19)) * 2f + 0.5f) % 1f;
			float num21 = (v2 - num10) / Mathf.Max(1E-05f, num11 - num10);
			bool num22 = ShellSkinApplier.CfgFlipH != null && ShellSkinApplier.CfgFlipH.Value;
			bool flag3 = ShellSkinApplier.CfgFlipV != null && ShellSkinApplier.CfgFlipV.Value;
			if (num22)
			{
				num20 = 1f - num20;
			}
			if (flag3)
			{
				num21 = 1f - num21;
			}
			array[j] = Sample(runtimeTexture, num20, num21);
		}
		try
		{
			if ((Object)(object)layer.paintingOverlayMat == (Object)null)
			{
				Type type = typeof(DysonSphere).Assembly.GetType("BuiltinConfig");
				FieldInfo fieldInfo = ((type != null) ? type.GetField("dysonLayerPaintingOverlayMaterial", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) : null);
				Material val8 = (Material)((fieldInfo != null) ? /*isinst with value type is only supported in some contexts*/: null);
				if ((Object)(object)val8 != (Object)null)
				{
					layer.paintingOverlayMat = Object.Instantiate<Material>(val8);
				}
			}
		}
		catch (Exception)
		{
		}
		if ((Object)(object)layer.paintingOverlayMat == (Object)null)
		{
			ManualLogSource log2 = DysonShellSkinPlugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)"涂装跳过: layer.paintingOverlayMat 为 null 且无法从 BuiltinConfig 补建");
			}
			return false;
		}
		try
		{
			if (layer.paintingGridMode != num)
			{
				layer.SetPaintingGrid(num);
			}
			layer.SetPaintingData(array);
		}
		catch (Exception ex3)
		{
			ManualLogSource log3 = DysonShellSkinPlugin.Log;
			if (log3 != null)
			{
				log3.LogWarning((object)("涂装写入失败(SetPaintingGrid/SetPaintingData): " + ex3.Message));
			}
			return false;
		}
		LastPaintInfo = GridName(num) + " · " + num3 + " 格 · 纬度带 " + BandLatMin.ToString("0") + "°~" + BandLatMax.ToString("0") + "°";
		ManualLogSource log4 = DysonShellSkinPlugin.Log;
		if (log4 != null)
		{
			log4.LogInfo((object)$"涂装完成: 层{layer.id} mode={num}({GridName(num)}) triCount={num2} cells={num3} 方向来源={LastDirSource} 纬度带=[{BandLatMin:0.0},{BandLatMax:0.0}]");
		}
		return true;
	}

	private static int DetectDirSource(Mesh grid, Vector3[] verts, Vector3[] nrms, Vector2[] uvs)
	{
		bool flag = uvs != null && uvs.Length == verts.Length;
		bool flag2 = nrms != null && nrms.Length == verts.Length;
		float num = 0f;
		float num2 = 0f;
		int num3 = Mathf.Max(1, verts.Length / 500);
		for (int i = 0; i < verts.Length; i += num3)
		{
			if (flag)
			{
				float num4 = Mathf.Abs(uvs[i].y - 0.5f) * 2f;
				if (num4 > num)
				{
					num = num4;
				}
			}
			if (flag2)
			{
				float num5 = Mathf.Abs(nrms[i].y);
				if (num5 > num2)
				{
					num2 = num5;
				}
			}
		}
		int num6 = ((flag && num >= 0.9f) ? 2 : ((flag2 && num2 >= 0.85f) ? 1 : 0));
		ManualLogSource log = DysonShellSkinPlugin.Log;
		if (log != null)
		{
			log.LogInfo((object)$"涂装方向来源探测: 选择={LastDirSourceOf(num6)} (uv覆盖={num:0.00}, 法线max|y|={num2:0.00})");
		}
		return num6;
	}

	private static string LastDirSourceOf(int src)
	{
		return src switch
		{
			1 => "normal", 
			2 => "uv", 
			_ => "position", 
		};
	}

	internal static string GridName(int m)
	{
		return m switch
		{
			3 => "geo4", 
			2 => "geo8", 
			1 => "geo20", 
			0 => "经纬", 
			_ => "?", 
		};
	}

	private static int ResolveMode(Mesh[] grids)
	{
		int num = ((ShellSkinApplier.CfgPaintMode != null) ? ShellSkinApplier.CfgPaintMode.Value : (-1));
		if (num == 0)
		{
			num = -1;
		}
		if (num >= 1)
		{
			if (num < grids.Length && (Object)(object)grids[num] != (Object)null)
			{
				return num;
			}
			return -1;
		}
		int num2 = ((ShellSkinApplier.CfgMaxPaintCells != null) ? ShellSkinApplier.CfgMaxPaintCells.Value : 200000);
		int num3 = -1;
		uint num4 = 0u;
		for (int i = 1; i < grids.Length; i++)
		{
			Mesh val = grids[i];
			if (!((Object)(object)val == (Object)null))
			{
				uint num5;
				try
				{
					num5 = val.GetIndexCount(0) / 2;
				}
				catch (Exception)
				{
					continue;
				}
				if (num5 != 0 && num5 <= (uint)num2 && num5 >= num4)
				{
					num4 = num5;
					num3 = i;
				}
			}
		}
		if (num3 < 0)
		{
			for (int j = 1; j < grids.Length; j++)
			{
				if ((Object)(object)grids[j] != (Object)null)
				{
					return j;
				}
			}
		}
		return num3;
	}

	private static void DumpGrid(int mode, Mesh grid)
	{
		try
		{
			int[] triangles;
			Vector3[] vertices;
			Vector2[] uv;
			Vector3[] normals;
			try
			{
				triangles = grid.triangles;
				vertices = grid.vertices;
				uv = grid.uv;
				normals = grid.normals;
			}
			catch (Exception ex)
			{
				File.WriteAllText(Path.Combine(Paths.ConfigPath, $"DysonShellSkin_grid_dump_{mode}.txt"), $"mode={mode} name={((Object)grid).name} 读取失败: {ex.Message}", Encoding.UTF8);
				return;
			}
			int num = ((triangles != null) ? (triangles.Length / 3) : 0);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"mode={mode} name={((Object)grid).name} verts={vertices.Length} tris={triangles.Length} triCount={num} subMeshes={grid.subMeshCount}");
			stringBuilder.AppendLine("uvCount=" + ((uv != null) ? uv.Length : (-1)) + " normalCount=" + ((normals != null) ? normals.Length : (-1)) + " uv2Count=" + ((grid.uv2 != null) ? grid.uv2.Length : (-1)));
			if (vertices != null)
			{
				stringBuilder.AppendLine("--- VERTS ---");
				for (int i = 0; i < vertices.Length; i++)
				{
					string text = ((normals != null && normals.Length == vertices.Length) ? (" n=" + normals[i].x.ToString("0.0000") + "," + normals[i].y.ToString("0.0000") + "," + normals[i].z.ToString("0.0000")) : "");
					string text2 = ((uv != null && uv.Length == vertices.Length) ? (" uv=" + uv[i].x.ToString("0.0000") + "," + uv[i].y.ToString("0.0000")) : "");
					stringBuilder.AppendLine($"v[{i}]={vertices[i].x:0.0000},{vertices[i].y:0.0000},{vertices[i].z:0.0000}{text}{text2}");
				}
			}
			if (triangles != null)
			{
				stringBuilder.AppendLine("--- TRIS ---");
				for (int j = 0; j < num; j++)
				{
					stringBuilder.AppendLine($"t[{j}]={triangles[j * 3]},{triangles[j * 3 + 1]},{triangles[j * 3 + 2]}");
				}
			}
			string text3 = Path.Combine(Paths.ConfigPath, $"DysonShellSkin_grid_dump_{mode}.txt");
			File.WriteAllText(text3, stringBuilder.ToString(), Encoding.UTF8);
			ManualLogSource log = DysonShellSkinPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)("涂装网格转储已写入: " + text3 + $" (verts={vertices.Length}, tris={num})"));
			}
		}
		catch (Exception ex2)
		{
			ManualLogSource log2 = DysonShellSkinPlugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)("网格转储失败: " + ex2.Message));
			}
		}
	}

	public static Color32 Sample(Texture2D tex, float u, float v)
	{
		//IL_0003: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Unknown result type (might be due to invalid IL or missing references)
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		Color pixelBilinear = tex.GetPixelBilinear(u, v);
		return new Color32((byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.r, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.g, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.b, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.a, 0f, 1f) * 255f));
	}
}
[BepInPlugin("local.DysonShellSkin", "DysonShellSkin", "1.4.2")]
public class DysonShellSkinPlugin : BaseUnityPlugin
{
	public const string GUID = "local.DysonShellSkin";

	public const string NAME = "DysonShellSkin";

	public const string VER = "1.4.2";

	internal static ManualLogSource Log;

	private Harmony _harmony;

	private void Awake()
	{
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Expected O, but got Unknown
		//IL_0037: Unknown result type (might be due to invalid IL or missing references)
		//IL_0041: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		ShellSkinApplier.Init(((BaseUnityPlugin)this).Config, Log);
		GameObject val = new GameObject("DysonShellSkin.Controller");
		val.AddComponent<SkinController>();
		Object.DontDestroyOnLoad((Object)val);
		_harmony = new Harmony("local.DysonShellSkin");
		Type[] array = new Type[4]
		{
			typeof(DysonSphereSegmentRenderer_DrawModels_Patch),
			typeof(DysonSphereLayer_Import_Patch),
			typeof(DysonSphere_AddLayerOnId_Patch),
			typeof(DysonSphere_AddLayer_Patch)
		};
		foreach (Type type in array)
		{
			try
			{
				_harmony.PatchAll(type);
				Log.LogInfo((object)("补丁应用成功: " + type.Name));
			}
			catch (Exception ex)
			{
				Log.LogWarning((object)("补丁应用失败: " + type.Name + " -> " + ex.Message));
			}
		}
		Log.LogInfo((object)"[DysonShellSkin] v1.4.2 已加载。戴森球编辑界面内按 Alt+D 打开编辑面板");
	}

	private void OnDestroy()
	{
		OverlaySkinRenderer.Shutdown();
		if (_harmony != null)
		{
			_harmony.UnpatchSelf();
		}
	}
}
[HarmonyPatch(typeof(DysonSphereSegmentRenderer), "DrawModels")]
internal static class DysonSphereSegmentRenderer_DrawModels_Patch
{
	private static void Postfix(DysonSphereSegmentRenderer __instance, ERenderPlace place)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		OverlaySkinRenderer.OnDrawModels(__instance, place);
	}
}
[HarmonyPatch(typeof(DysonSphereLayer), "Import")]
internal static class DysonSphereLayer_Import_Patch
{
	private static void Postfix(DysonSphereLayer __instance)
	{
		ShellSkinApplier.OnLayerRefresh(__instance);
	}
}
[HarmonyPatch(typeof(DysonSphere), "AddLayerOnId")]
internal static class DysonSphere_AddLayerOnId_Patch
{
	private static void Postfix(DysonSphereLayer __result)
	{
		if (__result != null)
		{
			ShellSkinApplier.OnLayerRefresh(__result);
		}
	}
}
[HarmonyPatch(typeof(DysonSphere), "AddLayer")]
internal static class DysonSphere_AddLayer_Patch
{
	private static void Postfix(DysonSphereLayer __result)
	{
		if (__result != null)
		{
			ShellSkinApplier.OnLayerRefresh(__result);
		}
	}
}
internal static class ShellSkinApplier
{
	private static ManualLogSource _log;

	internal static ConfigEntry<KeyboardShortcut> CfgPanelKey;

	internal static ConfigEntry<int> CfgMaxSize;

	internal static ConfigEntry<int> CfgPaintMode;

	internal static ConfigEntry<int> CfgMaxPaintCells;

	internal static ConfigEntry<bool> CfgDebug;

	internal static ConfigEntry<int> CfgFlipbookFps;

	internal static ConfigEntry<float> CfgBandMax;

	internal static ConfigEntry<float> CfgBandMin;

	internal static ConfigEntry<bool> CfgOverlayEnabled;

	internal static ConfigEntry<float> CfgOverlayOpacity;

	internal static ConfigEntry<int> CfgOverlaySegLon;

	internal static ConfigEntry<int> CfgOverlaySegLat;

	internal static ConfigEntry<bool> CfgDrawInStarmap;

	internal static ConfigEntry<float> CfgLonOffset;

	internal static ConfigEntry<bool> CfgFlipH;

	internal static ConfigEntry<bool> CfgFlipV;

	internal static string StatusMessage = "戴森球界面内按 Alt+D 打开编辑面板";

	private static readonly HashSet<long> _paintedKeys = new HashSet<long>();

	private static readonly Dictionary<long, Texture2D> _texCache = new Dictionary<long, Texture2D>();

	private static readonly HashSet<long> _texFailed = new HashSet<long>();

	private static readonly Dictionary<long, Vector4> _cropCache = new Dictionary<long, Vector4>();

	internal static int SelectedLayer { get; set; } = 1;

	internal static int CurrentStarIndex { get; set; } = -1;

	internal static void Init(ConfigFile cfg, ManualLogSource log)
	{
		//IL_0021: 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_008a: Expected O, but got Unknown
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Expected O, but got Unknown
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0145: Expected O, but got Unknown
		//IL_0173: Unknown result type (might be due to invalid IL or missing references)
		//IL_017d: Expected O, but got Unknown
		//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b2: Expected O, but got Unknown
		//IL_01fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0205: Expected O, but got Unknown
		//IL_0233: Unknown result type (might be due to invalid IL or missing references)
		//IL_023d: Expected O, but got Unknown
		//IL_026b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0275: Expected O, but got Unknown
		_log = log;
		CfgPanelKey = cfg.Bind<KeyboardShortcut>("通用", "编辑模式热键", new KeyboardShortcut((KeyCode)100, (KeyCode[])(object)new KeyCode[1] { (KeyCode)308 }), "戴森球编辑界面内按 Alt+D 打开/关闭编辑面板");
		CfgMaxSize = cfg.Bind<int>("图片", "最大边长", 8192, "导入图片超过此边长会自动缩放");
		CfgPaintMode = cfg.Bind<int>("涂装", "网格模式", -1, new ConfigDescription("-1=自动选最密;0=经纬网格;1/2/3=geo20/8/4", (AcceptableValueBase)(object)new AcceptableValueList<int>(new int[5] { -1, 0, 1, 2, 3 }), Array.Empty<object>()));
		CfgMaxPaintCells = cfg.Bind<int>("涂装", "最大格子数", 200000, "自动模式下超过此格子数的网格不选用");
		CfgDebug = cfg.Bind<bool>("通用", "调试日志", false, "输出涂装网格数据转储(排查用)");
		CfgFlipbookFps = cfg.Bind<int>("帧序列", "播放帧率", 10, new ConfigDescription("1~30", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 30), Array.Empty<object>()));
		CfgOverlayEnabled = cfg.Bind<bool>("高清叠加", "启用", true, "高清晰度显示层(自建高分辨率网格),比官方涂装格子清晰数倍");
		CfgOverlayOpacity = cfg.Bind<float>("高清叠加", "不透明度", 1f, new ConfigDescription("0.05~1", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 1f), Array.Empty<object>()));
		CfgOverlaySegLon = cfg.Bind<int>("高清叠加", "经向分段", 384, new ConfigDescription("128~1024,越大越清晰(消耗略增)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(128, 1024), Array.Empty<object>()));
		CfgOverlaySegLat = cfg.Bind<int>("高清叠加", "纬向分段", 192, new ConfigDescription("64~512,越大越清晰(消耗略增)", (AcceptableValueBase)(object)new AcceptableValueRange<int>(64, 512), Array.Empty<object>()));
		CfgDrawInStarmap = cfg.Bind<bool>("高清叠加", "星图中显示", false, "一般无需开启");
		CfgBandMax = cfg.Bind<float>("涂装", "纬度上限", 55f, new ConfigDescription("图片只显示在此纬度以下(北纬,度)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 90f), Array.Empty<object>()));
		CfgBandMin = cfg.Bind<float>("涂装", "纬度下限", -55f, new ConfigDescription("图片只显示在此纬度以上(南纬,度)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-90f, -10f), Array.Empty<object>()));
		CfgLonOffset = cfg.Bind<float>("涂装", "朝向经度", 0f, new ConfigDescription("图片中心对着哪条经线(-180~180)", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-180f, 180f), Array.Empty<object>()));
		CfgFlipH = cfg.Bind<bool>("涂装", "水平翻转", true, "修正球外观看的左右镜像(默认开)");
		CfgFlipV = cfg.Bind<bool>("涂装", "垂直翻转", false, "图片上下颠倒时开启");
	}

	internal static bool PanelKeyDown()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Invalid comparison between Unknown and I4
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Invalid comparison between Unknown and I4
		KeyboardShortcut value = CfgPanelKey.Value;
		try
		{
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				return true;
			}
			if ((int)((KeyboardShortcut)(ref value)).MainKey != 0 && ((KeyboardShortcut)(ref value)).Modifiers != null && Input.GetKeyDown(((KeyboardShortcut)(ref value)).MainKey))
			{
				bool flag = Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307);
				foreach (KeyCode modifier in ((KeyboardShortcut)(ref value)).Modifiers)
				{
					if (((int)modifier == 308 || (int)modifier == 307) && flag)
					{
						return true;
					}
				}
			}
		}
		catch (Exception)
		{
		}
		return false;
	}

	internal static Texture2D GetRuntimeTexture(SkinRecord r)
	{
		long key = r.Key;
		if (_texCache.TryGetValue(key, out var value) && (Object)(object)value != (Object)null)
		{
			return value;
		}
		if (_texFailed.Contains(key))
		{
			return null;
		}
		if (string.IsNullOrEmpty(r.imagePath))
		{
			return null;
		}
		string err;
		Texture2D val = LoadTexture(r.imagePath, out err);
		if ((Object)(object)val == (Object)null)
		{
			_texFailed.Add(key);
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogWarning((object)$"层{r.layerId}图片加载失败({r.imagePath}): {err}");
			}
			return null;
		}
		string info;
		Texture2D val2 = BakeEquirect(val, out info);
		Object.Destroy((Object)(object)val);
		ManualLogSource log2 = _log;
		if (log2 != null)
		{
			log2.LogInfo((object)("贴图预处理完成: " + info));
		}
		_texCache[key] = val2;
		return val2;
	}

	private static Texture2D BakeEquirect(Texture2D src, out string info)
	{
		//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_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Expected O, but got Unknown
		//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_010d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_0136: Unknown result type (might be due to invalid IL or missing references)
		//IL_013b: Unknown result type (might be due to invalid IL or missing references)
		//IL_014a: 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)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		float num = Mathf.Clamp((CfgBandMax != null) ? CfgBandMax.Value : 55f, 10f, 90f);
		float num2 = Mathf.Clamp((CfgBandMin != null) ? CfgBandMin.Value : (-55f), -90f, -10f);
		float num3 = (num2 + 90f) / 180f;
		float num4 = (num + 90f) / 180f;
		Vector4 val = ComputeCrop(src);
		Texture2D val2 = new Texture2D(2048, 1024, (TextureFormat)4, true, false);
		Color32[] array = (Color32[])(object)new Color32[2097152];
		int num5 = Mathf.Clamp((int)(num3 * 1024f), 0, 1024);
		int num6 = Mathf.Clamp((int)Math.Ceiling(num4 * 1024f), 0, 1024);
		for (int i = num5; i < num6; i++)
		{
			float num7 = (((float)i + 0.5f) / 1024f - num3) / Mathf.Max(1E-05f, num4 - num3);
			float num8 = Mathf.Lerp(val.w, val.y, num7);
			for (int j = 0; j < 2048; j++)
			{
				float num9 = Mathf.Lerp(val.x, val.z, ((float)j + 0.5f) / 2048f);
				Color pixelBilinear = src.GetPixelBilinear(num9, num8);
				array[i * 2048 + j] = new Color32((byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.r, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.g, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.b, 0f, 1f) * 255f), (byte)Mathf.RoundToInt(Mathf.Clamp(pixelBilinear.a, 0f, 1f) * 255f));
			}
		}
		val2.SetPixels32(array);
		((Texture)val2).filterMode = (FilterMode)1;
		((Texture)val2).anisoLevel = 4;
		((Texture)val2).wrapModeU = (TextureWrapMode)0;
		((Texture)val2).wrapModeV = (TextureWrapMode)1;
		val2.Apply(true, false);
		try
		{
			val2.Compress(true);
		}
		catch (Exception)
		{
		}
		info = $"烘焙 {2048}x{1024} 球面贴图(纬度带 {num2:0}°~{num:0}°,行 {num5}~{num6},带外全透明)";
		return val2;
	}

	internal static void InvalidateAssets(int starIndex, int layerId)
	{
		long num = (long)starIndex * 16L + layerId;
		if (_texCache.TryGetValue(num, out var value) && (Object)(object)value != (Object)null)
		{
			Object.Destroy((Object)(object)value);
		}
		_texCache.Remove(num);
		_texFailed.Remove(num);
		_cropCache.Remove(num);
	}

	internal static Vector4 GetTexCrop(SkinRecord r)
	{
		//IL_0016: 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_003c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		long key = r.Key;
		if (_cropCache.TryGetValue(key, out var value))
		{
			return value;
		}
		Texture2D runtimeTexture = GetRuntimeTexture(r);
		value = (Vector4)(((Object)(object)runtimeTexture != (Object)null) ? ComputeCrop(runtimeTexture) : new Vector4(0f, 0f, 1f, 1f));
		_cropCache[key] = value;
		return value;
	}

	internal static Vector2 GetTexContentSize(SkinRecord r)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_002c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: 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)
		Texture2D runtimeTexture = GetRuntimeTexture(r);
		Vector4 texCrop = GetTexCrop(r);
		if ((Object)(object)runtimeTexture == (Object)null)
		{
			return new Vector2(1f, 1f);
		}
		float num = Mathf.Max(0.001f, texCrop.z - texCrop.x) * (float)((Texture)runtimeTexture).width;
		float num2 = Mathf.Max(0.001f, texCrop.w - texCrop.y) * (float)((Texture)runtimeTexture).height;
		return new Vector2(num, num2);
	}

	private static Vector4 ComputeCrop(Texture2D t)
	{
		//IL_013d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_011f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			int num = 48;
			int num2 = 48;
			float num3 = 1f;
			float num4 = 1f;
			float num5 = 0f;
			float num6 = 0f;
			bool flag = false;
			for (int i = 0; i < num2; i++)
			{
				for (int j = 0; j < num; j++)
				{
					if (t.GetPixel(j * (((Texture)t).width - 1) / (num - 1), i * (((Texture)t).height - 1) / (num2 - 1)).a > 0.1f)
					{
						flag = true;
						float num7 = (float)j / (float)(num - 1);
						float num8 = (float)i / (float)(num2 - 1);
						if (num7 < num3)
						{
							num3 = num7;
						}
						if (num7 > num5)
						{
							num5 = num7;
						}
						if (num8 < num4)
						{
							num4 = num8;
						}
						if (num8 > num6)
						{
							num6 = num8;
						}
					}
				}
			}
			if (!flag)
			{
				return new Vector4(0f, 0f, 1f, 1f);
			}
			float num9 = (num5 - num3) * 0.04f + 0.005f;
			float num10 = (num6 - num4) * 0.04f + 0.005f;
			return new Vector4(Mathf.Clamp01(num3 - num9), Mathf.Clamp01(num4 - num10), Mathf.Clamp01(num5 + num9), Mathf.Clamp01(num6 + num10));
		}
		catch (Exception)
		{
			return new Vector4(0f, 0f, 1f, 1f);
		}
	}

	internal static Texture2D LoadTexture(string path, out string err)
	{
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0093: Expected O, but got Unknown
		err = null;
		if (string.IsNullOrEmpty(path) || !File.Exists(path))
		{
			err = "文件不存在";
			return null;
		}
		string text = (Path.GetExtension(path) ?? "").ToLowerInvariant();
		if (text != ".png" && text != ".jpg" && text != ".jpeg")
		{
			err = "仅支持 PNG/JPG 图片";
			return null;
		}
		byte[] array;
		try
		{
			array = File.ReadAllBytes(path);
		}
		catch (Exception ex)
		{
			err = "读取失败: " + ex.Message;
			return null;
		}
		Texture2D val = null;
		try
		{
			val = new Texture2D(2, 2, (TextureFormat)4, true, false);
			if (!ImageConversion.LoadImage(val, array, false))
			{
				Object.Destroy((Object)(object)val);
				err = "图片解码失败(仅支持 PNG/JPG)";
				return null;
			}
			((Texture)val).filterMode = (FilterMode)1;
			((Texture)val).anisoLevel = 4;
			val = DownscaleIfNeeded(val);
			try
			{
				val.Compress(true);
			}
			catch (Exception ex2)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("压缩贴图跳过: " + ex2.Message));
				}
			}
		}
		catch (Exception ex3)
		{
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			err = "创建贴图失败: " + ex3.Message;
			return null;
		}
		return val;
	}

	private static Texture2D DownscaleIfNeeded(Texture2D src)
	{
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Expected O, but got Unknown
		//IL_00d2: Expected O, but got Unknown
		int num = Mathf.Max(((Texture)src).width, ((Texture)src).height);
		int num2 = ((CfgMaxSize != null) ? CfgMaxSize.Value : 8192);
		if (num <= num2)
		{
			return src;
		}
		float num3 = (float)num2 / (float)num;
		int num4 = Mathf.Max(1, Mathf.RoundToInt((float)((Texture)src).width * num3));
		int num5 = Mathf.Max(1, Mathf.RoundToInt((float)((Texture)src).height * num3));
		RenderTexture active = RenderTexture.active;
		RenderTexture temporary = RenderTexture.GetTemporary(num4, num5, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
		Graphics.Blit((Texture)(object)src, temporary);
		RenderTexture.active = temporary;
		Texture2D val = new Texture2D(num4, num5, (TextureFormat)4, true, false);
		val.ReadPixels(new Rect(0f, 0f, (float)num4, (float)num5), 0, 0);
		val.Apply(true, false);
		RenderTexture.active = active;
		RenderTexture.ReleaseTemporary(temporary);
		Object.Destroy((Object)(object)src);
		ManualLogSource log = _log;
		if (log != null)
		{
			log.LogInfo((object)$"图片过大,已缩放到 {num4}x{num5}");
			return val;
		}
		return val;
	}

	public static string ApplyNow(int starIndex, int layerId)
	{
		SkinRecord skinRecord = SkinStore.TryGet(starIndex, layerId);
		if (skinRecord == null)
		{
			return "请先『导入图片』或『导入视频』";
		}
		if (string.IsNullOrEmpty(skinRecord.imagePath))
		{
			return "请先『导入图片』";
		}
		GameData val;
		try
		{
			val = GameMain.data;
		}
		catch (Exception)
		{
			val = null;
		}
		if (val == null)
		{
			return "未进入游戏";
		}
		if (val.dysonSpheres == null || starIndex < 0 || starIndex >= val.dysonSpheres.Length)
		{
			return "戴森球数据未加载";
		}
		DysonSphere val2 = val.dysonSpheres[starIndex];
		if (val2 == null || val2.layersIdBased == null)
		{
			return "戴森球尚未加载(进入该星系后会自动生效)";
		}
		if (layerId < 1 || layerId >= val2.layersIdBased.Length)
		{
			return "层级编号无效";
		}
		DysonSphereLayer val3 = val2.layersIdBased[layerId];
		if (val3 == null)
		{
			return "层" + layerId + "尚未建成(先在编辑器里建层)";
		}
		bool flag;
		try
		{
			flag = PaintMapper.ApplyToLayer(val3, skinRecord);
		}
		catch (Exception ex2)
		{
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogWarning((object)("应用涂装异常: " + ex2));
			}
			return "涂装执行异常(详见日志)";
		}
		if (!flag)
		{
			return "涂装未执行(图片未就绪或格子数超限,详见日志)";
		}
		_paintedKeys.Add(skinRecord.Key);
		StatusMessage = "已应用 · 层" + layerId + " · " + PaintMapper.LastPaintInfo;
		return null;
	}

	public static void ApplyImageToLayer(int starIndex, int layerId, string path)
	{
		string err;
		Texture2D val = LoadTexture(path, out err);
		if ((Object)(object)val == (Object)null)
		{
			StatusMessage = "导入失败: " + err;
			ManualLogSource log = _log;
			if (log != null)
			{
				log.LogWarning((object)StatusMessage);
			}
			return;
		}
		Object.Destroy((Object)(object)val);
		SkinStore.GetOrCreate(starIndex, layerId).imagePath = path;
		InvalidateAssets(starIndex, layerId);
		SkinStore.Save();
		string text = ApplyNow(starIndex, layerId);
		StatusMessage = ((text == null) ? ("已应用 · 层" + layerId + " · " + Path.GetFileName(path) + " · " + PaintMapper.LastPaintInfo) : ("图片已导入,但 " + text));
		ManualLogSource log2 = _log;
		if (log2 != null)
		{
			log2.LogInfo((object)StatusMessage);
		}
	}

	public static void RemoveLayerSkin(int starIndex, int layerId)
	{
		InvalidateAssets(starIndex, layerId);
		if (SkinStore.Remove(starIndex, layerId))
		{
			SkinStore.Save();
			_paintedKeys.Remove((long)starIndex * 16L + layerId);
			StatusMessage = "已移除层" + layerId + "的外观";
		}
	}

	public static void ApplyFramesToLayer(int starIndex, int layerId, string folder)
	{
		if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
		{
			StatusMessage = "导入失败: 文件夹不存在";
			return;
		}
		int num = Directory.GetFiles(folder, "*.png").Length;
		if (num == 0)
		{
			StatusMessage = "导入失败: 文件夹内没有 PNG 帧";
			return;
		}
		SkinRecord orCreate = SkinStore.GetOrCreate(starIndex, layerId);
		orCreate.isFrames = true;
		orCreate.framesPath = folder;
		orCreate.imagePath = null;
		SkinStore.Save();
		InvalidateAssets(starIndex, layerId);
		OverlaySkinRenderer.EnsureFlipbook(folder);
		float num2 = ((CfgFlipbookFps != null) ? ((float)CfgFlipbookFps.Value) : 10f);
		StatusMessage = "已应用 · 层" + layerId + " · 帧序列 " + num + " 帧 · " + num2 + "fps 循环";
		ManualLogSource log = _log;
		if (log != null)
		{
			log.LogInfo((object)StatusMessage);
		}
	}

	public static void RepaintAll()
	{
		_paintedKeys.Clear();
		Poll();
	}

	public static void ClearAllSkins()
	{
		foreach (SkinRecord record in SkinStore.Records)
		{
			InvalidateAssets(record.starIndex, record.layerId);
		}
		SkinStore.Records.Clear();
		SkinStore.Save();
		_paintedKeys.Clear();
		StatusMessage = "已清除全部外观";
	}

	public static void Poll()
	{
		try
		{
			GameData data = GameMain.data;
			if (data == null || data.galaxy == null || data.galaxy.stars == null)
			{
				return;
			}
			foreach (SkinRecord record in SkinStore.Records)
			{
				if (record.starIndex < 0 || record.starIndex >= data.galaxy.stars.Length)
				{
					continue;
				}
				DysonSphere val = data.dysonSpheres[record.starIndex];
				if (val == null || val.layersIdBased == null || record.layerId < 1 || record.layerId >= val.layersIdBased.Length)
				{
					continue;
				}
				DysonSphereLayer val2 = val.layersIdBased[record.layerId];
				long key = record.Key;
				if (record.isFrames)
				{
					if (val2 != null)
					{
						OverlaySkinRenderer.EnsureFlipbook(record.framesPath);
					}
				}
				else
				{
					if (val2 == null || _paintedKeys.Contains(key) || string.IsNullOrEmpty(record.imagePath))
					{
						continue;
					}
					bool flag = false;
					try
					{
						flag = PaintMapper.ApplyToLayer(val2, record);
					}
					catch (Exception ex)
					{
						ManualLogSource log = _log;
						if (log != null)
						{
							log.LogDebug((object)("涂装路径异常: " + ex.Message));
						}
					}
					if (flag)
					{
						_paintedKeys.Add(key);
					}
				}
			}
		}
		catch (Exception ex2)
		{
			ManualLogSource log2 = _log;
			if (log2 != null)
			{
				log2.LogDebug((object)("Poll 异常: " + ex2));
			}
		}
	}

	public static void OnLayerRefresh(DysonSphereLayer layer)
	{
		if (layer == null || layer.dysonSphere == null || layer.dysonSphere.starData == null)
		{
			return;
		}
		SkinRecord skinRecord = SkinStore.TryGet(layer.dysonSphere.starData.index, layer.id);
		if (skinRecord == null)
		{
			return;
		}
		if (skinRecord.isFrames)
		{
			if (!string.IsNullOrEmpty(skinRecord.framesPath))
			{
				OverlaySkinRenderer.EnsureFlipbook(skinRecord.framesPath);
			}
		}
		else
		{
			if (string.IsNullOrEmpty(skinRecord.imagePath))
			{
				return;
			}
			try
			{
				PaintMapper.ApplyToLayer(layer, skinRecord);
			}
			catch (Exception ex)
			{
				ManualLogSource log = _log;
				if (log != null)
				{
					log.LogDebug((object)("OnLayerRefresh 异常: " + ex.Message));
				}
			}
		}
	}

	internal static int RecordAxisInt(SkinRecord r)
	{
		return 1;
	}

	internal static void BaseUV(Vector3 n, out float u01, out float v01)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		v01 = 0.5f + Mathf.Asin(Mathf.Clamp(n.y, -1f, 1f)) / (float)Math.PI;
		u01 = Mathf.Atan2(n.z, n.x) / ((float)Math.PI * 2f) + 0.5f;
		u01 -= Mathf.Floor(u01);
	}
}
public class SkinController : MonoBehaviour
{
	private bool _panelOpen;

	private Rect _winRect = new Rect(60f, 80f, 400f, 380f);

	private float _pollTimer;

	private float _gateLogAt;

	private int _selLayer = 1;

	private bool _stylesBuilt;

	private GUIStyle _hintStyle;

	private GUIStyle _layerActive;

	public static void Init(ConfigFile _, ManualLogSource log)
	{
	}

	private void Awake()
	{
		Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
	}

	private static bool IsDysonEditorOpen()
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		try
		{
			if ((int)DysonSphere.renderPlace == 2)
			{
				return true;
			}
			UIGame val = (((Object)(object)UIRoot.instance != (Object)null && (Object)(object)UIRoot.instance.uiGame != (Object)null) ? UIRoot.instance.uiGame : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			UIDysonEditor dysonEditor = val.dysonEditor;
			if ((Object)(object)dysonEditor == (Object)null)
			{
				return false;
			}
			try
			{
				if (((ManualBehaviour)dysonEditor).active)
				{
					return true;
				}
			}
			catch (Exception)
			{
			}
			GameObject gameObject = ((Component)dysonEditor).gameObject;
			return (Object)(object)gameObject != (Object)null && gameObject.activeInHierarchy;
		}
		catch (Exception)
		{
			return false;
		}
	}

	private void Update()
	{
		bool flag = IsDysonEditorOpen();
		if (_panelOpen && !flag)
		{
			_panelOpen = false;
		}
		bool flag2 = false;
		try
		{
			flag2 = ShellSkinApplier.PanelKeyDown();
		}
		catch (Exception)
		{
		}
		if (flag2)
		{
			if (flag)
			{
				_panelOpen = !_panelOpen;
			}
			else if (Time.time >= _gateLogAt)
			{
				_gateLogAt = Time.time + 5f;
				ManualLogSource log = DysonShellSkinPlugin.Log;
				if (log != null)
				{
					log.LogInfo((object)"编辑热键已按下,但当前不在戴森球编辑界面,面板未打开");
				}
			}
		}
		try
		{
			OverlaySkinRenderer.UpdateFlipbook(ShellSkinApplier.CfgFlipbookFps.Value);
		}
		catch (Exception)
		{
		}
		_pollTimer -= Time.deltaTime;
		if (_pollTimer <= 0f)
		{
			_pollTimer = 2f;
			try
			{
				ShellSkinApplier.Poll();
			}
			catch (Exception)
			{
			}
		}
	}

	private void OnGUI()
	{
		//IL_0025: 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_0045: Expected O, but got Unknown
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		if (_panelOpen)
		{
			if (!IsDysonEditorOpen())
			{
				_panelOpen = false;
				return;
			}
			EnsureStyles();
			_winRect = GUILayout.Window(54530, _winRect, new WindowFunction(DrawWindow), "DysonShellSkin v1.4.2 · 编辑模式(戴森球界面)", Array.Empty<GUILayoutOption>());
		}
	}

	private void EnsureStyles()
	{
		//IL_0014: 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: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Expected O, but got Unknown
		//IL_0047: 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_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		if (!_stylesBuilt)
		{
			_hintStyle = new GUIStyle(GUI.skin.label)
			{
				fontSize = 11,
				wordWrap = true
			};
			_hintStyle.normal.textColor = new Color(0.75f, 0.78f, 0.82f);
			_layerActive = new GUIStyle(GUI.skin.button)
			{
				fontStyle = (FontStyle)1
			};
			_stylesBuilt = true;
		}
	}

	private void DrawWindow(int id)
	{
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0574: Unknown result type (might be due to invalid IL or missing references)
		//IL_0579: Unknown result type (might be due to invalid IL or missing references)
		//IL_05bf: Unknown result type (might be due to invalid IL or missing references)
		GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
		GameData val = null;
		StarData val2 = null;
		try
		{
			val = GameMain.data;
		}
		catch (Exception)
		{
		}
		try
		{
			val2 = ((val != null) ? val.localStar : null);
		}
		catch (Exception)
		{
		}
		int num = val2?.index ?? (-1);
		DysonSphere val3 = null;
		try
		{
			if (val != null && val2 != null && val.dysonSpheres != null && val2.index >= 0 && val2.index < val.dysonSpheres.Length)
			{
				val3 = val.dysonSpheres[val2.index];
			}
		}
		catch (Exception)
		{
		}
		if (val2 == null)
		{
			GUILayout.Label("未检测到当前星系。", _hintStyle, Array.Empty<GUILayoutOption>());
			GUILayout.EndVertical();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f));
			return;
		}
		GUILayout.Label("当前星球: " + (val2.name ?? ("星" + num)), _hintStyle, Array.Empty<GUILayoutOption>());
		SkinRecord skinRecord = ((num >= 0) ? SkinStore.TryGet(num, _selLayer) : null);
		string text = ((skinRecord == null) ? "(未导入)" : (string.IsNullOrEmpty(skinRecord.imagePath) ? "(未导入图片)" : skinRecord.imagePath));
		GUILayout.Label("层" + _selLayer + ": " + text, _hintStyle, Array.Empty<GUILayoutOption>());
		if (!string.IsNullOrEmpty(PaintMapper.LastPaintInfo))
		{
			GUILayout.Label("涂装: " + PaintMapper.LastPaintInfo, _hintStyle, Array.Empty<GUILayoutOption>());
		}
		if (!string.IsNullOrEmpty(ShellSkinApplier.StatusMessage))
		{
			GUILayout.Label(ShellSkinApplier.StatusMessage, _hintStyle, Array.Empty<GUILayoutOption>());
		}
		GUILayout.Space(6f);
		GUILayout.Label("<b>① 选择壳层级(1~10)</b>", Array.Empty<GUILayoutOption>());
		for (int i = 0; i < 2; i++)
		{
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			for (int j = 1; j <= 5; j++)
			{
				int num2 = i * 5 + j;
				bool flag = val3 != null && val3.layersIdBased != null && num2 < val3.layersIdBased.Length && val3.layersIdBased[num2] != null;
				string obj = ((_selLayer == num2) ? ("▶ " + num2) : (num2 + (flag ? "" : " 空")));
				GUIStyle val4 = ((_selLayer == num2) ? _layerActive : GUI.skin.button);
				if (GUILayout.Button(obj, val4, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(24f) }))
				{
					_selLayer = num2;
					if (!flag)
					{
						ShellSkinApplier.StatusMessage = "层" + num2 + " 尚未建成,建成后再点『应用』即可";
					}
				}
			}
			GUILayout.EndHorizontal();
		}
		GUILayout.Space(6f);
		GUILayout.Label("<b>② 导入图片到层" + _selLayer + "</b>", Array.Empty<GUILayoutOption>());
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("选择图片…", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(30f) }))
		{
			try
			{
				string text2 = NativeFileDialog.OpenImageDialog("选择贴到层" + _selLayer + "的图片 (PNG/JPG)");
				if (!string.IsNullOrEmpty(text2) && num >= 0)
				{
					ShellSkinApplier.ApplyImageToLayer(num, _selLayer, text2);
				}
				else if (string.IsNullOrEmpty(text2))
				{
					ShellSkinApplier.StatusMessage = "未选择图片(对话框被取消,或被游戏窗口遮挡)";
				}
			}
			catch (Exception ex4)
			{
				ShellSkinApplier.StatusMessage = "对话框失败: " + ex4.Message;
			}
		}
		if (GUILayout.Button("移除此层外观", (GUILayoutOption[])(object)new GUILayoutOption[2]
		{
			GUILayout.Height(30f),
			GUILayout.Width(120f)
		}))
		{
			ShellSkinApplier.RemoveLayerSkin(num, _selLayer);
		}
		GUILayout.EndHorizontal();
		GUILayout.Space(4f);
		GUILayout.Space(6f);
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		GUILayout.Label("图片翻转", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(64f) });
		bool flag2 = GUILayout.Toggle(ShellSkinApplier.CfgFlipH.Value, "水平翻转", Array.Empty<GUILayoutOption>());
		if (flag2 != ShellSkinApplier.CfgFlipH.Value)
		{
			ShellSkinApplier.CfgFlipH.Value = flag2;
			ShellSkinApplier.RepaintAll();
		}
		bool flag3 = GUILayout.Toggle(ShellSkinApplier.CfgFlipV.Value, "垂直翻转", Array.Empty<GUILayoutOption>());
		if (flag3 != ShellSkinApplier.CfgFlipV.Value)
		{
			ShellSkinApplier.CfgFlipV.Value = flag3;
			ShellSkinApplier.RepaintAll();
		}
		GUILayout.EndHorizontal();
		GUILayout.Label("<b>③ 应用(生成外观)</b>", Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("应  用", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(34f) }))
		{
			string text3 = ((num >= 0) ? ShellSkinApplier.ApplyNow(num, _selLayer) : "未检测到当前星球");
			if (text3 != null)
			{
				ShellSkinApplier.StatusMessage = "应用失败: " + text3;
			}
		}
		if (GUILayout.Button("清除全部星球全部外观", Array.Empty<GUILayoutOption>()))
		{
			ShellSkinApplier.ClearAllSkins();
		}
		GUILayout.Space(6f);
		bool flag4 = GUILayout.Toggle(ShellSkinApplier.CfgOverlayEnabled.Value, "显示层(帧序列)", Array.Empty<GUILayoutOption>());
		if (flag4 != ShellSkinApplier.CfgOverlayEnabled.Value)
		{
			ShellSkinApplier.CfgOverlayEnabled.Value = flag4;
		}
		GUILayout.Space(6f);
		GUILayout.Label("· 图片自动适配游戏纬度限制带(当前 -" + PaintMapper.BandLatMax.ToString("0") + "°~+" + PaintMapper.BandLatMax.ToString("0") + "°),带外两极不动\n· 颜色随游戏存档保存;读档/新层自动重新生成\n· 编辑热键: " + ((object)ShellSkinApplier.CfgPanelKey.Value/*cast due to .constrained prefix*/).ToString() + "(仅戴森球界面)", _hintStyle, Array.Empty<GUILayoutOption>());
		GUILayout.EndVertical();
		GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f));
	}
}
public class SkinRecord
{
	public int starIndex;

	public int layerId;

	public string imagePath;

	public bool isVideo;

	public string videoPath;

	public bool isFrames;

	public string framesPath;

	public long Key => (long)starIndex * 16L + layerId;
}
internal static class SkinStore
{
	private static readonly List<SkinRecord> _records = new List<SkinRecord>();

	private static bool _loaded;

	public static string StorePath => Path.Combine(Paths.ConfigPath, "DysonShellSkin.skins.dat");

	public static IList<SkinRecord> Records => _records;

	private static void EnsureLoaded()
	{
		if (_loaded)
		{
			return;
		}
		_loaded = true;
		try
		{
			string storePath = StorePath;
			if (!File.Exists(storePath))
			{
				return;
			}
			string[] array = File.ReadAllLines(storePath, Encoding.UTF8);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length == 0 || text.StartsWith("#"))
				{
					continue;
				}
				string[] array2 = text.Split('\t');
				if (array2.Length >= 3)
				{
					SkinRecord skinRecord = new SkinRecord();
					int.TryParse(array2[0], out skinRecord.starIndex);
					int.TryParse(array2[1], out skinRecord.layerId);
					if (array2.Length >= 5 && array2[3] == "V")
					{
						skinRecord.isVideo = true;
						skinRecord.videoPath = array2[4];
					}
					else if (array2.Length >= 5 && array2[3] == "F")
					{
						skinRecord.isFrames = true;
						skinRecord.framesPath = array2[4];
					}
					else
					{
						skinRecord.imagePath = array2[2];
					}
					if (skinRecord.layerId < 1 || skinRecord.layerId > 10)
					{
						skinRecord.layerId = 1;
					}
					_records.Add(skinRecord);
				}
			}
			ManualLogSource log = DysonShellSkinPlugin.Log;
			if (log != null)
			{
				log.LogInfo((object)$"外观存储已加载:{_records.Count} 条 ({storePath})");
			}
		}
		catch (Exception ex)
		{
			ManualLogSource log2 = DysonShellSkinPlugin.Log;
			if (log2 != null)
			{
				log2.LogWarning((object)("外观存储加载失败: " + ex.Message));
			}
		}
	}

	public static SkinRecord TryGet(int starIndex, int layerId)
	{
		EnsureLoaded();
		foreach (SkinRecord record in _records)
		{
			if (record.starIndex == starIndex && record.layerId == layerId)
			{
				return record;
			}
		}
		return null;
	}

	public static SkinRecord GetOrCreate(int starIndex, int layerId)
	{
		EnsureLoaded();
		SkinRecord skinRecord = TryGet(starIndex, layerId);
		if (skinRecord != null)
		{
			return skinRecord;
		}
		skinRecord = new SkinRecord
		{
			starIndex = starIndex,
			layerId = layerId
		};
		_records.Add(skinRecord);
		return skinRecord;
	}

	public static bool Remove(int starIndex, int layerId)
	{
		EnsureLoaded();
		SkinRecord skinRecord = TryGet(starIndex, layerId);
		if (skinRecord == null)
		{
			return false;
		}
		_records.Remove(skinRecord);
		return true;
	}

	public static IEnumerable<SkinRecord> ForStar(int starIndex)
	{
		EnsureLoaded();
		for (int i = _records.Count - 1; i >= 0; i--)
		{
			if (_records[i].starIndex == starIndex)
			{
				yield return _records[i];
			}
		}
	}

	public static bool HasAny(int starIndex)
	{
		EnsureLoaded();
		for (int i = 0; i < _records.Count; i++)
		{
			if (_records[i].starIndex == starIndex)
			{
				if (_records[i].isVideo && !string.IsNullOrEmpty(_records[i].videoPath))
				{
					return true;
				}
				if (!_records[i].isVideo && !string.IsNullOrEmpty(_records[i].imagePath))
				{
					return true;
				}
			}
		}
		return false;
	}

	public static void Save()
	{
		try
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("#DysonShellSkin v3");
			foreach (SkinRecord record in _records)
			{
				string text;
				string text2;
				if (record.isVideo)
				{
					text = "V";
					text2 = record.videoPath ?? "";
				}
				else if (record.isFrames)
				{
					text = "F";
					text2 = record.framesPath ?? "";
				}
				else
				{
					text = "I";
					text2 = record.imagePath ?? "";
				}
				stringBuilder.AppendLine(string.Join("\t", record.starIndex.ToString(), record.layerId.ToString(), "", text, text2));
			}
			File.WriteAllText(StorePath, stringBuilder.ToString(), Encoding.UTF8);
		}
		catch (Exception ex)
		{
			ManualLogSource log = DysonShellSkinPlugin.Log;
			if (log != null)
			{
				log.LogWarning((object)("外观存储保存失败: " + ex.Message));
			}
		}
	}
}