Decompiled source of Multiplayer Expansion Rossi v1.0.0

BepInEx/plugins/WKPmxAvatar/WKPmxAvatar.dll

Decompiled 35 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using WKPmxAvatar.RuntimePhysics;
using WKPmxAvatar.SecondaryMotion;

[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("CllIEBE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 CllIEBE")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("联机扩展-洛茜模组")]
[assembly: AssemblyTitle("WKPmxAvatar")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
public static class EyeFaceUvTransfer
{
	private sealed class Prepared
	{
		public bool valid;

		public Stats stats;
	}

	[Serializable]
	public class Stats
	{
		public string scope;

		public int vertices;

		public int inside;

		public int nearestFallback;

		public float maxDistance;

		public float meanDistance;
	}

	private static readonly ConditionalWeakTable<Mesh, Prepared> prepared = new ConditionalWeakTable<Mesh, Prepared>();

	public static int ProjectionRuns { get; private set; }

	public static bool TryGetStatistics(Mesh mesh, out Stats stats)
	{
		stats = null;
		if ((Object)(object)mesh == (Object)null || !prepared.TryGetValue(mesh, out var value) || !value.valid)
		{
			return false;
		}
		stats = value.stats;
		return stats != null;
	}

	public static bool EnsurePrepared(Mesh mesh, int iris, int sclera)
	{
		//IL_0071: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: 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_0085: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)mesh == (Object)null || iris < 0 || sclera < 0)
		{
			return false;
		}
		if (EyeFaceUvTransfer.prepared.TryGetValue(mesh, out var value))
		{
			return value.valid;
		}
		Prepared prepared = new Prepared();
		EyeFaceUvTransfer.prepared.Add(mesh, prepared);
		try
		{
			if ((mesh.vertexCount & 1) != 0 || mesh.uv2.Length != 0)
			{
				throw new InvalidDataException("Unsupported PMX mesh layout or occupied UV1");
			}
			int num = mesh.vertexCount / 2;
			Vector3[] vertices = mesh.vertices;
			for (int i = 0; i < num; i++)
			{
				Vector3 val = vertices[i] - vertices[i + num];
				if (((Vector3)(ref val)).sqrMagnitude > 1E-12f)
				{
					throw new InvalidDataException("PMX backface duplication differs");
				}
			}
			Apply(mesh, iris, sclera, num);
			prepared.valid = true;
		}
		catch (Exception)
		{
			Debug.LogWarning((object)"Rossi eye-face linkage unavailable for this mesh [R020].");
		}
		return prepared.valid;
	}

	public static Stats Apply(Mesh mesh, int iris, int sclera, int originalCount)
	{
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Unknown result type (might be due to invalid IL or missing references)
		//IL_0262: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0270: Unknown result type (might be due to invalid IL or missing references)
		//IL_0103: Unknown result type (might be due to invalid IL or missing references)
		//IL_0105: 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_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: 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_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0149: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Unknown result type (might be due to invalid IL or missing references)
		//IL_0156: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: 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_016f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0180: Unknown result type (might be due to invalid IL or missing references)
		//IL_0182: Unknown result type (might be due to invalid IL or missing references)
		//IL_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_0191: Unknown result type (might be due to invalid IL or missing references)
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_027e: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_0206: Unknown result type (might be due to invalid IL or missing references)
		//IL_020d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0212: Unknown result type (might be due to invalid IL or missing references)
		//IL_021a: 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_0226: Unknown result type (might be due to invalid IL or missing references)
		//IL_022b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0230: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
		Vector3[] vertices = mesh.vertices;
		Vector2[] uv = mesh.uv;
		Vector2[] array = (Vector2[])uv.Clone();
		int[] triangles = mesh.GetTriangles(sclera);
		int[] triangles2 = mesh.GetTriangles(iris);
		bool[] array2 = new bool[originalCount];
		Stats stats = new Stats
		{
			scope = "Diagnostic XY surface projection onto actual PMX sclera triangles. UV0 unchanged. This is a facial-context approximation, not original-game UV recovery."
		};
		int[] array3 = triangles2;
		for (int i = 0; i < array3.Length; i++)
		{
			int num = array3[i] % originalCount;
			if (array2[num])
			{
				continue;
			}
			array2[num] = true;
			Vector3 val = vertices[num];
			float num2 = float.MaxValue;
			Vector2 val2 = Vector2.zero;
			bool flag = false;
			float num3 = 0f;
			Vector2 val5;
			for (int j = 0; j < triangles.Length; j += 3)
			{
				int num4 = triangles[j];
				int num5 = triangles[j + 1];
				int num6 = triangles[j + 2];
				if (num4 < originalCount && num5 < originalCount && num6 < originalCount && Mathf.Sign((vertices[num4].x + vertices[num5].x + vertices[num6].x) / 3f) == Mathf.Sign(val.x))
				{
					bool inside;
					Vector3 val3 = Nearest(Vector2.op_Implicit(val), Vector2.op_Implicit(vertices[num4]), Vector2.op_Implicit(vertices[num5]), Vector2.op_Implicit(vertices[num6]), out inside);
					Vector3 val4 = vertices[num4] * val3.x + vertices[num5] * val3.y + vertices[num6] * val3.z;
					val5 = new Vector2(val4.x - val.x, val4.y - val.y);
					float sqrMagnitude = ((Vector2)(ref val5)).sqrMagnitude;
					float num7 = (float)((!inside) ? 1 : 0) + sqrMagnitude * 10000f + Mathf.Abs(val4.z - val.z) * 0.001f;
					if (!(num7 >= num2))
					{
						num2 = num7;
						flag = inside;
						val2 = uv[num4] * val3.x + uv[num5] * val3.y + uv[num6] * val3.z;
						num3 = Mathf.Sqrt(sqrMagnitude);
					}
				}
			}
			if (num2 == float.MaxValue || val2.x < 0f || val2.x > 1f || val2.y < 0f || val2.y > 1f)
			{
				throw new InvalidDataException("No bounded face UV projection for iris vertex");
			}
			if (num3 > 0.012f)
			{
				throw new InvalidDataException("Iris/sclera projection exceeds diagnostic 12mm limit");
			}
			val5 = (array[num] = (array[num + originalCount] = val2));
			stats.vertices++;
			if (flag)
			{
				stats.inside++;
			}
			else
			{
				stats.nearestFallback++;
			}
			stats.maxDistance = Mathf.Max(stats.maxDistance, num3);
			stats.meanDistance += num3;
		}
		stats.meanDistance /= Mathf.Max(1, stats.vertices);
		mesh.uv2 = array;
		ProjectionRuns++;
		if (!prepared.TryGetValue(mesh, out var value))
		{
			value = new Prepared();
			prepared.Add(mesh, value);
		}
		value.valid = true;
		value.stats = stats;
		return stats;
		static Vector3 Nearest(Vector2 p, Vector2 a, Vector2 b, Vector2 c, out bool reference)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: 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_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: 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_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: 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_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: 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_0142: 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_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01be: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			float num8 = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);
			if (Mathf.Abs(num8) > 1E-12f)
			{
				float num9 = ((b.y - c.y) * (p.x - c.x) + (c.x - b.x) * (p.y - c.y)) / num8;
				float num10 = ((c.y - a.y) * (p.x - c.x) + (a.x - c.x) * (p.y - c.y)) / num8;
				float num11 = 1f - num9 - num10;
				reference = num9 >= -1E-05f && num10 >= -1E-05f && num11 >= -1E-05f;
				if (reference)
				{
					return new Vector3(num9, num10, num11);
				}
			}
			reference = false;
			float num12 = float.MaxValue;
			Vector3 result = Vector3.right;
			for (int k = 0; k < 3; k++)
			{
				Vector2 val6 = (Vector2)(k switch
				{
					1 => b, 
					0 => a, 
					_ => c, 
				});
				Vector2 val7 = (Vector2)(k switch
				{
					1 => c, 
					0 => b, 
					_ => a, 
				}) - val6;
				float num13 = Mathf.Clamp01(Vector2.Dot(p - val6, val7) / Mathf.Max(1E-12f, ((Vector2)(ref val7)).sqrMagnitude));
				Vector2 val8 = val6 + val7 * num13 - p;
				float sqrMagnitude2 = ((Vector2)(ref val8)).sqrMagnitude;
				if (!(sqrMagnitude2 >= num12))
				{
					num12 = sqrMagnitude2;
					result = (Vector3)(k switch
					{
						1 => new Vector3(0f, 1f - num13, num13), 
						0 => new Vector3(1f - num13, num13, 0f), 
						_ => new Vector3(num13, 0f, 1f - num13), 
					});
				}
			}
			return result;
		}
	}
}
public static class EyeShadowFeather
{
	private sealed class State
	{
		public bool valid;

		public Stats stats;
	}

	private struct Edge
	{
		public int a;

		public int b;

		public int opposite;

		public int count;
	}

	[Serializable]
	public sealed class Stats
	{
		public int vertices;

		public int boundaryEdges;

		public int lowerEdges;

		public float maximumDistance;
	}

	private static readonly ConditionalWeakTable<Mesh, State> cache = new ConditionalWeakTable<Mesh, State>();

	public static int PreparationRuns { get; private set; }

	public static bool TryGetStatistics(Mesh mesh, out Stats stats)
	{
		stats = null;
		if ((Object)(object)mesh == (Object)null || !cache.TryGetValue(mesh, out var value) || !value.valid)
		{
			return false;
		}
		stats = value.stats;
		return true;
	}

	public static bool EnsurePrepared(Mesh mesh, int materialIndex)
	{
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0201: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0214: Unknown result type (might be due to invalid IL or missing references)
		//IL_0219: Unknown result type (might be due to invalid IL or missing references)
		//IL_021b: Unknown result type (might be due to invalid IL or missing references)
		//IL_021d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0222: 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_022b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0232: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		//IL_0249: Unknown result type (might be due to invalid IL or missing references)
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_026c: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fc: Unknown result type (might be due to invalid IL or missing references)
		//IL_0301: Unknown result type (might be due to invalid IL or missing references)
		//IL_0306: 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_0334: Unknown result type (might be due to invalid IL or missing references)
		//IL_0339: Unknown result type (might be due to invalid IL or missing references)
		//IL_0344: Unknown result type (might be due to invalid IL or missing references)
		//IL_0349: Unknown result type (might be due to invalid IL or missing references)
		//IL_034e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0350: Unknown result type (might be due to invalid IL or missing references)
		//IL_0355: Unknown result type (might be due to invalid IL or missing references)
		//IL_0357: Unknown result type (might be due to invalid IL or missing references)
		//IL_0359: Unknown result type (might be due to invalid IL or missing references)
		//IL_035b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0360: Unknown result type (might be due to invalid IL or missing references)
		//IL_0382: Unknown result type (might be due to invalid IL or missing references)
		//IL_0384: Unknown result type (might be due to invalid IL or missing references)
		//IL_0386: Unknown result type (might be due to invalid IL or missing references)
		//IL_038a: 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_0481: Unknown result type (might be due to invalid IL or missing references)
		//IL_0486: Unknown result type (might be due to invalid IL or missing references)
		//IL_0487: Unknown result type (might be due to invalid IL or missing references)
		//IL_0489: Unknown result type (might be due to invalid IL or missing references)
		//IL_048e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0490: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f9: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)mesh == (Object)null || materialIndex < 0 || materialIndex >= mesh.subMeshCount)
		{
			return false;
		}
		if (cache.TryGetValue(mesh, out var value))
		{
			return value.valid;
		}
		State state = new State();
		cache.Add(mesh, state);
		try
		{
			if ((mesh.vertexCount & 1) != 0 || mesh.uv3.Length != 0)
			{
				throw new InvalidOperationException("Unsupported mesh layout or occupied UV2");
			}
			int num = mesh.vertexCount / 2;
			Vector3[] vertices = mesh.vertices;
			for (int i = 0; i < num; i++)
			{
				Vector3 val = vertices[i] - vertices[i + num];
				if (((Vector3)(ref val)).sqrMagnitude > 1E-12f)
				{
					throw new InvalidOperationException("Backface duplication differs");
				}
			}
			Dictionary<ulong, Edge> edges = new Dictionary<ulong, Edge>();
			HashSet<int> hashSet = new HashSet<int>();
			int[] triangles = mesh.GetTriangles(materialIndex);
			for (int j = 0; j < triangles.Length; j += 3)
			{
				int num2 = triangles[j];
				int num3 = triangles[j + 1];
				int num4 = triangles[j + 2];
				if (num2 < num && num3 < num && num4 < num)
				{
					hashSet.Add(num2);
					hashSet.Add(num3);
					hashSet.Add(num4);
					Add(num2, num3, num4);
					Add(num3, num4, num2);
					Add(num4, num2, num3);
				}
			}
			if (hashSet.Count < 6 || hashSet.Count > 256)
			{
				throw new InvalidOperationException("Unsupported overlay topology");
			}
			List<Edge> list = new List<Edge>();
			Stats stats = new Stats
			{
				vertices = hashSet.Count
			};
			foreach (Edge value3 in edges.Values)
			{
				if (value3.count > 2)
				{
					throw new InvalidOperationException("Non-manifold overlay");
				}
				if (value3.count == 1)
				{
					stats.boundaryEdges++;
					Vector2 val2 = Vector2.op_Implicit(vertices[value3.a]);
					Vector2 val3 = Vector2.op_Implicit(vertices[value3.b]);
					Vector2 val4 = Vector2.op_Implicit(vertices[value3.opposite]);
					Vector2 val5 = val3 - val2;
					float num5 = val5.x * (val4.y - val2.y) - val5.y * (val4.x - val2.x);
					if (!(Mathf.Abs(num5) < 1E-12f) && ((num5 > 0f) ? (0f - val5.x) : val5.x) < -0.2f * ((Vector2)(ref val5)).magnitude)
					{
						list.Add(value3);
					}
				}
			}
			stats.lowerEdges = list.Count;
			if (list.Count < 4)
			{
				throw new InvalidOperationException("No continuous lower overlay boundary");
			}
			Vector2[] array = (Vector2[])(object)new Vector2[mesh.vertexCount];
			foreach (int item in hashSet)
			{
				Vector2 val6 = Vector2.op_Implicit(vertices[item]);
				float num6 = float.MaxValue;
				foreach (Edge item2 in list)
				{
					Vector2 val7 = Vector2.op_Implicit(vertices[item2.a]);
					Vector2 val8 = Vector2.op_Implicit(vertices[item2.b]) - val7;
					float num7 = Mathf.Clamp01(Vector2.Dot(val6 - val7, val8) / Mathf.Max(1E-12f, ((Vector2)(ref val8)).sqrMagnitude));
					num6 = Mathf.Min(num6, Vector2.Distance(val6, val7 + val8 * num7));
				}
				if (float.IsNaN(num6) || float.IsInfinity(num6))
				{
					throw new InvalidOperationException("Non-finite boundary distance");
				}
				array[item] = (array[item + num] = new Vector2(num6, 0f));
				stats.maximumDistance = Mathf.Max(stats.maximumDistance, num6);
			}
			if (stats.maximumDistance < 1E-06f)
			{
				throw new InvalidOperationException("Overlay has no interior depth");
			}
			foreach (int item3 in hashSet)
			{
				array[item3] = (array[item3 + num] = new Vector2(array[item3].x / stats.maximumDistance, 0f));
			}
			mesh.uv3 = array;
			state.stats = stats;
			state.valid = true;
			PreparationRuns++;
			void Add(int a, int b, int opposite)
			{
				ulong key = ((ulong)(uint)Math.Min(a, b) << 32) | (uint)Math.Max(a, b);
				if (edges.TryGetValue(key, out var value2))
				{
					value2.count++;
					edges[key] = value2;
				}
				else
				{
					edges.Add(key, new Edge
					{
						a = a,
						b = b,
						opposite = opposite,
						count = 1
					});
				}
			}
		}
		catch (Exception)
		{
			Debug.LogWarning((object)"Rossi eye-shadow adaptation unavailable for this mesh [R021].");
		}
		return state.valid;
	}
}
[DefaultExecutionOrder(10000)]
public sealed class FaceFrameBinding : MonoBehaviour
{
	public Renderer Target;

	public Transform Head;

	public int MaterialIndex;

	public int[] AdditionalMaterialIndices;

	public Vector3 LocalForward = Vector3.back;

	public Vector3 LocalUp = Vector3.up;

	private MaterialPropertyBlock block;

	private static readonly int EnabledId = Shader.PropertyToID("_HeadFrameEnabled");

	private static readonly int RightId = Shader.PropertyToID("_HeadRight");

	private static readonly int UpId = Shader.PropertyToID("_HeadUp");

	private static readonly int ForwardId = Shader.PropertyToID("_HeadForward");

	public bool Refresh()
	{
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003d: 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_004a: 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)
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_007b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: 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_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_00cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: 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_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c8: Expected O, but got Unknown
		//IL_0105: Unknown result type (might be due to invalid IL or missing references)
		//IL_0106: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)Target == (Object)null || (Object)(object)Head == (Object)null || MaterialIndex < 0)
		{
			return false;
		}
		Vector3 val = Head.rotation * LocalForward;
		Vector3 val2 = Head.rotation * LocalUp;
		if (((Vector3)(ref val)).sqrMagnitude < 1E-08f || ((Vector3)(ref val2)).sqrMagnitude < 1E-08f)
		{
			return false;
		}
		((Vector3)(ref val)).Normalize();
		val2 -= val * Vector3.Dot(val2, val);
		if (((Vector3)(ref val2)).sqrMagnitude < 1E-08f)
		{
			return false;
		}
		((Vector3)(ref val2)).Normalize();
		Vector3 val3 = Vector3.Cross(val, val2);
		Vector3 normalized = ((Vector3)(ref val3)).normalized;
		if (block == null)
		{
			block = new MaterialPropertyBlock();
		}
		Write(MaterialIndex, normalized, val2, val);
		if (AdditionalMaterialIndices != null)
		{
			int[] additionalMaterialIndices = AdditionalMaterialIndices;
			foreach (int num in additionalMaterialIndices)
			{
				if (num >= 0 && num != MaterialIndex)
				{
					Write(num, normalized, val2, val);
				}
			}
		}
		return true;
	}

	private void Write(int index, Vector3 right, Vector3 up, Vector3 forward)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0033: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: 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_004b: Unknown result type (might be due to invalid IL or missing references)
		Target.GetPropertyBlock(block, index);
		block.SetVector(RightId, Vector4.op_Implicit(right));
		block.SetVector(UpId, Vector4.op_Implicit(up));
		block.SetVector(ForwardId, Vector4.op_Implicit(forward));
		block.SetFloat(EnabledId, 1f);
		Target.SetPropertyBlock(block, index);
	}

	private void LateUpdate()
	{
		Refresh();
	}

	public void Clear()
	{
		if ((Object)(object)Target == (Object)null || block == null || MaterialIndex < 0)
		{
			return;
		}
		Target.GetPropertyBlock(block, MaterialIndex);
		block.SetFloat(EnabledId, 0f);
		Target.SetPropertyBlock(block, MaterialIndex);
		if (AdditionalMaterialIndices == null)
		{
			return;
		}
		int[] additionalMaterialIndices = AdditionalMaterialIndices;
		foreach (int num in additionalMaterialIndices)
		{
			if (num >= 0 && num != MaterialIndex)
			{
				Target.GetPropertyBlock(block, num);
				block.SetFloat(EnabledId, 0f);
				Target.SetPropertyBlock(block, num);
			}
		}
	}

	private void OnDisable()
	{
		Clear();
	}
}
namespace WKPmxAvatar
{
	internal sealed class RuntimeSecondaryMotion
	{
		private static Profile shared;

		private readonly Transform root;

		private readonly Transform[] bones;

		private readonly Vector3[] positions;

		private readonly Quaternion[] rotations;

		private readonly Quaternion[] saved;

		private readonly Action<string> warn;

		private readonly float pmxScale;

		private SecondaryRig solver;

		private readonly SkirtPose skirt;

		private readonly int[] legs;

		private float worldScale;

		private bool reset = true;

		private bool failed;

		private bool clearanceFailed;

		private int lastFrame = -1;

		private static Vector3 Vec(Vector3 v)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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)
			return new Vector3(v.x, v.y, v.z);
		}

		private static Quaternion Quat(Quaternion q)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Quaternion(q.x, q.y, q.z, q.w);
		}

		private static Quaternion Unity(Quaternion q)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			return new Quaternion(q.X, q.Y, q.Z, q.W);
		}

		private static Profile Load()
		{
			if (shared != null)
			{
				return shared;
			}
			using Stream stream = typeof(RuntimeSecondaryMotion).Assembly.GetManifestResourceStream("WKPmxAvatar.PhysicsProfile.json");
			using StreamReader streamReader = new StreamReader(stream ?? throw new InvalidDataException("Missing physics profile"));
			return shared = JsonConvert.DeserializeObject<Profile>(streamReader.ReadToEnd());
		}

		internal static RuntimeSecondaryMotion TryCreate(Transform root, Transform[] bones, Action<string> warn)
		{
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				Profile profile = Load();
				if (bones.Length != profile.Names.Length)
				{
					return null;
				}
				for (int i = 0; i < bones.Length; i++)
				{
					if ((Object)(object)bones[i] == (Object)null || ((Object)bones[i]).name != profile.Names[i] || (Object)(object)bones[i].parent != (Object)(object)((profile.Parents[i] < 0) ? root : bones[profile.Parents[i]]))
					{
						return null;
					}
				}
				float num = Vector3.Distance(SecondaryRig.Vec(profile.Rest[18]), SecondaryRig.Vec(profile.Rest[14]));
				float num2 = Vector3.Distance(root.InverseTransformPoint(bones[18].position), root.InverseTransformPoint(bones[14].position)) / num;
				if (!float.IsFinite(num2) || num2 <= 0f)
				{
					return null;
				}
				for (int j = 0; j < bones.Length; j++)
				{
					if (profile.Parents[j] >= 0)
					{
						Vector3 value = (SecondaryRig.Vec(profile.Rest[j]) - SecondaryRig.Vec(profile.Rest[profile.Parents[j]])) * num2;
						if (Vector3.Distance(Vec(bones[j].localPosition), value) > 0.002f * num2 / 0.10575f)
						{
							return null;
						}
					}
				}
				return new RuntimeSecondaryMotion(root, bones, num2, warn);
			}
			catch (Exception ex)
			{
				warn("Secondary motion unavailable; animation retained: " + ex.Message);
				return null;
			}
		}

		private RuntimeSecondaryMotion(Transform root, Transform[] bones, float scale, Action<string> warn)
		{
			this.root = root;
			this.bones = bones;
			pmxScale = scale;
			this.warn = warn;
			positions = new Vector3[bones.Length];
			rotations = new Quaternion[bones.Length];
			saved = (Quaternion[])(object)new Quaternion[bones.Length];
			for (int i = 0; i < rotations.Length; i++)
			{
				rotations[i] = Quaternion.Identity;
			}
			skirt = new SkirtPose(Load(), scale);
			legs = new int[8]
			{
				Array.IndexOf(Load().Names, "左足"),
				Array.IndexOf(Load().Names, "左ひざ"),
				Array.IndexOf(Load().Names, "左足首"),
				Array.IndexOf(Load().Names, "右足"),
				Array.IndexOf(Load().Names, "右ひざ"),
				Array.IndexOf(Load().Names, "右足首"),
				Array.IndexOf(Load().Names, "左つま先"),
				Array.IndexOf(Load().Names, "右つま先")
			};
		}

		private void ApplyClearance()
		{
			//IL_00e1: 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)
			Transform anchor = bones[14];
			skirt.Evaluate(Leg(0), Leg(1), Leg(2), Leg(3), Leg(4), Leg(5), Boot(2, 0.1f, 0.25f), Boot(2, 0.1f, -0.95f), Boot(5, -0.1f, 0.25f), Boot(5, -0.1f, -0.95f));
			for (int i = 0; i < skirt.Bones.Length; i++)
			{
				Vector3 vector = skirt.LocalPositions[i];
				bones[skirt.Bones[i]].localPosition = new Vector3(vector.X, vector.Y, vector.Z);
				bones[skirt.Bones[i]].localRotation = Unity(skirt.Rotations[i]);
			}
			Vector3 Boot(int leg, float x, float z)
			{
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0037: 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)
				return Vec(anchor.InverseTransformPoint(bones[legs[leg]].TransformPoint(new Vector3(x * pmxScale, -0.55f * pmxScale, z * pmxScale))));
			}
			Vector3 Leg(int num)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				return Vec(anchor.InverseTransformPoint(bones[legs[num]].position));
			}
		}

		internal void RequestReset()
		{
			reset = true;
		}

		internal void Tick(float dt, bool enabled, bool clearance = true)
		{
			//IL_02bb: 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_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: 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_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0245: 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_0261: Unknown result type (might be due to invalid IL or missing references)
			if (dt <= 0f)
			{
				reset = true;
				solver?.Invalidate();
				return;
			}
			if (clearance && !clearanceFailed)
			{
				try
				{
					ApplyClearance();
				}
				catch (Exception ex)
				{
					clearanceFailed = true;
					warn("Skirt clearance disabled for this avatar; animation retained: " + ex.Message);
				}
			}
			if (failed)
			{
				return;
			}
			if (!enabled)
			{
				reset = true;
				solver?.Invalidate();
				return;
			}
			int frameCount = Time.frameCount;
			if (lastFrame >= 0 && frameCount - lastFrame > 1)
			{
				reset = true;
			}
			lastFrame = frameCount;
			bool flag = false;
			try
			{
				Vector3 lossyScale = root.lossyScale;
				if (lossyScale.x <= 0f || Mathf.Abs(lossyScale.x - lossyScale.y) > 0.001f || Mathf.Abs(lossyScale.x - lossyScale.z) > 0.001f)
				{
					throw new InvalidOperationException("Secondary motion requires a uniform positive avatar scale");
				}
				if (solver == null || Mathf.Abs(lossyScale.x - worldScale) > 0.0001f)
				{
					worldScale = lossyScale.x;
					solver = new SecondaryRig(Load(), pmxScale * worldScale);
					reset = true;
				}
				int[] required = solver.Required;
				foreach (int num in required)
				{
					positions[num] = Vec(bones[num].localPosition);
					saved[num] = bones[num].localRotation;
					rotations[num] = Quat(saved[num]);
				}
				flag = true;
				solver.Tick(dt, positions, rotations, Vec(root.position), Quat(root.rotation), worldScale, reset);
				reset = false;
				required = solver.Owned;
				foreach (int num2 in required)
				{
					bones[num2].localRotation = saved[num2] * Unity(solver.Delta[num2]);
				}
			}
			catch (Exception ex2)
			{
				if (flag)
				{
					int[] required = solver.Owned;
					foreach (int num3 in required)
					{
						if ((Object)(object)bones[num3] != (Object)null)
						{
							bones[num3].localRotation = saved[num3];
						}
					}
				}
				failed = true;
				warn("Secondary motion disabled for this avatar; animation retained: " + ex2.Message);
			}
		}
	}
	public sealed class AvatarSelectionSync : MonoBehaviour
	{
		internal Plugin Owner;

		private Type network;

		private Type uiManager;

		private object previousNetwork;

		private ulong previousLobby;

		private string published;

		private float next;

		private float nextPublish;

		private static WeakReference<GameObject> mountedScreen;

		private float nextUiRecovery;

		public static void AfterDictionary(ref Dictionary<string, string> __result)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance != (Object)null && __result != null && ModelCatalog.ValidId(instance.PersonalModelId))
			{
				__result["wkpmx.avatar.v1"] = instance.PersonalModelId;
			}
		}

		public static void AfterReceive(object __instance, Dictionary<string, string> __0)
		{
			Plugin instance = Plugin.Instance;
			if (!((Object)(object)instance == (Object)null) && __0 != null)
			{
				__0.TryGetValue("wkpmx.avatar.v1", out var value);
				instance.ReceiveSelection(__instance, value);
			}
		}

		public void Invalidate()
		{
			published = null;
			next = 0f;
		}

		internal static object ExistingNetwork(Type t)
		{
			Type type = t;
			while (type != null)
			{
				FieldInfo field = type.GetField("_instance", BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field.GetValue(null);
				}
				type = type.BaseType;
			}
			return null;
		}

		private void Update()
		{
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)Owner == (Object)null || Time.unscaledTime < next)
			{
				return;
			}
			next = Time.unscaledTime + 1f;
			try
			{
				if (uiManager == null)
				{
					uiManager = (from a in AppDomain.CurrentDomain.GetAssemblies()
						select a.GetType("WKMPMod.UI.UI_Manager")).FirstOrDefault((Type t) => t != null);
				}
				if ((mountedScreen == null || !mountedScreen.TryGetTarget(out var target) || !((Object)(object)target != (Object)null)) && Time.unscaledTime >= nextUiRecovery)
				{
					nextUiRecovery = Time.unscaledTime + 5f;
					if (uiManager != null)
					{
						Object[] array = Resources.FindObjectsOfTypeAll(uiManager);
						foreach (Object val in array)
						{
							Component val2 = (Component)(object)((val is Component) ? val : null);
							if (val2 != null)
							{
								Scene scene = val2.gameObject.scene;
								if (((Scene)(ref scene)).IsValid())
								{
									AfterLobbyScreen(val);
								}
							}
						}
					}
				}
				if (network == null)
				{
					network = (from a in AppDomain.CurrentDomain.GetAssemblies()
						select a.GetType("WKMPMod.NetWork.MPSteamworks")).FirstOrDefault((Type t) => t != null);
				}
				object obj = ExistingNetwork(network);
				if (obj != null)
				{
					Object val3 = (Object)((obj is Object) ? obj : null);
					if (val3 == null || !(val3 == (Object)null))
					{
						object obj2 = network.GetProperty("IsInLobby")?.GetValue(obj);
						if (!(obj2 is bool) || !(bool)obj2)
						{
							Reset();
							return;
						}
						ulong num2 = Convert.ToUInt64(network.GetProperty("LobbyId").GetValue(obj));
						if (previousNetwork != obj || previousLobby != num2)
						{
							Owner.ClearSelections();
							published = null;
							previousNetwork = obj;
							previousLobby = num2;
						}
						MethodInfo method = network.GetMethod("GetMemberData", new Type[2]
						{
							typeof(ulong),
							typeof(string)
						});
						if (method == null)
						{
							return;
						}
						string personalModelId = Owner.PersonalModelId;
						if (ModelCatalog.ValidId(personalModelId) && (personalModelId != published || Time.unscaledTime >= nextPublish))
						{
							ulong num3 = Convert.ToUInt64(network.GetProperty("UserSteamId", BindingFlags.Static | BindingFlags.Public)?.GetValue(null) ?? ((object)0uL));
							if (((num3 == 0L) ? null : (method.Invoke(obj, new object[2] { num3, "wkpmx.avatar.v1" }) as string)) != personalModelId)
							{
								network.GetMethod("SetMemberData", new Type[2]
								{
									typeof(string),
									typeof(string)
								}).Invoke(obj, new object[2] { "wkpmx.avatar.v1", personalModelId });
							}
							published = personalModelId;
							nextPublish = Time.unscaledTime + 5f;
						}
						object[] remoteContainers = Owner.RemoteContainers;
						foreach (object obj3 in remoteContainers)
						{
							ulong num4 = Convert.ToUInt64(obj3.GetType().GetProperty("PlayerId").GetValue(obj3));
							string text = method.Invoke(obj, new object[2] { num4, "wkpmx.avatar.v1" }) as string;
							if (!string.IsNullOrEmpty(text))
							{
								Owner.ReceiveSelection(obj3, text);
							}
						}
						return;
					}
				}
				Reset();
			}
			catch (Exception ex)
			{
				Owner.SelectionWarning(ex.GetBaseException().Message);
				next = Time.unscaledTime + 5f;
			}
		}

		private void Reset()
		{
			if (previousNetwork != null || previousLobby != 0L)
			{
				Owner.ClearSelections();
			}
			previousNetwork = null;
			previousLobby = 0uL;
			published = null;
		}

		public static void AfterLobbyScreen(object __instance)
		{
			Plugin instance = Plugin.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			try
			{
				object? obj = AccessTools.Field(__instance.GetType(), "_mpScreen")?.GetValue(__instance);
				GameObject val = (GameObject)((obj is GameObject) ? obj : null);
				if ((Object)(object)val != (Object)null)
				{
					LobbyAvatarMenu.Mount(val, instance);
					mountedScreen = new WeakReference<GameObject>(val);
				}
			}
			catch (Exception ex)
			{
				instance.SelectionWarning(ex.Message);
			}
		}
	}
	internal sealed class BoundedWeakCache<T> where T : class
	{
		private readonly int capacity;

		private readonly Dictionary<string, WeakReference<T>> entries = new Dictionary<string, WeakReference<T>>(StringComparer.OrdinalIgnoreCase);

		private readonly List<string> dead = new List<string>();

		public int Hits { get; private set; }

		public int Loads { get; private set; }

		public int Keys => entries.Count;

		public BoundedWeakCache(int capacity)
		{
			if (capacity < 1)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			this.capacity = capacity;
		}

		public T Get(string key, Func<T> factory)
		{
			if (key == null || factory == null)
			{
				throw new ArgumentNullException();
			}
			if (entries.TryGetValue(key, out var value) && value.TryGetTarget(out var target))
			{
				Hits++;
				return target;
			}
			T val = factory() ?? throw new InvalidOperationException("Resource factory returned null");
			Loads++;
			if (entries.Count >= capacity)
			{
				dead.Clear();
				foreach (KeyValuePair<string, WeakReference<T>> entry in entries)
				{
					if (!entry.Value.TryGetTarget(out var _))
					{
						dead.Add(entry.Key);
					}
				}
				foreach (string item in dead)
				{
					entries.Remove(item);
				}
				dead.Clear();
			}
			if (entries.Count < capacity || entries.ContainsKey(key))
			{
				entries[key] = new WeakReference<T>(val);
			}
			return val;
		}
	}
	[DefaultExecutionOrder(10500)]
	public sealed class MotionPlayer : MonoBehaviour
	{
		private Transform[] bones;

		private float heightScale;

		private float groundFootY;

		private Transform leftFoot;

		private Transform rightFoot;

		private readonly Dictionary<int, MotionClip> cache = new Dictionary<int, MotionClip>();

		public float BaseFeetOffset;

		public float VisualLift { get; private set; }

		public float PreloadExternal(string folder, int index, Transform[] target)
		{
			if (!cache.TryGetValue(index, out var value))
			{
				value = MotionClip.Load(Path.Combine(folder, "clip-" + index + "-pmx.wkpmotion"), target);
				cache.Add(index, value);
			}
			return value.Duration;
		}

		public void Initialize(string folder, Transform[] target, float height)
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: 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_0141: Unknown result type (might be due to invalid IL or missing references)
			PreloadExternal(folder, 7, target);
			bones = target;
			heightScale = height / 2.1f;
			Vector3[] array = (Vector3[])(object)new Vector3[target.Length];
			Quaternion[] array2 = (Quaternion[])(object)new Quaternion[target.Length];
			for (int i = 0; i < target.Length; i++)
			{
				array[i] = target[i].localPosition;
				array2[i] = target[i].localRotation;
			}
			leftFoot = Array.Find(bones, (Transform b) => ((Object)b).name == "左足首");
			rightFoot = Array.Find(bones, (Transform b) => ((Object)b).name == "右足首");
			cache[7].Sample(bones, 0f, heightScale);
			groundFootY = FeetY();
			for (int num = 0; num < bones.Length; num++)
			{
				bones[num].localPosition = array[num];
				bones[num].localRotation = array2[num];
			}
			VisualLift = 0f;
			((Component)this).transform.localPosition = Vector3.up * BaseFeetOffset;
			((Behaviour)this).enabled = true;
		}

		private float FeetY()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)leftFoot != (Object)null) || !((Object)(object)rightFoot != (Object)null))
			{
				return 0f;
			}
			return Mathf.Min(((Component)this).transform.InverseTransformPoint(leftFoot.position).y, ((Component)this).transform.InverseTransformPoint(rightFoot.position).y);
		}

		public void SampleExternal(int index, float normalized, bool onGround)
		{
			//IL_006f: 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)
			if (bones == null || !cache.TryGetValue(index, out var value))
			{
				throw new InvalidOperationException("External motion not loaded");
			}
			value.Sample(bones, normalized, heightScale);
			VisualLift = (onGround ? Mathf.Clamp(groundFootY - FeetY(), 0f, 0.4f * heightScale) : 0f);
			((Component)this).transform.localPosition = Vector3.up * (BaseFeetOffset + VisualLift);
		}

		public void Stop()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			((Behaviour)this).enabled = false;
			VisualLift = 0f;
			((Component)this).transform.localPosition = Vector3.up * BaseFeetOffset;
		}
	}
	[DefaultExecutionOrder(12000)]
	public sealed class FirstPersonSkin : MonoBehaviour
	{
		private sealed class PoseRequest
		{
			public string Pose;

			public Sprite Source;
		}

		public static FirstPersonSkin Current;

		public Func<bool> HandsEnabled;

		public Func<bool> PawEnabled;

		public Func<float> HandScale;

		public Func<float> HandBrightness;

		public Action<string> Warn;

		public string Folder;

		private FirstPersonAssets assets;

		private HeldHandSkin heldSkin;

		private bool heldFailed;

		private Type playerType;

		private object player;

		private readonly HashSet<object> hands = new HashSet<object>();

		private readonly Dictionary<Sprite, bool> cursorMap = new Dictionary<Sprite, bool>();

		private readonly Dictionary<Image, Sprite> cursorOriginals = new Dictionary<Image, Sprite>();

		private readonly HashSet<SpriteRenderer> genericRenderers = new HashSet<SpriteRenderer>();

		private readonly HashSet<SpriteRenderer> seenGeneric = new HashSet<SpriteRenderer>();

		private readonly List<SpriteRenderer> staleGeneric = new List<SpriteRenderer>();

		private bool failed;

		private bool handsWereEnabled;

		private readonly Dictionary<object, PoseRequest> poseRequests = new Dictionary<object, PoseRequest>();

		private static readonly string[] HandRendererFields = new string[2] { "handSprite", "handForegroundSprite" };

		public string Status
		{
			get
			{
				if (!failed)
				{
					if (assets != null)
					{
						return "First person: 5 poses; " + (heldFailed ? "held resource error" : (heldSkin?.Status ?? "held not loaded"));
					}
					return "First person: not loaded";
				}
				return "First person: resource load failed; original visuals retained";
			}
		}

		private void Awake()
		{
			Current = this;
		}

		private bool Enabled(Func<bool> flag)
		{
			return flag?.Invoke() ?? false;
		}

		private bool Ensure()
		{
			if (assets != null)
			{
				return true;
			}
			if (failed || string.IsNullOrEmpty(Folder))
			{
				return false;
			}
			try
			{
				assets = new FirstPersonAssets(Folder);
				return true;
			}
			catch (Exception ex)
			{
				failed = true;
				Warn?.Invoke("First person skin unavailable: " + ex.Message);
				return false;
			}
		}

		private void Refresh()
		{
			if (playerType == null)
			{
				playerType = (from a in AppDomain.CurrentDomain.GetAssemblies()
					select a.GetType("ENT_Player")).FirstOrDefault((Type t) => t != null);
			}
			object obj = playerType?.GetField("playerObject", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null);
			Object val = (Object)((obj is Object) ? obj : null);
			if (val != null && val == (Object)null)
			{
				obj = null;
			}
			if (player == obj && hands.Count > 0 && cursorMap.Count > 0)
			{
				return;
			}
			if (player != obj)
			{
				poseRequests.Clear();
				handsWereEnabled = false;
			}
			player = obj;
			hands.Clear();
			cursorMap.Clear();
			if (player == null)
			{
				return;
			}
			if (playerType.GetField("hands")?.GetValue(player) is IEnumerable enumerable)
			{
				foreach (object item in enumerable)
				{
					if (item != null)
					{
						hands.Add(item);
					}
				}
			}
			if (!(playerType.GetField("uiSpriteDict")?.GetValue(player) is IDictionary dictionary))
			{
				return;
			}
			foreach (DictionaryEntry item2 in dictionary)
			{
				string text = item2.Key as string;
				if (!(text != "hand") || !(text != "hand-grabbed") || !(text != "hand-open") || !(text != "hand-grab") || !(text != "hand-grabbable"))
				{
					object? obj2 = item2.Value?.GetType().GetField("sprite")?.GetValue(item2.Value);
					Sprite val2 = (Sprite)((obj2 is Sprite) ? obj2 : null);
					if ((Object)(object)val2 != (Object)null)
					{
						cursorMap[val2] = text == "hand-grabbed" || text == "hand-grab";
					}
				}
			}
		}

		public Sprite ReplacePose(object hand, string pose, Sprite original)
		{
			if ((Object)(object)original == (Object)null)
			{
				return original;
			}
			if (!Enabled(HandsEnabled))
			{
				if (hand != null && poseRequests.TryGetValue(hand, out var value))
				{
					value.Pose = pose;
					value.Source = assets.Original(original);
				}
				return original;
			}
			if (!Ensure())
			{
				return original;
			}
			Refresh();
			if (!hands.Contains(hand))
			{
				return original;
			}
			return SelectPose(hand, pose, original);
		}

		private Sprite SelectPose(object hand, string pose, Sprite original)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			Type type = hand.GetType();
			int num = Convert.ToInt32(type.GetField("id")?.GetValue(hand) ?? ((object)1));
			object? obj = type.GetField("handSprite")?.GetValue(hand);
			SpriteRenderer val = (SpriteRenderer)((obj is SpriteRenderer) ? obj : null);
			bool flag = false;
			if ((Object)(object)val != (Object)null)
			{
				Transform val2 = ((Component)val).transform;
				while ((Object)(object)val2 != (Object)null)
				{
					if (val2.localScale.x < 0f)
					{
						flag = !flag;
					}
					val2 = val2.parent;
				}
			}
			bool mirrored = (num == 0) ^ ((Object)(object)val != (Object)null && val.flipX) ^ flag;
			Sprite val3 = assets.Replace(pose, original, mirrored, HandScale?.Invoke() ?? 0.85f);
			if (assets.IsHand(val3))
			{
				if (!poseRequests.TryGetValue(hand, out var value))
				{
					value = new PoseRequest();
					poseRequests.Add(hand, value);
				}
				value.Pose = pose;
				value.Source = assets.Original(original);
			}
			return val3;
		}

		private void ResumeGenericPoses()
		{
			foreach (object hand in hands)
			{
				Type type = hand.GetType();
				object? obj = type.GetField("handSprite")?.GetValue(hand);
				SpriteRenderer val = (SpriteRenderer)((obj is SpriteRenderer) ? obj : null);
				object? obj2 = type.GetField("handForegroundSprite")?.GetValue(hand);
				SpriteRenderer val2 = (SpriteRenderer)((obj2 is SpriteRenderer) ? obj2 : null);
				if ((Object)(object)val == (Object)null || ((Object)(object)val2 != (Object)null && (Object)(object)val2.sprite != (Object)null))
				{
					continue;
				}
				if (poseRequests.TryGetValue(hand, out var value) && (Object)(object)val.sprite == (Object)(object)value.Source && Array.IndexOf(FirstPersonAssets.Poses, value.Pose) >= 0)
				{
					val.sprite = SelectPose(hand, value.Pose, value.Source);
				}
				else
				{
					if (!(type.GetField("handPoses", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(hand) is IEnumerable enumerable))
					{
						continue;
					}
					foreach (object item in enumerable)
					{
						if (item != null)
						{
							Type type2 = item.GetType();
							string text = type2.GetField("id")?.GetValue(item) as string;
							object? obj3 = type2.GetField("sprite")?.GetValue(item);
							Sprite val3 = (Sprite)((obj3 is Sprite) ? obj3 : null);
							if ((Object)(object)val3 != (Object)null && (Object)(object)val3 == (Object)(object)val.sprite && Array.IndexOf(FirstPersonAssets.Poses, text) >= 0)
							{
								val.sprite = SelectPose(hand, text, val3);
								break;
							}
						}
					}
				}
			}
		}

		public Sprite ReplaceCursor(object hand, Sprite original)
		{
			if (!Enabled(PawEnabled) || (Object)(object)original == (Object)null || !Ensure())
			{
				return original;
			}
			Refresh();
			if (!hands.Contains(hand) || !cursorMap.TryGetValue(original, out var value))
			{
				return original;
			}
			object? obj = hand.GetType().GetField("uiInteract")?.GetValue(hand);
			Image val = (Image)((obj is Image) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				cursorOriginals[val] = original;
			}
			return assets.Paw(value);
		}

		private void LateUpdate()
		{
			Sync();
		}

		private void RestoreGeneric(SpriteRenderer r)
		{
			if ((Object)(object)r != (Object)null && assets != null && assets.IsHand(r.sprite))
			{
				r.sprite = assets.Original(r.sprite);
			}
		}

		public void Sync()
		{
			bool flag = Enabled(HandsEnabled);
			if (!flag)
			{
				RestoreHands();
			}
			else if (Ensure())
			{
				Refresh();
				if (!handsWereEnabled)
				{
					ResumeGenericPoses();
				}
				if (heldSkin == null && !heldFailed)
				{
					try
					{
						heldSkin = new HeldHandSkin(Path.Combine(Folder, "Held"));
					}
					catch (Exception ex)
					{
						heldFailed = true;
						Warn?.Invoke("Held hand skin unavailable: " + ex.Message);
					}
				}
				heldSkin?.Sync(hands, HandBrightness?.Invoke() ?? 0.7f);
				seenGeneric.Clear();
				foreach (object hand in hands)
				{
					string[] handRendererFields = HandRendererFields;
					foreach (string name in handRendererFields)
					{
						object? obj = hand.GetType().GetField(name)?.GetValue(hand);
						SpriteRenderer val = (SpriteRenderer)((obj is SpriteRenderer) ? obj : null);
						if (!((Object)(object)val == (Object)null) && assets.IsHand(val.sprite))
						{
							genericRenderers.Add(val);
							seenGeneric.Add(val);
						}
					}
				}
				staleGeneric.Clear();
				foreach (SpriteRenderer genericRenderer in genericRenderers)
				{
					if ((Object)(object)genericRenderer == (Object)null || !seenGeneric.Contains(genericRenderer))
					{
						staleGeneric.Add(genericRenderer);
					}
				}
				foreach (SpriteRenderer item in staleGeneric)
				{
					RestoreGeneric(item);
					genericRenderers.Remove(item);
				}
			}
			handsWereEnabled = flag;
			if (!Enabled(PawEnabled))
			{
				RestoreCursors();
			}
		}

		private void RestoreHands()
		{
			heldSkin?.Restore();
			if (assets == null)
			{
				return;
			}
			foreach (SpriteRenderer genericRenderer in genericRenderers)
			{
				RestoreGeneric(genericRenderer);
			}
			genericRenderers.Clear();
			foreach (object hand in hands)
			{
				string[] handRendererFields = HandRendererFields;
				foreach (string name in handRendererFields)
				{
					object? obj = hand.GetType().GetField(name)?.GetValue(hand);
					RestoreGeneric((SpriteRenderer)((obj is SpriteRenderer) ? obj : null));
				}
			}
		}

		private void RestoreCursors()
		{
			if (assets == null)
			{
				return;
			}
			foreach (KeyValuePair<Image, Sprite> cursorOriginal in cursorOriginals)
			{
				if ((Object)(object)cursorOriginal.Key != (Object)null && assets.IsPaw(cursorOriginal.Key.sprite))
				{
					cursorOriginal.Key.sprite = cursorOriginal.Value;
				}
			}
			cursorOriginals.Clear();
		}

		private void OnDestroy()
		{
			RestoreHands();
			RestoreCursors();
			poseRequests.Clear();
			heldSkin?.Dispose();
			assets?.Dispose();
			if ((Object)(object)Current == (Object)(object)this)
			{
				Current = null;
			}
		}
	}
	public sealed class HeldHandAssets : IDisposable
	{
		private readonly Dictionary<string, Texture2D> maps = new Dictionary<string, Texture2D>(StringComparer.Ordinal);

		private readonly Dictionary<string, Texture2D> contexts = new Dictionary<string, Texture2D>(StringComparer.Ordinal);

		private readonly Dictionary<string, Sprite> sprites = new Dictionary<string, Sprite>();

		private readonly Dictionary<Sprite, Sprite> originals = new Dictionary<Sprite, Sprite>();

		private readonly List<Object> owned = new List<Object>();

		public int Count => maps.Count + contexts.Count;

		public bool Ready => maps.Count > 0;

		private static string Key(string item, string source)
		{
			return item + "\n" + source;
		}

		private static bool Part(string s)
		{
			if (!string.IsNullOrEmpty(s) && s.Length <= 128)
			{
				return s.IndexOfAny(new char[3] { '\r', '\n', '\0' }) < 0;
			}
			return false;
		}

		public static bool IsHandSource(string s)
		{
			switch (s)
			{
			default:
				if (s.Length == 8 && s.StartsWith("HND_", StringComparison.Ordinal) && (s[4] == 'B' || s[4] == 'F') && s[5] >= '1' && s[5] <= '3' && s[6] >= 'A' && s[6] <= 'D' && s[7] >= '1')
				{
					return s[7] <= '4';
				}
				goto case null;
			case null:
				return false;
			case "H3A4":
			case "HotCocoaHands_":
			case "HotCocoafingers_1":
				return true;
			}
		}

		public static bool IsBackgroundSource(string s)
		{
			if (IsHandSource(s))
			{
				if (!(s == "H3A4") && !(s == "HotCocoaHands_"))
				{
					return s.StartsWith("HND_B", StringComparison.Ordinal);
				}
				return true;
			}
			return false;
		}

		private static string LocalFile(string folder, string file)
		{
			if (string.IsNullOrEmpty(file) || Path.GetFileName(file) != file || file.Contains("..") || file.IndexOfAny(new char[3] { '\r', '\n', '\0' }) >= 0)
			{
				throw new InvalidDataException("Invalid held asset filename");
			}
			return Path.Combine(folder, file);
		}

		private Texture2D Load(string folder, string file, string label)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			string text = LocalFile(folder, file);
			FileInfo fileInfo = new FileInfo(text);
			if (!fileInfo.Exists || fileInfo.Length > 16777216)
			{
				throw new InvalidDataException("Held image missing or too large");
			}
			Texture2D val = new Texture2D(2, 2, (TextureFormat)4, false);
			owned.Add((Object)(object)val);
			if (!ImageConversion.LoadImage(val, File.ReadAllBytes(text)) || ((Texture)val).width > 2048 || ((Texture)val).height > 2048)
			{
				throw new InvalidDataException("Invalid held PNG");
			}
			((Object)val).name = "RossiHeld/" + label;
			((Texture)val).wrapMode = (TextureWrapMode)1;
			((Texture)val).filterMode = (FilterMode)1;
			return val;
		}

		public HeldHandAssets(string folder)
		{
			try
			{
				string text = Path.Combine(folder, "manifest.json");
				if (!File.Exists(text))
				{
					return;
				}
				if (new FileInfo(text).Length > 65536)
				{
					throw new InvalidDataException("Held manifest too large");
				}
				JObject val = JObject.Parse(File.ReadAllText(text));
				if ((int?)val["schema"] != 1)
				{
					throw new InvalidDataException("Unsupported held manifest");
				}
				JToken obj = val["entries"];
				JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
				JToken obj2 = val["contextEntries"];
				JArray val3 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
				if (val2 == null || (val["contextEntries"] != null && val3 == null) || ((JContainer)val2).Count + ((val3 != null) ? ((JContainer)val3).Count : 0) > 128)
				{
					throw new InvalidDataException("Invalid held entries");
				}
				foreach (JToken item in val2)
				{
					string text2 = (string)item[(object)"item"];
					string text3 = (string)item[(object)"source"];
					if (!Part(text2) || !IsHandSource(text3))
					{
						throw new InvalidDataException("Invalid held mapping");
					}
					string key = Key(text2, text3);
					if (maps.ContainsKey(key))
					{
						throw new InvalidDataException("Duplicate held mapping");
					}
					maps.Add(key, Load(folder, (string)item[(object)"file"], text2 + "/" + text3));
				}
				if (val3 == null)
				{
					return;
				}
				foreach (JToken item2 in val3)
				{
					string text4 = (string)item2[(object)"item"];
					string text5 = (string)item2[(object)"background"];
					string text6 = (string)item2[(object)"source"];
					if (!Part(text4) || !IsBackgroundSource(text5) || !IsHandSource(text6) || IsBackgroundSource(text6))
					{
						throw new InvalidDataException("Invalid held context");
					}
					string key2 = Key(text4, text5) + "\n" + text6;
					if (contexts.ContainsKey(key2))
					{
						throw new InvalidDataException("Duplicate held context");
					}
					contexts.Add(key2, Load(folder, (string)item2[(object)"file"], text4 + "/" + text5 + "/" + text6));
				}
			}
			catch
			{
				Dispose();
				throw;
			}
		}

		public Sprite Original(Sprite s)
		{
			if (!((Object)(object)s != (Object)null) || !originals.TryGetValue(s, out var value))
			{
				return s;
			}
			return value;
		}

		public bool IsReplacement(Sprite s)
		{
			if ((Object)(object)s != (Object)null)
			{
				return originals.ContainsKey(s);
			}
			return false;
		}

		public Sprite Replace(string item, Sprite source, Sprite background = null)
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			source = Original(source);
			background = Original(background);
			if (!Ready || (Object)(object)source == (Object)null || item == null || !IsHandSource(((Object)source).name))
			{
				return source;
			}
			Texture2D value = null;
			if ((Object)(object)background != (Object)null)
			{
				string source2 = ((Object)background).name + "\n" + ((Object)source).name;
				if (!contexts.TryGetValue(Key(item, source2), out value))
				{
					contexts.TryGetValue(Key("*", source2), out value);
				}
			}
			if ((Object)(object)value == (Object)null && !maps.TryGetValue(Key(item, ((Object)source).name), out value) && !maps.TryGetValue(Key("*", ((Object)source).name), out value))
			{
				return source;
			}
			string key = ((Object)value).GetInstanceID() + "\n" + ((Object)source).GetInstanceID();
			if (sprites.TryGetValue(key, out var value2))
			{
				return value2;
			}
			if (sprites.Count >= 256)
			{
				return source;
			}
			Rect rect = source.rect;
			float num = (float)((Texture)value).width / ((Rect)(ref rect)).width;
			if (Mathf.Abs((float)((Texture)value).height / ((Rect)(ref rect)).height - num) > 0.001f)
			{
				return source;
			}
			Sprite val = Sprite.Create(value, new Rect(0f, 0f, (float)((Texture)value).width, (float)((Texture)value).height), new Vector2(source.pivot.x / ((Rect)(ref rect)).width, source.pivot.y / ((Rect)(ref rect)).height), source.pixelsPerUnit * num, 0u, (SpriteMeshType)0);
			((Object)val).name = "RossiHeld/" + item + "/" + ((Object)source).name;
			owned.Add((Object)(object)val);
			sprites.Add(key, val);
			originals.Add(val, source);
			return val;
		}

		public void Dispose()
		{
			for (int num = owned.Count - 1; num >= 0; num--)
			{
				if (owned[num] != (Object)null)
				{
					if (Application.isPlaying)
					{
						Object.Destroy(owned[num]);
					}
					else
					{
						Object.DestroyImmediate(owned[num]);
					}
				}
			}
			owned.Clear();
			maps.Clear();
			contexts.Clear();
			sprites.Clear();
			originals.Clear();
		}
	}
	public sealed class HeldHandSkin : IDisposable
	{
		private sealed class Binding
		{
			public SpriteRenderer Renderer;
		}

		private sealed class ControllerCache
		{
			public Component[] Controllers;

			public float RefreshAt;
		}

		private readonly HeldHandAssets assets;

		private readonly Dictionary<SpriteRenderer, Binding> bindings = new Dictionary<SpriteRenderer, Binding>();

		private readonly HashSet<SpriteRenderer> seen = new HashSet<SpriteRenderer>();

		private readonly List<SpriteRenderer> stale = new List<SpriteRenderer>();

		private readonly Dictionary<object, ControllerCache> controllerCache = new Dictionary<object, ControllerCache>();

		private readonly HashSet<object> currentItems = new HashSet<object>();

		private readonly List<object> expired = new List<object>();

		private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		public string Status
		{
			get
			{
				if (!assets.Ready)
				{
					return "held: original visuals (resources unavailable)";
				}
				return "held: " + assets.Count + " hand/context mappings";
			}
		}

		private static object Field(object instance, string name)
		{
			if (instance == null)
			{
				return null;
			}
			Type type = instance.GetType();
			while (type != null)
			{
				FieldInfo field = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field != null)
				{
					return field.GetValue(instance);
				}
				type = type.BaseType;
			}
			return null;
		}

		public HeldHandSkin(string folder)
		{
			assets = new HeldHandAssets(folder);
		}

		private IEnumerable Controllers(object item)
		{
			Component val = (Component)((item is Component) ? item : null);
			if (val == null)
			{
				return Field(item, "handSprites") as IEnumerable;
			}
			if (!controllerCache.TryGetValue(item, out var value) || Time.unscaledTime >= value.RefreshAt)
			{
				Type type = item.GetType().Assembly.GetType("Hand_SpriteController");
				if (type == null)
				{
					return Field(item, "handSprites") as IEnumerable;
				}
				value = new ControllerCache
				{
					Controllers = val.GetComponentsInChildren(type, true),
					RefreshAt = Time.unscaledTime + 1f
				};
				controllerCache[item] = value;
			}
			return value.Controllers;
		}

		private Sprite AncestorBackground(SpriteRenderer r, Component owner)
		{
			Transform parent = ((Component)r).transform.parent;
			while ((Object)(object)parent != (Object)null && (!((Object)(object)owner != (Object)null) || !((Object)(object)parent == (Object)(object)owner.transform.parent)))
			{
				SpriteRenderer component = ((Component)parent).GetComponent<SpriteRenderer>();
				Sprite val = (((Object)(object)component == (Object)null) ? null : assets.Original(component.sprite));
				if ((Object)(object)val != (Object)null && HeldHandAssets.IsBackgroundSource(((Object)val).name))
				{
					return val;
				}
				parent = parent.parent;
			}
			return null;
		}

		private void Apply(SpriteRenderer r, string item, Sprite background, float brightness)
		{
			if ((Object)(object)r == (Object)null)
			{
				return;
			}
			Sprite val = assets.Original(r.sprite);
			Sprite val2 = assets.Replace(item, val, background);
			if (!((Object)(object)val2 == (Object)(object)val))
			{
				seen.Add(r);
				if (!bindings.ContainsKey(r))
				{
					bindings.Add(r, new Binding
					{
						Renderer = r
					});
				}
				r.sprite = val2;
			}
		}

		public void Sync(IEnumerable hands, float brightness)
		{
			seen.Clear();
			currentItems.Clear();
			if (!float.IsFinite(brightness))
			{
				brightness = 0.7f;
			}
			brightness = Mathf.Clamp(brightness, 0.35f, 1f);
			foreach (object hand in hands)
			{
				if (hand == null)
				{
					continue;
				}
				object obj = hand.GetType().GetMethod("GetHandItem", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null)?.Invoke(hand, null);
				Object val = (Object)((obj is Object) ? obj : null);
				if (val != null && val == (Object)null)
				{
					obj = null;
				}
				string text = Field(Field(obj, "item"), "prefabName") as string;
				if (obj != null)
				{
					currentItems.Add(obj);
					if (text != null)
					{
						IEnumerable enumerable = Controllers(obj);
						if (enumerable != null)
						{
							foreach (object item in enumerable)
							{
								object obj2 = Field(item, "sprite");
								SpriteRenderer val2 = (SpriteRenderer)((obj2 is SpriteRenderer) ? obj2 : null);
								if ((Object)(object)val2 == (Object)null)
								{
									Component val3 = (Component)((item is Component) ? item : null);
									if (val3 != null)
									{
										val2 = val3.GetComponent<SpriteRenderer>();
									}
								}
								if ((Object)(object)val2 != (Object)null)
								{
									Apply(val2, text, AncestorBackground(val2, (Component)((obj is Component) ? obj : null)), brightness);
								}
							}
						}
					}
				}
				object obj3 = Field(hand, "handSprite");
				SpriteRenderer val4 = (SpriteRenderer)((obj3 is SpriteRenderer) ? obj3 : null);
				object obj4 = Field(hand, "handForegroundSprite");
				SpriteRenderer r = (SpriteRenderer)((obj4 is SpriteRenderer) ? obj4 : null);
				Sprite background = (((Object)(object)val4 == (Object)null) ? null : assets.Original(val4.sprite));
				Apply(val4, text ?? "*", null, brightness);
				Apply(r, text ?? "*", background, brightness);
			}
			stale.Clear();
			foreach (KeyValuePair<SpriteRenderer, Binding> binding in bindings)
			{
				if ((Object)(object)binding.Key == (Object)null || !seen.Contains(binding.Key))
				{
					stale.Add(binding.Key);
				}
			}
			foreach (SpriteRenderer item2 in stale)
			{
				Restore(bindings[item2]);
				bindings.Remove(item2);
			}
			expired.Clear();
			foreach (object key in controllerCache.Keys)
			{
				if (!currentItems.Contains(key))
				{
					expired.Add(key);
				}
			}
			foreach (object item3 in expired)
			{
				controllerCache.Remove(item3);
			}
		}

		private void Restore(Binding b)
		{
			if ((Object)(object)b.Renderer != (Object)null && assets.IsReplacement(b.Renderer.sprite))
			{
				b.Renderer.sprite = assets.Original(b.Renderer.sprite);
			}
		}

		public void Restore()
		{
			foreach (Binding value in bindings.Values)
			{
				Restore(value);
			}
			bindings.Clear();
			controllerCache.Clear();
			currentItems.Clear();
		}

		public void Dispose()
		{
			Restore();
			assets.Dispose();
		}
	}
	internal sealed class AvatarAsset : IDisposable
	{
		private readonly List<Object> owned = new List<Object>();

		internal GameObject Template;

		internal readonly List<string> Warnings = new List<string>();

		private Material[] avatarMaterials;

		private Texture2D[] maps;

		private Color[] tints;

		private bool[] textureAlpha;

		internal static Vector3 Vec(PmxData.V3 v)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			return new Vector3(v.X, v.Y, v.Z);
		}

		internal static AvatarAsset Load(string path, float height)
		{
			AvatarAsset avatarAsset = new AvatarAsset();
			try
			{
				avatarAsset.Build(path, height);
				return avatarAsset;
			}
			catch
			{
				avatarAsset.Dispose();
				throw;
			}
		}

		private void Build(string path, float height)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_0218: 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: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_0256: Unknown result type (might be due to invalid IL or missing references)
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0266: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_0306: Unknown result type (might be due to invalid IL or missing references)
			//IL_030b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0318: Unknown result type (might be due to invalid IL or missing references)
			//IL_031d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0322: 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_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0341: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_0371: Unknown result type (might be due to invalid IL or missing references)
			//IL_0381: Unknown result type (might be due to invalid IL or missing references)
			//IL_0386: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_039e: 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_03af: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b8: Expected O, but got Unknown
			//IL_0543: Unknown result type (might be due to invalid IL or missing references)
			//IL_0548: Unknown result type (might be due to invalid IL or missing references)
			//IL_0557: Expected O, but got Unknown
			//IL_058f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0594: Unknown result type (might be due to invalid IL or missing references)
			//IL_07d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_07de: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_07ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_07f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_07fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0802: Unknown result type (might be due to invalid IL or missing references)
			//IL_0688: Unknown result type (might be due to invalid IL or missing references)
			//IL_068f: Expected O, but got Unknown
			//IL_06ed: Unknown result type (might be due to invalid IL or missing references)
			PmxData pmxData;
			using (FileStream stream = File.OpenRead(path))
			{
				pmxData = PmxReader.Read(stream);
			}
			Template = new GameObject("PMX_" + pmxData.Name);
			Template.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)Template);
			Transform[] array = (Transform[])(object)new Transform[pmxData.Bones.Length];
			float num = float.MaxValue;
			float num2 = float.MinValue;
			PmxData.Vertex[] vertices = pmxData.Vertices;
			foreach (PmxData.Vertex vertex in vertices)
			{
				num = Mathf.Min(num, vertex.Position.Y);
				num2 = Mathf.Max(num2, vertex.Position.Y);
			}
			if (num2 - num < 0.001f)
			{
				throw new InvalidDataException("PMX has no height");
			}
			float num3 = height / (num2 - num);
			for (int j = 0; j < array.Length; j++)
			{
				array[j] = new GameObject(pmxData.Bones[j].Name).transform;
				array[j].SetParent(Template.transform, false);
				array[j].localPosition = (Vec(pmxData.Bones[j].Position) - Vector3.up * num) * num3;
			}
			for (int k = 0; k < array.Length; k++)
			{
				if (pmxData.Bones[k].Parent >= 0)
				{
					array[k].SetParent(array[pmxData.Bones[k].Parent], true);
				}
			}
			bool flag = Array.Exists(pmxData.Materials, (PmxData.Material m) => (m.Flags & 1) != 0 && m.A > 0.001f);
			int num4 = pmxData.Vertices.Length;
			Vector3[] array2 = (Vector3[])(object)new Vector3[num4 * ((!flag) ? 1 : 2)];
			Vector3[] array3 = (Vector3[])(object)new Vector3[array2.Length];
			Vector2[] array4 = (Vector2[])(object)new Vector2[array2.Length];
			BoneWeight[] array5 = (BoneWeight[])(object)new BoneWeight[array2.Length];
			for (int num5 = 0; num5 < num4; num5++)
			{
				PmxData.Vertex vertex2 = pmxData.Vertices[num5];
				array2[num5] = (Vec(vertex2.Position) - Vector3.up * num) * num3;
				array3[num5] = Vec(vertex2.Normal);
				array4[num5] = new Vector2(vertex2.U, 1f - vertex2.V);
				int num6 = num5;
				BoneWeight val = default(BoneWeight);
				((BoneWeight)(ref val)).boneIndex0 = vertex2.Bones[0];
				((BoneWeight)(ref val)).boneIndex1 = vertex2.Bones[1];
				((BoneWeight)(ref val)).boneIndex2 = vertex2.Bones[2];
				((BoneWeight)(ref val)).boneIndex3 = vertex2.Bones[3];
				((BoneWeight)(ref val)).weight0 = vertex2.Weights[0];
				((BoneWeight)(ref val)).weight1 = vertex2.Weights[1];
				((BoneWeight)(ref val)).weight2 = vertex2.Weights[2];
				((BoneWeight)(ref val)).weight3 = vertex2.Weights[3];
				array5[num6] = val;
				if (flag)
				{
					int num7 = num5 + num4;
					array2[num7] = array2[num5];
					array3[num7] = -array3[num5];
					array4[num7] = array4[num5];
					array5[num7] = array5[num5];
				}
			}
			Matrix4x4[] array6 = (Matrix4x4[])(object)new Matrix4x4[array.Length];
			for (int num8 = 0; num8 < array6.Length; num8++)
			{
				array6[num8] = array[num8].worldToLocalMatrix * Template.transform.localToWorldMatrix;
			}
			Mesh val2 = new Mesh
			{
				name = pmxData.Name,
				indexFormat = (IndexFormat)1
			};
			owned.Add((Object)(object)val2);
			val2.vertices = array2;
			val2.normals = array3;
			val2.uv = array4;
			val2.boneWeights = array5;
			val2.bindposes = array6;
			val2.subMeshCount = pmxData.Materials.Length;
			int num9 = 0;
			for (int num10 = 0; num10 < pmxData.Materials.Length; num10++)
			{
				int indexCount = pmxData.Materials[num10].IndexCount;
				int[] array7 = new int[indexCount];
				Array.Copy(pmxData.Indices, num9, array7, 0, indexCount);
				val2.SetTriangles((pmxData.Materials[num10].A <= 0.001f) ? Array.Empty<int>() : MaterialPolicy.Faces(array7, (pmxData.Materials[num10].Flags & 1) != 0, num4), num10, false);
				num9 += indexCount;
			}
			val2.RecalculateBounds();
			val2.RecalculateTangents();
			Shader val3 = SelectShader(Plugin.Instance.UnlitTextures.Value);
			Dictionary<string, Texture2D> dictionary = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);
			Dictionary<string, bool> dictionary2 = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
			Material[] materials = (avatarMaterials = (Material[])(object)new Material[pmxData.Materials.Length]);
			maps = (Texture2D[])(object)new Texture2D[materials.Length];
			tints = (Color[])(object)new Color[materials.Length];
			textureAlpha = new bool[materials.Length];
			string text = Path.GetFullPath(Path.GetDirectoryName(path)) + Path.DirectorySeparatorChar;
			for (int num11 = 0; num11 < materials.Length; num11++)
			{
				PmxData.Material material = pmxData.Materials[num11];
				Material val4 = new Material(val3)
				{
					name = material.Name
				};
				owned.Add((Object)(object)val4);
				materials[num11] = val4;
				tints[num11] = new Color(material.R, material.G, material.B, material.A);
				if (material.Texture < 0)
				{
					continue;
				}
				string fullPath = Path.GetFullPath(Path.Combine(text, pmxData.Textures[material.Texture].Replace('\\', Path.DirectorySeparatorChar)));
				if (!fullPath.StartsWith(text, StringComparison.OrdinalIgnoreCase))
				{
					throw new InvalidDataException("Texture path escapes model folder: " + pmxData.Textures[material.Texture]);
				}
				if (!dictionary.TryGetValue(fullPath, out var value))
				{
					string text2 = Path.GetExtension(fullPath).ToLowerInvariant();
					if (!File.Exists(fullPath) || (text2 != ".png" && text2 != ".jpg" && text2 != ".jpeg"))
					{
						Warnings.Add("Missing/unsupported texture: " + fullPath);
						continue;
					}
					if (new FileInfo(fullPath).Length > 134217728)
					{
						throw new InvalidDataException("Texture file too large");
					}
					value = new Texture2D(2, 2, (TextureFormat)4, true);
					owned.Add((Object)(object)value);
					if (!ImageConversion.LoadImage(value, File.ReadAllBytes(fullPath), false))
					{
						throw new InvalidDataException("Cannot decode texture: " + fullPath);
					}
					((Object)value).name = Path.GetFileName(fullPath);
					dictionary[fullPath] = value;
					bool value2 = false;
					Color32[] pixels = value.GetPixels32();
					for (int i = 0; i < pixels.Length; i++)
					{
						if (MaterialPolicy.HasCoverageAlpha(pixels[i].a))
						{
							value2 = true;
							break;
						}
					}
					dictionary2[fullPath] = value2;
					value.Apply(true, true);
				}
				maps[num11] = value;
				textureAlpha[num11] = dictionary2[fullPath];
			}
			TailMaterialSplit.Apply(pmxData, val2, ref materials, ref maps, ref tints, ref textureAlpha, owned);
			avatarMaterials = materials;
			_ = 0;
			ApplyRendering(Plugin.Instance.UnlitTextures.Value);
			SkinnedMeshRenderer val5 = Template.AddComponent<SkinnedMeshRenderer>();
			val5.sharedMesh = val2;
			val5.bones = array;
			((Renderer)val5).sharedMaterials = materials;
			val5.rootBone = Template.transform;
			val5.quality = (SkinQuality)4;
			((Renderer)val5).localBounds = new Bounds(Vector3.up * height * 0.5f, Vector3.one * height * 3f);
			if (Array.Exists(pmxData.Textures, (string t) => t.IndexOf("T_actor_wulfa_cloth_01_D", StringComparison.OrdinalIgnoreCase) >= 0) && Array.Exists(pmxData.Textures, (string t) => t.IndexOf("T_actor_wulfa_body_01_D", StringComparison.OrdinalIgnoreCase) >= 0))
			{
				if (Plugin.Instance.RenderingResources.TryCreateMaterials(materials, maps, out var result, out var mapped, out var error))
				{
					int[] array8 = mapped;
					foreach (int num12 in array8)
					{
						owned.Add((Object)(object)result[num12]);
					}
					AvatarAppearanceBinding avatarAppearanceBinding = Template.AddComponent<AvatarAppearanceBinding>();
					avatarAppearanceBinding.Target = (Renderer)(object)val5;
					avatarAppearanceBinding.Baseline = materials;
					avatarAppearanceBinding.Experimental = result;
					avatarAppearanceBinding.MappedSlots = mapped;
					int num13 = Array.FindIndex(pmxData.Materials, (PmxData.Material m) => m.Name == "面");
					int num14 = Array.FindIndex(pmxData.Bones, (PmxData.Bone b) => b.Name == "頭");
					if (num13 >= 0 && num14 >= 0)
					{
						FaceFrameBinding faceFrameBinding = Template.AddComponent<FaceFrameBinding>();
						faceFrameBinding.Target = (Renderer)(object)val5;
						faceFrameBinding.Head = array[num14];
						faceFrameBinding.MaterialIndex = num13;
						((Behaviour)faceFrameBinding).enabled = false;
						avatarAppearanceBinding.Face = faceFrameBinding;
					}
				}
				else
				{
					Warnings.Add("Experimental materials unavailable; base textures retained: " + error);
				}
			}
			AvatarMotion avatarMotion = Template.AddComponent<AvatarMotion>();
			avatarMotion.Bones = array;
			avatarMotion.GrantSources = new int[array.Length];
			avatarMotion.GrantWeights = new float[array.Length];
			avatarMotion.GrantFlags = new int[array.Length];
			for (int num15 = 0; num15 < array.Length; num15++)
			{
				avatarMotion.GrantSources[num15] = pmxData.Bones[num15].InheritParent;
				avatarMotion.GrantWeights[num15] = pmxData.Bones[num15].InheritWeight;
				avatarMotion.GrantFlags[num15] = pmxData.Bones[num15].Flags;
			}
			if (pmxData.ApproximateWeights > 0)
			{
				Warnings.Add(pmxData.ApproximateWeights + " SDEF/QDEF vertices approximated using linear skinning");
			}
		}

		private static Shader SelectShader(bool unlit)
		{
			string[] array = ((!((Object)(object)GraphicsSettings.currentRenderPipeline != (Object)null)) ? new string[1] { "Standard" } : ((!unlit) ? new string[1] { "Universal Render Pipeline/Lit" } : new string[2] { "Universal Render Pipeline/Unlit", "Universal Render Pipeline/Lit" }));
			for (int i = 0; i < array.Length; i++)
			{
				Shader val = Shader.Find(array[i]);
				if ((Object)(object)val != (Object)null && val.isSupported)
				{
					return val;
				}
			}
			throw new InvalidOperationException("No supported depth-writing 3D avatar shader found for this render pipeline");
		}

		private static void SetFloat(Material mat, string property, float value)
		{
			if (mat.HasProperty(property))
			{
				mat.SetFloat(property, value);
			}
		}

		internal void ApplyRendering(bool unlit)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: 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_0095: 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_00e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0375: Unknown result type (might be due to invalid IL or missing references)
			//IL_037c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0383: 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_036e: Unknown result type (might be due to invalid IL or missing references)
			Shader val = SelectShader(unlit);
			for (int i = 0; i < avatarMaterials.Length; i++)
			{
				MaterialSurface materialSurface = MaterialPolicy.Classify(tints[i].a, textureAlpha[i]);
				bool flag = materialSurface == MaterialSurface.Transparent;
				bool flag2 = materialSurface == MaterialSurface.Cutout;
				Material val2 = avatarMaterials[i];
				val2.shader = val;
				val2.shaderKeywords = Array.Empty<string>();
				bool flag3 = unlit && (((Object)val).name == "Standard" || ((Object)val).name.EndsWith("/Lit"));
				Color val3 = tints[i];
				Color val4 = (Color)(flag3 ? new Color(0f, 0f, 0f, val3.a) : val3);
				string[] array = new string[2] { "_Color", "_BaseColor" };
				foreach (string text in array)
				{
					if (val2.HasProperty(text))
					{
						val2.SetColor(text, val4);
					}
				}
				array = new string[2] { "_MainTex", "_BaseMap" };
				foreach (string text2 in array)
				{
					if (val2.HasProperty(text2))
					{
						val2.SetTexture(text2, (Texture)(object)maps[i]);
					}
				}
				SetFloat(val2, "_Cull", 2f);
				SetFloat(val2, "_Metallic", 0f);
				SetFloat(val2, "_Smoothness", unlit ? 0f : 0.15f);
				SetFloat(val2, "_Glossiness", unlit ? 0f : 0.15f);
				SetFloat(val2, "_SpecularHighlights", (!unlit) ? 1 : 0);
				SetFloat(val2, "_GlossyReflections", (!unlit) ? 1 : 0);
				SetFloat(val2, "_EnvironmentReflections", (!unlit) ? 1 : 0);
				if (unlit)
				{
					val2.EnableKeyword("_SPECULARHIGHLIGHTS_OFF");
					val2.EnableKeyword("_GLOSSYREFLECTIONS_OFF");
					val2.EnableKeyword("_ENVIRONMENTREFLECTIONS_OFF");
				}
				SetFloat(val2, "_Cutoff", 0.15f);
				SetFloat(val2, "_AlphaClip", flag2 ? 1 : 0);
				SetFloat(val2, "_Mode", flag ? 2 : (flag2 ? 1 : 0));
				SetFloat(val2, "_Surface", flag ? 1 : 0);
				SetFloat(val2, "_Blend", 0f);
				SetFloat(val2, "_SrcBlend", (!flag) ? 1 : 5);
				SetFloat(val2, "_DstBlend", flag ? 10 : 0);
				SetFloat(val2, "_SrcBlendAlpha", 1f);
				SetFloat(val2, "_DstBlendAlpha", flag ? 10 : 0);
				SetFloat(val2, "_ZWrite", (!flag) ? 1 : 0);
				if (flag)
				{
					val2.EnableKeyword("_ALPHABLEND_ON");
					if (((Object)val).name.StartsWith("Universal"))
					{
						val2.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");
					}
				}
				if (flag2)
				{
					val2.EnableKeyword("_ALPHATEST_ON");
				}
				val2.SetOverrideTag("RenderType", flag ? "Transparent" : (flag2 ? "TransparentCutout" : "Opaque"));
				val2.renderQueue = (flag ? 3000 : (flag2 ? 2450 : 2000));
				val2.SetShaderPassEnabled("ShadowCaster", !flag && materialSurface != MaterialSurface.Hidden);
				if (val2.HasProperty("_EmissionColor"))
				{
					val2.SetColor("_EmissionColor", (Color)(flag3 ? new Color(val3.r, val3.g, val3.b, 1f) : Color.black));
				}
				if (val2.HasProperty("_EmissionMap"))
				{
					val2.SetTexture("_EmissionMap", (Texture)(object)maps[i]);
				}
				if (flag3)
				{
					val2.EnableKeyword("_EMISSION");
					val2.globalIlluminationFlags = (MaterialGlobalIlluminationFlags)0;
				}
			}
		}

		public void Dispose()
		{
			if ((Object)(object)Template != (Object)null)
			{
				Object.Destroy((Object)(object)Template);
			}
			foreach (Object item in owned)
			{
				if (item != (Object)null)
				{
					Object.Destroy(item);
				}
			}
			owned.Clear();
		}
	}
	public sealed class BodyGrabAlignment : IDisposable
	{
		private sealed class Saved
		{
			public CapsuleCollider Collider;

			public Vector3 Center;

			public float Height;

			public float Radius;

			public int Direction;
		}

		private readonly List<Saved> saved = new List<Saved>();

		private readonly Transform head;

		private readonly Transform leftFoot;

		private readonly Transform rightFoot;

		private readonly Transform leftArm;

		private readonly Transform rightArm;

		private readonly Transform hips;

		public int Count => saved.Count;

		public BodyGrabAlignment(Transform root, Transform[] bones)
		{
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			Transform[] bones2 = bones;
			base..ctor();
			head = Find("頭");
			leftFoot = Find("左足首");
			rightFoot = Find("右足首");
			leftArm = Find("左腕");
			rightArm = Find("右腕");
			hips = Find("腰");
			if ((Object)(object)head == (Object)null || (Object)(object)leftFoot == (Object)null || (Object)(object)rightFoot == (Object)null || (Object)(object)leftArm == (Object)null || (Object)(object)rightArm == (Object)null || (Object)(object)hips == (Object)null)
			{
				return;
			}
			CapsuleCollider[] componentsInChildren = ((Component)root).GetComponentsInChildren<CapsuleCollider>(true);
			foreach (CapsuleCollider val in componentsInChildren)
			{
				if (!((Collider)val).isTrigger)
				{
					continue;
				}
				bool flag = false;
				Component[] componentsInParent = ((Component)val).GetComponentsInParent<Component>(true);
				foreach (Component val2 in componentsInParent)
				{
					if ((Object)(object)val2 != (Object)null && (((object)val2).GetType().Name == "RemoteHand" || ((object)val2).GetType().Name == "AvatarMotion"))
					{
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					float height = val.height;
					Vector3 lossyScale = ((Component)val).transform.lossyScale;
					if (!(height * Mathf.Abs(((Vector3)(ref lossyScale))[val.direction]) < 0.6f))
					{
						saved.Add(new Saved
						{
							Collider = val,
							Center = val.center,
							Height = val.height,
							Radius = val.radius,
							Direction = val.direction
						});
					}
				}
			}
			Transform Find(string name)
			{
				return Array.Find(bones2, (Transform b) => ((Object)b).name == name);
			}
		}

		public void Apply(bool enabled)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//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)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: 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_00e6: 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_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Unknown result type (might be d