Decompiled source of Skysail v0.1.0

plugins/Skysail/Skysail.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using MagicaCloth2;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Skysail;

[HarmonyPatch]
internal static class CapeWind
{
	private class Orig
	{
		public float g;

		public float turb;

		public float freq;

		public float moving;

		public float3 dir;
	}

	private static readonly Dictionary<MagicaCloth, Orig> _orig = new Dictionary<MagicaCloth, Orig>();

	[HarmonyPostfix]
	[HarmonyPatch(typeof(PlayerClothWindShelter), "Update")]
	private static void After(Player ___m_player, MagicaCloth ___m_cloth)
	{
		//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: 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_0262: Unknown result type (might be due to invalid IL or missing references)
		//IL_026d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0272: Unknown result type (might be due to invalid IL or missing references)
		//IL_0283: Unknown result type (might be due to invalid IL or missing references)
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_028c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0291: Unknown result type (might be due to invalid IL or missing references)
		//IL_02aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02af: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)___m_player == (Object)null || (Object)(object)___m_cloth == (Object)null)
		{
			return;
		}
		GlideView component = ((Component)___m_player).GetComponent<GlideView>();
		float num = (((Object)(object)component != (Object)null) ? component.Weight : 0f);
		Orig value;
		bool flag = _orig.TryGetValue(___m_cloth, out value);
		ClothSerializeData serializeData = ___m_cloth.SerializeData;
		if (num <= 0f)
		{
			if (flag)
			{
				serializeData.gravity = value.g;
				serializeData.gravityDirection = value.dir;
				serializeData.wind.turbulence = value.turb;
				serializeData.wind.frequency = value.freq;
				serializeData.wind.movingWind = value.moving;
				___m_cloth.SetParameterChange();
				_orig.Remove(___m_cloth);
			}
			return;
		}
		if (!flag)
		{
			Orig orig = new Orig();
			orig.g = serializeData.gravity;
			orig.dir = serializeData.gravityDirection;
			orig.turb = serializeData.wind.turbulence;
			orig.freq = serializeData.wind.frequency;
			orig.moving = serializeData.wind.movingWind;
			value = orig;
			_orig[___m_cloth] = value;
			Plugin.Debug("[cape] cloth " + ((Object)___m_cloth).name + ": gravity " + value.g.ToString("0.##") + ", wind " + serializeData.wind.influence.ToString("0.##") + ", turbulence " + value.turb.ToString("0.##") + ", frequency " + value.freq.ToString("0.##") + ", moving wind " + value.moving.ToString("0.##") + ", damping " + serializeData.damping.value.ToString("0.###"));
		}
		Vector3 down = default(Vector3);
		((Vector3)(ref down))..ctor(value.dir.x, value.dir.y, value.dir.z);
		if (((Vector3)(ref down)).sqrMagnitude < 0.01f)
		{
			down = Vector3.down;
		}
		Vector3 val = Vector3.Slerp(((Vector3)(ref down)).normalized, -((Component)___m_player).transform.forward, Plugin.CapeStream.Value * num);
		Vector3 normalized = ((Vector3)(ref val)).normalized;
		serializeData.gravityDirection = new float3(normalized.x, normalized.y, normalized.z);
		serializeData.gravity = Mathf.Lerp(value.g, value.g * Plugin.CapeGravity.Value, num);
		serializeData.wind.influence = Mathf.Lerp(serializeData.wind.influence, Plugin.CapeFlutter.Value, num);
		serializeData.wind.turbulence = Mathf.Lerp(value.turb, Plugin.CapeTurbulence.Value, num);
		serializeData.wind.frequency = Mathf.Lerp(value.freq, Plugin.CapeFrequency.Value, num);
		serializeData.wind.movingWind = Mathf.Lerp(value.moving, Plugin.CapeMovingWind.Value, num);
		___m_cloth.SetParameterChange();
	}
}
[HarmonyPatch]
internal static class Exporter
{
	private static float _stillSince = -1f;

	private static bool _capesDone;

	private static float _air;

	private static float _fallFor;

	private static bool _fallSaved;

	private static readonly int FallingTag = Animator.StringToHash("falling");

	private static string _lastSnap;

	private static float _snapAt;

	[HarmonyPatch(typeof(Player), "Update")]
	[HarmonyPostfix]
	private static void Tick(Player __instance)
	{
		//IL_0099: 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)
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
		{
			return;
		}
		if (!_capesDone && (Object)(object)ObjectDB.instance != (Object)null)
		{
			_capesDone = true;
			try
			{
				Plugin.Log.LogInfo((object)("[export] cape textures saved to " + SaveCapes()));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("[export] capes: " + ex));
			}
		}
		FallTick(__instance);
		if (!Plugin.ExportPlayer.Value)
		{
			return;
		}
		Rigidbody component = ((Component)__instance).GetComponent<Rigidbody>();
		if (((Character)__instance).IsOnGround() && !((Character)__instance).IsAttached() && !((Character)__instance).InWater() && (Object)(object)component != (Object)null)
		{
			Vector3 linearVelocity = component.linearVelocity;
			if (((Vector3)(ref linearVelocity)).magnitude < 0.1f)
			{
				if (_stillSince < 0f)
				{
					_stillSince = Time.time;
				}
				else if (!(Time.time - _stillSince < 3f))
				{
					Plugin.ExportPlayer.Value = false;
					try
					{
						string text = Save(__instance);
						Plugin.Log.LogInfo((object)("[export] character saved to " + text));
						((Character)__instance).Message((MessageType)2, "Skysail: your character was saved for the sail editor", 0, (Sprite)null, false);
						return;
					}
					catch (Exception ex2)
					{
						Plugin.Log.LogWarning((object)("[export] " + ex2));
						return;
					}
				}
				return;
			}
		}
		_stillSince = -1f;
	}

	private static void FallTick(Player p)
	{
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0117: Unknown result type (might be due to invalid IL or missing references)
		if (!Plugin.ExportFall.Value)
		{
			return;
		}
		if (Flight.OpenTier > 0)
		{
			_fallSaved = true;
		}
		if (((Character)p).IsOnGround() || ((Character)p).InWater() || ((Character)p).IsAttached())
		{
			if (_air > 0.15f)
			{
				Plugin.Debug("[fall] " + _air.ToString("0.00") + " s in the air, " + _fallFor.ToString("0.00") + " s in the fall animation" + (_fallSaved ? "" : ", saving the pose from just before landing"));
				if (!_fallSaved && _lastSnap != null)
				{
					Write(p, _lastSnap, "just before landing");
				}
			}
			_air = 0f;
			_fallFor = 0f;
			_fallSaved = false;
			_lastSnap = null;
			return;
		}
		_air += Time.deltaTime;
		Animator componentInChildren = ((Component)p).GetComponentInChildren<Animator>();
		if ((Object)(object)componentInChildren != (Object)null)
		{
			AnimatorStateInfo currentAnimatorStateInfo = componentInChildren.GetCurrentAnimatorStateInfo(0);
			if (((AnimatorStateInfo)(ref currentAnimatorStateInfo)).tagHash == FallingTag)
			{
				_fallFor += Time.deltaTime;
			}
		}
		if (!_fallSaved)
		{
			if (_air >= 1f)
			{
				Write(p, SaveFall(p), "1 s into the fall");
				_fallSaved = true;
			}
			else if (_air >= 0.1f && Time.time >= _snapAt)
			{
				_lastSnap = SaveFall(p);
				_snapAt = Time.time + 0.1f;
			}
		}
	}

	private static void Write(Player p, string json, string when)
	{
		try
		{
			string text = Path.Combine(Paths.ConfigPath, "Skysail_editor");
			Directory.CreateDirectory(text);
			string text2 = Path.Combine(text, "fall.json");
			File.WriteAllText(text2, json);
			Plugin.Log.LogInfo((object)("[export] fall pose saved to " + text2 + " (" + when + ")"));
			((Character)p).Message((MessageType)2, "Skysail: fall pose saved for the editor", 0, (Sprite)null, false);
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[export] fall: " + ex));
		}
	}

	private static string SaveFall(Player p)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		Transform transform = ((Component)p).transform;
		Matrix4x4 worldToLocalMatrix = transform.worldToLocalMatrix;
		Quaternion val = Quaternion.Inverse(transform.rotation);
		List<Transform> list = new List<Transform>();
		HashSet<Transform> hashSet = new HashSet<Transform>();
		SkinnedMeshRenderer[] componentsInChildren = ((Component)p).GetComponentsInChildren<SkinnedMeshRenderer>(false);
		foreach (SkinnedMeshRenderer val2 in componentsInChildren)
		{
			if (val2.bones == null)
			{
				continue;
			}
			Transform[] bones = val2.bones;
			foreach (Transform val3 in bones)
			{
				Transform val4 = val3;
				while ((Object)(object)val4 != (Object)null && (Object)(object)val4 != (Object)(object)transform)
				{
					if (hashSet.Add(val4))
					{
						list.Add(val4);
					}
					val4 = val4.parent;
				}
			}
		}
		StringBuilder stringBuilder = new StringBuilder("{\"bones\":[");
		for (int k = 0; k < list.Count; k++)
		{
			Transform val5 = list[k];
			Vector3 val6 = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val5.position);
			Quaternion val7 = val * val5.rotation;
			if (k > 0)
			{
				stringBuilder.Append(",");
			}
			stringBuilder.Append("{\"n\":\"").Append(((Object)val5).name).Append("\",\"pos\":[")
				.Append(F(val6.x))
				.Append(",")
				.Append(F(val6.y))
				.Append(",")
				.Append(F(val6.z))
				.Append("],\"rot\":[")
				.Append(F(val7.x))
				.Append(",")
				.Append(F(val7.y))
				.Append(",")
				.Append(F(val7.z))
				.Append(",")
				.Append(F(val7.w))
				.Append("]}");
		}
		stringBuilder.Append("]}");
		return stringBuilder.ToString();
	}

	private static string F(float f)
	{
		return f.ToString("0.####", CultureInfo.InvariantCulture);
	}

	private static string Save(Player p)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_017b: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0228: Unknown result type (might be due to invalid IL or missing references)
		//IL_022d: 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_0234: Unknown result type (might be due to invalid IL or missing references)
		//IL_0237: Unknown result type (might be due to invalid IL or missing references)
		//IL_023c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0241: 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_024a: Unknown result type (might be due to invalid IL or missing references)
		Transform root = ((Component)p).transform;
		Matrix4x4 worldToLocalMatrix = root.worldToLocalMatrix;
		Quaternion val = Quaternion.Inverse(root.rotation);
		List<SkinnedMeshRenderer> list = new List<SkinnedMeshRenderer>();
		SkinnedMeshRenderer[] componentsInChildren = ((Component)p).GetComponentsInChildren<SkinnedMeshRenderer>(false);
		foreach (SkinnedMeshRenderer val2 in componentsInChildren)
		{
			if (((Renderer)val2).enabled && (Object)(object)val2.sharedMesh != (Object)null && val2.bones != null && val2.bones.Length > 0)
			{
				list.Add(val2);
			}
		}
		List<Transform> bones = new List<Transform>();
		Dictionary<Transform, int> index = new Dictionary<Transform, int>();
		Action<Transform> add = null;
		add = delegate(Transform t)
		{
			if (!((Object)(object)t == (Object)null) && !((Object)(object)t == (Object)(object)root) && !index.ContainsKey(t))
			{
				add(t.parent);
				index[t] = bones.Count;
				bones.Add(t);
			}
		};
		foreach (SkinnedMeshRenderer item in list)
		{
			Transform[] bones2 = item.bones;
			foreach (Transform obj in bones2)
			{
				add(obj);
			}
		}
		StringBuilder stringBuilder = new StringBuilder();
		Dictionary<Texture, string> texCache = new Dictionary<Texture, string>();
		for (int num2 = 0; num2 < list.Count; num2++)
		{
			if (num2 > 0)
			{
				stringBuilder.Append(",");
			}
			Part(stringBuilder, list[num2], worldToLocalMatrix, bones, index, texCache);
		}
		StringBuilder stringBuilder2 = new StringBuilder();
		AllCapes(p, stringBuilder2, worldToLocalMatrix, bones, index, add, texCache);
		StringBuilder stringBuilder3 = new StringBuilder();
		stringBuilder3.Append("{\"name\":\"").Append(p.GetPlayerName().Replace("\"", "")).Append("\",\"bones\":[");
		for (int num3 = 0; num3 < bones.Count; num3++)
		{
			Transform val3 = bones[num3];
			int value = (((Object)(object)val3.parent != (Object)null && index.ContainsKey(val3.parent)) ? index[val3.parent] : (-1));
			Vector3 val4 = ((Matrix4x4)(ref worldToLocalMatrix)).MultiplyPoint3x4(val3.position);
			Quaternion val5 = val * val3.rotation;
			Quaternion localRotation = val3.localRotation;
			if (num3 > 0)
			{
				stringBuilder3.Append(",");
			}
			stringBuilder3.Append("{\"n\":\"").Append(((Object)val3).name).Append("\",\"p\":")
				.Append(value)
				.Append(",\"pos\":[")
				.Append(F(val4.x))
				.Append(",")
				.Append(F(val4.y))
				.Append(",")
				.Append(F(val4.z))
				.Append("],\"rot\":[")
				.Append(F(val5.x))
				.Append(",")
				.Append(F(val5.y))
				.Append(",")
				.Append(F(val5.z))
				.Append(",")
				.Append(F(val5.w))
				.Append("],\"lr\":[")
				.Append(F(localRotation.x))
				.Append(",")
				.Append(F(localRotation.y))
				.Append(",")
				.Append(F(localRotation.z))
				.Append(",")
				.Append(F(localRotation.w))
				.Append("]}");
		}
		stringBuilder3.Append("],\"parts\":[").Append(stringBuilder.ToString()).Append("],\"capes\":[")
			.Append(stringBuilder2.ToString())
			.Append("]}");
		string text = Path.Combine(Paths.ConfigPath, "Skysail_editor");
		Directory.CreateDirectory(text);
		string text2 = Path.Combine(text, "player.json");
		File.WriteAllText(text2, stringBuilder3.ToString());
		return text2;
	}

	private static void Part(StringBuilder sb, SkinnedMeshRenderer sk, Matrix4x4 toRoot, List<Transform> bones, Dictionary<Transform, int> index, Dictionary<Texture, string> texCache)
	{
		//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		Part(sb, sk, toRoot, bones, index, texCache, sheet: false);
	}

	private static void Part(StringBuilder sb, SkinnedMeshRenderer sk, Matrix4x4 toRoot, List<Transform> bones, Dictionary<Transform, int> index, Dictionary<Texture, string> texCache, bool sheet)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_001f: 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_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_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_029f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a4: Unknown result type (might be due to invalid IL or missing references)
		Mesh val = new Mesh();
		sk.BakeMesh(val, true);
		Matrix4x4 mx = toRoot * ((Component)sk).transform.localToWorldMatrix;
		Vector3[] vertices = val.vertices;
		Vector2[] uv = val.uv;
		int[] triangles = val.triangles;
		int[] array = VertexBones(sk, vertices, mx, bones, index);
		sb.Append("{\"name\":\"").Append(((Object)sk).name).Append("\",");
		if (sheet)
		{
			sb.Append("\"cloth\":true,\"mesh\":\"").Append(((Object)sk.sharedMesh).name).Append("\",");
		}
		sb.Append("\"v\":[");
		for (int i = 0; i < vertices.Length; i++)
		{
			Vector3 val2 = ((Matrix4x4)(ref mx)).MultiplyPoint3x4(vertices[i]);
			if (i > 0)
			{
				sb.Append(",");
			}
			sb.Append(F(val2.x)).Append(",").Append(F(val2.y))
				.Append(",")
				.Append(F(val2.z));
		}
		sb.Append("],\"uv\":[");
		for (int j = 0; j < uv.Length; j++)
		{
			if (j > 0)
			{
				sb.Append(",");
			}
			sb.Append(F(uv[j].x)).Append(",").Append(F(uv[j].y));
		}
		sb.Append("],\"t\":[");
		for (int k = 0; k < triangles.Length; k++)
		{
			if (k > 0)
			{
				sb.Append(",");
			}
			sb.Append(triangles[k]);
		}
		sb.Append("],\"b\":[");
		for (int l = 0; l < array.Length; l++)
		{
			if (l > 0)
			{
				sb.Append(",");
			}
			sb.Append(array[l]);
		}
		sb.Append("]");
		Material sharedMaterial = ((Renderer)sk).sharedMaterial;
		Texture val3 = (((Object)(object)sharedMaterial != (Object)null && sharedMaterial.HasProperty("_MainTex")) ? sharedMaterial.mainTexture : null);
		if ((Object)(object)val3 != (Object)null)
		{
			if (!texCache.TryGetValue(val3, out var value))
			{
				value = (texCache[val3] = Png(val3, 512));
			}
			if (value != null)
			{
				sb.Append(",\"tex\":\"").Append(value).Append("\"");
			}
		}
		if ((Object)(object)sharedMaterial != (Object)null && sharedMaterial.HasProperty("_Color"))
		{
			Color color = sharedMaterial.color;
			sb.Append(",\"col\":[").Append(F(color.r)).Append(",")
				.Append(F(color.g))
				.Append(",")
				.Append(F(color.b))
				.Append("]");
		}
		sb.Append("}");
		Object.Destroy((Object)(object)val);
	}

	private static void AllCapes(Player p, StringBuilder sb, Matrix4x4 toRoot, List<Transform> bones, Dictionary<Transform, int> index, Action<Transform> add, Dictionary<Texture, string> texCache)
	{
		//IL_014a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Invalid comparison between Unknown and I4
		//IL_04fb: Unknown result type (might be due to invalid IL or missing references)
		VisEquipment component = ((Component)p).GetComponent<VisEquipment>();
		if ((Object)(object)component == (Object)null)
		{
			return;
		}
		MethodInfo methodInfo = AccessTools.Method(typeof(VisEquipment), "SetShoulderEquipped", (Type[])null, (Type[])null);
		FieldInfo fieldInfo = AccessTools.Field(typeof(VisEquipment), "m_shoulderItemInstances");
		FieldInfo fieldInfo2 = AccessTools.Field(typeof(VisEquipment), "m_currentShoulderItemHash");
		FieldInfo fieldInfo3 = AccessTools.Field(typeof(VisEquipment), "m_currentShoulderItemVariant");
		FieldInfo fieldInfo4 = AccessTools.Field(typeof(VisEquipment), "m_currentShoulderItemQuality");
		if (methodInfo == null || fieldInfo == null || fieldInfo2 == null)
		{
			Plugin.Log.LogWarning((object)"[export] capes: VisEquipment changed");
			return;
		}
		int num = (int)fieldInfo2.GetValue(component);
		int num2 = ((fieldInfo3 != null) ? ((int)fieldInfo3.GetValue(component)) : 0);
		int num3 = ((!(fieldInfo4 != null)) ? 1 : ((int)fieldInfo4.GetValue(component)));
		bool flag = true;
		int num4 = 0;
		HashSet<string> hashSet = new HashSet<string>();
		try
		{
			foreach (GameObject item2 in ObjectDB.instance.m_items)
			{
				ItemDrop val = (((Object)(object)item2 != (Object)null) ? item2.GetComponent<ItemDrop>() : null);
				if ((Object)(object)val == (Object)null || (int)val.m_itemData.m_shared.m_itemType != 17 || ((Object)item2).name.StartsWith("Skysail_"))
				{
					continue;
				}
				methodInfo.Invoke(component, new object[3]
				{
					StringExtensionMethods.GetStableHashCode(((Object)item2).name),
					0,
					1
				});
				if (!(fieldInfo.GetValue(component) is List<GameObject> list))
				{
					continue;
				}
				List<SkinnedMeshRenderer> list2 = new List<SkinnedMeshRenderer>();
				foreach (GameObject item3 in list)
				{
					if (!((Object)(object)item3 != (Object)null))
					{
						continue;
					}
					SkinnedMeshRenderer[] componentsInChildren = item3.GetComponentsInChildren<SkinnedMeshRenderer>(true);
					foreach (SkinnedMeshRenderer val2 in componentsInChildren)
					{
						if ((Object)(object)val2.sharedMesh != (Object)null && val2.bones != null && val2.bones.Length > 0)
						{
							list2.Add(val2);
						}
					}
				}
				SkinnedMeshRenderer val3 = null;
				foreach (SkinnedMeshRenderer item4 in list2)
				{
					if ((Object)(object)((Component)item4).GetComponent<Cloth>() != (Object)null)
					{
						val3 = item4;
						break;
					}
				}
				if ((Object)(object)val3 == (Object)null)
				{
					foreach (SkinnedMeshRenderer item5 in list2)
					{
						if ((Object)(object)val3 == (Object)null || item5.sharedMesh.vertexCount > val3.sharedMesh.vertexCount)
						{
							val3 = item5;
						}
					}
				}
				if ((Object)(object)val3 == (Object)null)
				{
					Plugin.Debug("[export] " + ((Object)item2).name + " has no skinned mesh, skipped");
					continue;
				}
				string item = ((Object)val3.sharedMesh).name + "|" + (((Object)(object)((Renderer)val3).sharedMaterial != (Object)null) ? ((Object)((Renderer)val3).sharedMaterial).name : "");
				if (hashSet.Contains(item))
				{
					Plugin.Debug("[export] " + ((Object)item2).name + " looks like a cape already saved, skipped");
					continue;
				}
				hashSet.Add(item);
				Plugin.Debug("[export] " + ((Object)item2).name + ": sheet " + ((Object)val3).name + " (" + val3.sharedMesh.vertexCount + " vertices" + (((Object)(object)((Component)val3).GetComponent<Cloth>() != (Object)null) ? ", cloth" : ", no cloth") + ")");
				foreach (SkinnedMeshRenderer item6 in list2)
				{
					Transform[] bones2 = item6.bones;
					foreach (Transform obj in bones2)
					{
						add(obj);
					}
				}
				if (!flag)
				{
					sb.Append(",");
				}
				flag = false;
				sb.Append("{\"item\":\"").Append(((Object)item2).name).Append("\",\"label\":\"")
					.Append(Localization.instance.Localize(val.m_itemData.m_shared.m_name).Replace("\"", ""))
					.Append("\",\"parts\":[");
				for (int k = 0; k < list2.Count; k++)
				{
					if (k > 0)
					{
						sb.Append(",");
					}
					Part(sb, list2[k], toRoot, bones, index, texCache, (Object)(object)list2[k] == (Object)(object)val3);
				}
				sb.Append("]}");
				num4++;
			}
		}
		finally
		{
			methodInfo.Invoke(component, new object[3] { 0, 0, 0 });
			methodInfo.Invoke(component, new object[3] { num, num2, num3 });
		}
		Plugin.Log.LogInfo((object)("[export] " + num4 + " capes saved for the capes editor"));
	}

	private static string SaveCapes()
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Invalid comparison between Unknown and I4
		StringBuilder stringBuilder = new StringBuilder("{");
		Dictionary<Texture, string> dictionary = new Dictionary<Texture, string>();
		bool flag = true;
		foreach (GameObject item in ObjectDB.instance.m_items)
		{
			ItemDrop val = (((Object)(object)item != (Object)null) ? item.GetComponent<ItemDrop>() : null);
			if ((Object)(object)val == (Object)null || (int)val.m_itemData.m_shared.m_itemType != 17 || ((Object)item).name.StartsWith("Skysail_"))
			{
				continue;
			}
			Material val2 = null;
			SkinnedMeshRenderer[] componentsInChildren = item.GetComponentsInChildren<SkinnedMeshRenderer>(true);
			foreach (SkinnedMeshRenderer val3 in componentsInChildren)
			{
				if ((Object)(object)((Renderer)val3).sharedMaterial != (Object)null && (Object)(object)((Renderer)val3).sharedMaterial.mainTexture != (Object)null)
				{
					val2 = ((Renderer)val3).sharedMaterial;
					break;
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				continue;
			}
			if (!dictionary.TryGetValue(val2.mainTexture, out var value))
			{
				value = (dictionary[val2.mainTexture] = Png(val2.mainTexture, 512));
			}
			if (value != null)
			{
				if (!flag)
				{
					stringBuilder.Append(",");
				}
				flag = false;
				stringBuilder.Append("\"").Append(((Object)item).name).Append("\":{\"name\":\"")
					.Append(Localization.instance.Localize(val.m_itemData.m_shared.m_name).Replace("\"", ""))
					.Append("\",\"tex\":\"")
					.Append(value)
					.Append("\"}");
			}
		}
		stringBuilder.Append("}");
		string text2 = Path.Combine(Paths.ConfigPath, "Skysail_editor");
		Directory.CreateDirectory(text2);
		string text3 = Path.Combine(text2, "capes.json");
		File.WriteAllText(text3, stringBuilder.ToString());
		return text3;
	}

	private static int[] VertexBones(SkinnedMeshRenderer sk, Vector3[] v, Matrix4x4 mx, List<Transform> bones, Dictionary<Transform, int> index)
	{
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: 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_0123: 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_0144: Unknown result type (might be due to invalid IL or missing references)
		int[] array = new int[v.Length];
		BoneWeight[] array2 = null;
		try
		{
			if (sk.sharedMesh.isReadable)
			{
				array2 = sk.sharedMesh.boneWeights;
			}
		}
		catch (Exception)
		{
		}
		Transform[] bones2 = sk.bones;
		if (array2 != null && array2.Length == v.Length)
		{
			for (int i = 0; i < v.Length; i++)
			{
				int boneIndex = ((BoneWeight)(ref array2[i])).boneIndex0;
				Transform val = ((boneIndex >= 0 && boneIndex < bones2.Length) ? bones2[boneIndex] : null);
				array[i] = (((Object)(object)val != (Object)null && index.ContainsKey(val)) ? index[val] : 0);
			}
			return array;
		}
		Matrix4x4 val2 = mx * ((Component)sk).transform.worldToLocalMatrix;
		List<Vector3> list = new List<Vector3>();
		List<int> list2 = new List<int>();
		Transform[] array3 = bones2;
		foreach (Transform val3 in array3)
		{
			if (!((Object)(object)val3 == (Object)null) && index.ContainsKey(val3))
			{
				list.Add(((Matrix4x4)(ref val2)).MultiplyPoint3x4(val3.position));
				list2.Add(index[val3]);
			}
		}
		for (int k = 0; k < v.Length; k++)
		{
			Vector3 val4 = ((Matrix4x4)(ref mx)).MultiplyPoint3x4(v[k]);
			float num = float.MaxValue;
			int num2 = 0;
			for (int l = 0; l < list.Count; l++)
			{
				Vector3 val5 = list[l] - val4;
				float sqrMagnitude = ((Vector3)(ref val5)).sqrMagnitude;
				if (sqrMagnitude < num)
				{
					num = sqrMagnitude;
					num2 = list2[l];
				}
			}
			array[k] = num2;
		}
		return array;
	}

	internal static string Png(Texture tex, int max)
	{
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0049: Expected O, but got Unknown
		//IL_0059: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			int num = tex.width;
			int num2 = tex.height;
			if (num > max)
			{
				num2 = Mathf.Max(1, num2 * max / num);
				num = max;
			}
			RenderTexture temporary = RenderTexture.GetTemporary(num, num2, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
			Graphics.Blit(tex, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(num, num2, (TextureFormat)4, false);
			val.ReadPixels(new Rect(0f, 0f, (float)num, (float)num2), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			string result = Convert.ToBase64String(ImageConversion.EncodeToPNG(val));
			Object.Destroy((Object)(object)val);
			return result;
		}
		catch (Exception ex)
		{
			Plugin.Debug("[export] texture " + ((Object)tex).name + ": " + ex.Message);
			return null;
		}
	}
}
[HarmonyPatch]
internal static class Flight
{
	internal const string ZdoKey = "Skysail_glide";

	private static readonly FieldInfo ShoulderF = AccessTools.Field(typeof(Humanoid), "m_shoulderItem");

	private static readonly FieldInfo AirF = AccessTools.Field(typeof(Character), "m_maxAirAltitude");

	private static readonly MethodInfo TakeInputM = AccessTools.Method(typeof(Player), "TakeInput", (Type[])null, (Type[])null);

	internal static int OpenTier;

	private static Vector3 _dir = Vector3.forward;

	private static Vector3 _vel;

	private static float _openedAt;

	private static int _ground;

	private static ItemData ShoulderItem(Player p)
	{
		if (!(ShoulderF != null))
		{
			return null;
		}
		object? value = ShoulderF.GetValue(p);
		return (ItemData)((value is ItemData) ? value : null);
	}

	private static void ResetFall(Player p)
	{
		//IL_0019: Unknown result type (might be due to invalid IL or missing references)
		if (AirF != null)
		{
			AirF.SetValue(p, ((Component)p).transform.position.y);
		}
	}

	internal static int Equipped(Player p)
	{
		if (!((Object)(object)p == (Object)null))
		{
			return Sails.TierOf(ShoulderItem(p));
		}
		return 0;
	}

	private static bool CanInput(Player p)
	{
		try
		{
			return TakeInputM == null || (bool)TakeInputM.Invoke(p, null);
		}
		catch (Exception)
		{
			return true;
		}
	}

	private static bool JumpDown()
	{
		if (!ZInput.GetButtonDown("Jump"))
		{
			return ZInput.GetButtonDown("JoyJump");
		}
		return true;
	}

	private static int GroundMask()
	{
		if (_ground == 0)
		{
			_ground = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" });
		}
		return _ground;
	}

	internal static float Height(Player p)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//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)
		//IL_001f: Unknown result type (might be due to invalid IL or missing references)
		RaycastHit val = default(RaycastHit);
		if (Physics.Raycast(((Component)p).transform.position + Vector3.up * 0.3f, Vector3.down, ref val, 100f, GroundMask(), (QueryTriggerInteraction)1))
		{
			return ((RaycastHit)(ref val)).distance - 0.3f;
		}
		return 100f;
	}

	[HarmonyPatch(typeof(Player), "Update")]
	[HarmonyPostfix]
	private static void PlayerUpdate(Player __instance)
	{
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
		{
			return;
		}
		int num = Equipped(__instance);
		try
		{
			if (OpenTier > 0)
			{
				string text = null;
				if (num == 0)
				{
					text = "sail taken off";
				}
				else if (((Character)__instance).IsDead())
				{
					text = "dead";
				}
				else if (((Character)__instance).IsOnGround() && Time.time - _openedAt > 0.3f)
				{
					text = "landed";
				}
				else if (Time.time - _openedAt > 0.3f && Height(__instance) <= Plugin.LandHeight.Value)
				{
					text = "landed";
				}
				else if (((Character)__instance).InWater())
				{
					text = "water";
				}
				else if (((Character)__instance).IsAttached())
				{
					text = "attached";
				}
				else if (__instance.GetStamina() <= 0f)
				{
					text = "out of stamina";
				}
				else if (JumpDown() && CanInput(__instance) && Time.time - _openedAt > 0.2f)
				{
					text = "closed";
				}
				if (text != null)
				{
					Close(__instance, text);
					return;
				}
				if (num != OpenTier)
				{
					OpenTier = num;
					SetZdo(__instance, num);
				}
				((Character)__instance).UseStamina(Sails.Tiers[OpenTier].Stamina * Time.deltaTime);
			}
			else
			{
				if (num <= 0 || !JumpDown() || !CanInput(__instance) || ((Character)__instance).IsOnGround() || ((Character)__instance).InWater() || ((Character)__instance).IsAttached() || ((Character)__instance).IsDead())
				{
					return;
				}
				float num2 = Height(__instance);
				if (num2 < Plugin.MinHeight.Value)
				{
					Plugin.Debug("[glide] too low to open: " + num2.ToString("0.0") + " m (MinHeight " + Plugin.MinHeight.Value + ")");
				}
				else if (__instance.GetStamina() < Plugin.MinStamina.Value)
				{
					if ((Object)(object)Hud.instance != (Object)null)
					{
						Hud.instance.StaminaBarEmptyFlash();
					}
					((Character)__instance).Message((MessageType)2, "Not enough stamina to open the sail", 0, (Sprite)null, false);
				}
				else
				{
					Open(__instance, num, num2);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Update: " + ex.Message));
		}
	}

	private static void Open(Player p, int tier, float h)
	{
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: 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_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0066: Unknown result type (might be due to invalid IL or missing references)
		OpenTier = tier;
		_openedAt = Time.time;
		Rigidbody component = ((Component)p).GetComponent<Rigidbody>();
		_vel = (((Object)(object)component != (Object)null) ? component.linearVelocity : Vector3.zero);
		Vector3 forward = ((Component)p).transform.forward;
		forward.y = 0f;
		_dir = ((((Vector3)(ref forward)).sqrMagnitude > 0.01f) ? ((Vector3)(ref forward)).normalized : Vector3.forward);
		SetZdo(p, tier);
		Plugin.Debug("[glide] open tier " + tier + " at " + h.ToString("0.0") + " m above ground");
	}

	internal static void Close(Player p, string why)
	{
		if (OpenTier != 0)
		{
			OpenTier = 0;
			if ((Object)(object)p != (Object)null)
			{
				ResetFall(p);
				SetZdo(p, 0);
			}
			GlideGuard.Closed(why);
			Plugin.Debug("[glide] close: " + why);
		}
	}

	private static void SetZdo(Player p, int tier)
	{
		ZNetView component = ((Component)p).GetComponent<ZNetView>();
		ZDO val = (((Object)(object)component != (Object)null) ? component.GetZDO() : null);
		if (val != null && component.IsOwner())
		{
			val.Set("Skysail_glide", tier);
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "FixedUpdate")]
	private static void PlayerFixedUpdate(Player __instance)
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Unknown result type (might be due to invalid IL or missing references)
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_0091: Unknown result type (might be due to invalid IL or missing references)
		//IL_0096: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: 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_0150: Unknown result type (might be due to invalid IL or missing references)
		//IL_0155: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_0168: 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_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_018c: Unknown result type (might be due to invalid IL or missing references)
		//IL_019d: 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)
		if (OpenTier == 0 || (Object)(object)__instance != (Object)(object)Player.m_localPlayer)
		{
			return;
		}
		Rigidbody component = ((Component)__instance).GetComponent<Rigidbody>();
		if ((Object)(object)component == (Object)null)
		{
			return;
		}
		Tier tier = Sails.Tiers[OpenTier];
		float fixedDeltaTime = Time.fixedDeltaTime;
		if ((Object)(object)GameCamera.instance != (Object)null)
		{
			Vector3 forward = ((Component)GameCamera.instance).transform.forward;
			forward.y = 0f;
			if (((Vector3)(ref forward)).sqrMagnitude > 0.01f)
			{
				Vector3 val = Vector3.RotateTowards(_dir, ((Vector3)(ref forward)).normalized, tier.Turn * ((float)Math.PI / 180f) * fixedDeltaTime, 0f);
				_dir = ((Vector3)(ref val)).normalized;
			}
		}
		float num = tier.Forward;
		float num2 = tier.Descent;
		bool flag = ZInput.GetButton("Forward") || ZInput.GetJoyLeftStickY() < -0.5f;
		bool flag2 = ZInput.GetButton("Backward") || ZInput.GetJoyLeftStickY() > 0.5f;
		if (!CanInput(__instance))
		{
			flag = (flag2 = false);
		}
		if (flag)
		{
			num *= 1.35f;
			num2 *= 1.8f;
		}
		else if (flag2)
		{
			num *= 0.5f;
			num2 *= 0.8f;
		}
		if (Height(__instance) < 2f)
		{
			num2 = Mathf.Max(num2, -1f);
		}
		Vector3 val2 = _dir * num + Vector3.up * num2;
		_vel = Vector3.Lerp(_vel, val2, 1f - Mathf.Exp(-2.5f * fixedDeltaTime));
		component.linearVelocity = _vel;
		ResetFall(__instance);
		component.MoveRotation(Quaternion.LookRotation(_dir, Vector3.up));
	}

	[HarmonyPatch(typeof(Player), "OnDestroy")]
	[HarmonyPrefix]
	private static void PlayerDestroy(Player __instance)
	{
		if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
		{
			OpenTier = 0;
		}
	}
}
[HarmonyPatch]
internal static class GlideGuard
{
	internal static bool SoftFall;

	private static float _groundSince = -1f;

	[HarmonyPatch(typeof(Player), "SetControls")]
	[HarmonyPrefix]
	private static void Controls(Player __instance, ref Vector3 movedir, ref bool crouch, ref bool run, ref bool autoRun, ref bool dodge)
	{
		//IL_0016: 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)
		if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Flight.OpenTier != 0)
		{
			movedir = Vector3.zero;
			crouch = (run = (autoRun = (dodge = false)));
		}
	}

	internal static void Closed(string why)
	{
		switch (why)
		{
		case "water":
			return;
		case "attached":
			return;
		case "dead":
			return;
		}
		SoftFall = true;
		_groundSince = -1f;
	}

	[HarmonyPatch(typeof(Character), "Damage")]
	[HarmonyPrefix]
	private static void Damage(Character __instance, HitData hit)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Invalid comparison between Unknown and I4
		if (SoftFall && hit != null && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && (int)hit.m_hitType == 3)
		{
			float damage = hit.m_damage.m_damage;
			ref DamageTypes damage2 = ref hit.m_damage;
			damage2.m_damage *= Plugin.SoftFallShare.Value;
			SoftFall = false;
			Plugin.Debug("[glide] fall after the sail: " + damage.ToString("0") + " -> " + hit.m_damage.m_damage.ToString("0") + " damage");
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "Update")]
	private static void Tick(Player __instance)
	{
		if (SoftFall && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && Flight.OpenTier <= 0)
		{
			if (!((Character)__instance).IsOnGround() && !((Character)__instance).InWater())
			{
				_groundSince = -1f;
			}
			else if (_groundSince < 0f)
			{
				_groundSince = Time.time;
			}
			else if (Time.time - _groundSince > 0.3f)
			{
				SoftFall = false;
				Plugin.Debug("[glide] landed, soft fall over");
			}
		}
	}
}
[HarmonyPatch]
internal static class GlideRecorder
{
	private static readonly FieldInfo CapeF = AccessTools.Field(typeof(VisEquipment), "m_shoulderItemInstances");

	private static float _glidingSince = -1f;

	private static bool _running;

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "Update")]
	private static void Tick(Player __instance)
	{
		if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && !_running && Plugin.RecordGlide.Value)
		{
			if (Flight.OpenTier == 0)
			{
				_glidingSince = -1f;
			}
			else if (_glidingSince < 0f)
			{
				_glidingSince = Time.time;
			}
			else if (!(Time.time - _glidingSince < 0.3f))
			{
				_running = true;
				((Character)__instance).Message((MessageType)1, "Skysail: recording the glide...", 0, (Sprite)null, false);
				((MonoBehaviour)__instance).StartCoroutine(Record(__instance));
			}
		}
	}

	private static void Skin(StringBuilder sb, SkinnedMeshRenderer sk, List<Transform> bones, Transform root)
	{
		//IL_0386: Unknown result type (might be due to invalid IL or missing references)
		//IL_0391: Unknown result type (might be due to invalid IL or missing references)
		//IL_0396: Unknown result type (might be due to invalid IL or missing references)
		//IL_039b: Unknown result type (might be due to invalid IL or missing references)
		Mesh val = (((Object)(object)sk != (Object)null) ? sk.sharedMesh : null);
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		if (!val.isReadable)
		{
			Plugin.Log.LogInfo((object)("[record] the cape mesh " + ((Object)val).name + " is not readable: no weights"));
			return;
		}
		Vector3[] vertices = val.vertices;
		BoneWeight[] boneWeights = val.boneWeights;
		Matrix4x4[] bindposes = val.bindposes;
		Transform[] bones2 = sk.bones;
		if (vertices.Length == 0 || boneWeights.Length != vertices.Length || bones2 == null || bindposes.Length != bones2.Length)
		{
			Plugin.Log.LogInfo((object)("[record] cape skin data missing (" + vertices.Length + " vertices, " + boneWeights.Length + " weights, " + bindposes.Length + " bind poses)"));
			return;
		}
		sb.Append(",\"mv\":[");
		for (int i = 0; i < vertices.Length; i++)
		{
			if (i > 0)
			{
				sb.Append(",");
			}
			sb.Append(F(vertices[i].x)).Append(",").Append(F(vertices[i].y))
				.Append(",")
				.Append(F(vertices[i].z));
		}
		sb.Append("],\"bw\":[");
		for (int j = 0; j < boneWeights.Length; j++)
		{
			if (j > 0)
			{
				sb.Append(",");
			}
			sb.Append(((BoneWeight)(ref boneWeights[j])).boneIndex0).Append(",").Append(((BoneWeight)(ref boneWeights[j])).boneIndex1)
				.Append(",")
				.Append(((BoneWeight)(ref boneWeights[j])).boneIndex2)
				.Append(",")
				.Append(((BoneWeight)(ref boneWeights[j])).boneIndex3)
				.Append(",")
				.Append(F(((BoneWeight)(ref boneWeights[j])).weight0))
				.Append(",")
				.Append(F(((BoneWeight)(ref boneWeights[j])).weight1))
				.Append(",")
				.Append(F(((BoneWeight)(ref boneWeights[j])).weight2))
				.Append(",")
				.Append(F(((BoneWeight)(ref boneWeights[j])).weight3));
		}
		sb.Append("],\"sb\":[");
		for (int k = 0; k < bones2.Length; k++)
		{
			if (k > 0)
			{
				sb.Append(",");
			}
			sb.Append(((Object)(object)bones2[k] != (Object)null) ? bones.IndexOf(bones2[k]) : (-1));
		}
		sb.Append("],\"bind\":[");
		for (int l = 0; l < bindposes.Length; l++)
		{
			if (l > 0)
			{
				sb.Append(",");
			}
			sb.Append("[");
			for (int m = 0; m < 16; m++)
			{
				if (m > 0)
				{
					sb.Append(",");
				}
				sb.Append(((Matrix4x4)(ref bindposes[l]))[m / 4, m % 4].ToString("0.######", CultureInfo.InvariantCulture));
			}
			sb.Append("]");
		}
		sb.Append("],\"smr\":[");
		Matrix4x4 val2 = root.worldToLocalMatrix * ((Component)sk).transform.localToWorldMatrix;
		for (int n = 0; n < 16; n++)
		{
			if (n > 0)
			{
				sb.Append(",");
			}
			sb.Append(((Matrix4x4)(ref val2))[n / 4, n % 4].ToString("0.######", CultureInfo.InvariantCulture));
		}
		sb.Append("]");
		Plugin.Log.LogInfo((object)("[record] cape skin: " + vertices.Length + " vertices, " + bones2.Length + " bones"));
	}

	private static string F(float f)
	{
		return f.ToString("0.###", CultureInfo.InvariantCulture);
	}

	private static IEnumerator Record(Player p)
	{
		Transform root = ((Component)p).transform;
		int tier = Flight.OpenTier;
		VisEquipment ve = ((Component)p).GetComponent<VisEquipment>();
		List<GameObject> capeObjs = (((Object)(object)ve != (Object)null && CapeF != null) ? (CapeF.GetValue(ve) as List<GameObject>) : null);
		List<SkinnedMeshRenderer> cape = new List<SkinnedMeshRenderer>();
		StringBuilder info = new StringBuilder();
		if (capeObjs != null)
		{
			foreach (GameObject item in capeObjs)
			{
				if (!((Object)(object)item != (Object)null))
				{
					continue;
				}
				SkinnedMeshRenderer[] componentsInChildren = item.GetComponentsInChildren<SkinnedMeshRenderer>(true);
				foreach (SkinnedMeshRenderer val in componentsInChildren)
				{
					if ((Object)(object)val.sharedMesh != (Object)null)
					{
						cape.Add(val);
					}
				}
				Cloth[] componentsInChildren2 = item.GetComponentsInChildren<Cloth>(true);
				foreach (Cloth val2 in componentsInChildren2)
				{
					info.Append(" cloth on ").Append(((Object)val2).name).Append(" (enabled ")
						.Append(val2.enabled)
						.Append(", stretch ")
						.Append(F(val2.stretchingStiffness))
						.Append(", bend ")
						.Append(F(val2.bendingStiffness))
						.Append(", damping ")
						.Append(F(val2.damping))
						.Append(", world velocity ")
						.Append(F(val2.worldVelocityScale))
						.Append(", world acceleration ")
						.Append(F(val2.worldAccelerationScale))
						.Append(", external ")
						.Append(val2.externalAcceleration)
						.Append(", random ")
						.Append(val2.randomAcceleration)
						.Append(")");
				}
			}
		}
		List<MagicaCloth> cloths = new List<MagicaCloth>();
		if (capeObjs != null)
		{
			foreach (GameObject item2 in capeObjs)
			{
				if ((Object)(object)item2 != (Object)null)
				{
					cloths.AddRange(item2.GetComponentsInChildren<MagicaCloth>(true));
				}
			}
		}
		MagicaCloth[] clothOf = (MagicaCloth[])(object)new MagicaCloth[cape.Count];
		for (int k = 0; k < cape.Count; k++)
		{
			foreach (MagicaCloth item3 in cloths)
			{
				Mesh val3 = null;
				try
				{
					val3 = item3.GetCustomMesh((Renderer)(object)cape[k]);
				}
				catch (Exception)
				{
				}
				if (!((Object)(object)val3 == (Object)null))
				{
					clothOf[k] = item3;
					List<Transform> list = null;
					try
					{
						list = item3.GetCustomBones((Renderer)(object)cape[k]);
					}
					catch (Exception)
					{
					}
					info.Append(" magica on ").Append(((Object)cape[k]).name).Append(": renderer uses the cloth mesh ")
						.Append((Object)(object)cape[k].sharedMesh == (Object)(object)val3)
						.Append(", readable ")
						.Append(val3.isReadable)
						.Append(", ")
						.Append(val3.vertexCount)
						.Append(" vertices, renderer bones ")
						.Append((cape[k].bones != null) ? cape[k].bones.Length : (-1))
						.Append(", cloth bones ")
						.Append(list?.Count ?? (-1))
						.Append(", root bone ")
						.Append(((Object)(object)cape[k].rootBone != (Object)null) ? ((Object)cape[k].rootBone).name : "none")
						.Append(", write mode ")
						.Append(item3.SerializeData.meshWriteMode)
						.Append(", type ")
						.Append(item3.SerializeData.clothType);
					break;
				}
			}
		}
		Plugin.Log.LogInfo((object)("[record] cape parts: " + cape.Count + ((info.Length > 0) ? (";" + info) : "; no Cloth component")));
		List<Transform> bones = new List<Transform>();
		HashSet<Transform> seen = new HashSet<Transform>();
		SkinnedMeshRenderer[] componentsInChildren3 = ((Component)p).GetComponentsInChildren<SkinnedMeshRenderer>(false);
		foreach (SkinnedMeshRenderer val4 in componentsInChildren3)
		{
			if (val4.bones == null)
			{
				continue;
			}
			Transform[] bones2 = val4.bones;
			foreach (Transform val5 in bones2)
			{
				Transform val6 = val5;
				while ((Object)(object)val6 != (Object)null && (Object)(object)val6 != (Object)(object)root)
				{
					if (seen.Add(val6))
					{
						bones.Add(val6);
					}
					val6 = val6.parent;
				}
			}
		}
		StringBuilder frames = new StringBuilder();
		int n = 0;
		float start = Time.time;
		bool skip = false;
		while (Time.time - start < 4f && Flight.OpenTier > 0)
		{
			yield return (object)new WaitForEndOfFrame();
			skip = !skip;
			if (skip)
			{
				continue;
			}
			Matrix4x4 toRoot = root.worldToLocalMatrix;
			Quaternion rootInv = Quaternion.Inverse(root.rotation);
			if (n > 0)
			{
				frames.Append(",");
			}
			frames.Append("{\"t\":").Append(F(Time.time - start)).Append(",\"bones\":[");
			for (int num = 0; num < bones.Count; num++)
			{
				Transform val7 = bones[num];
				if (num > 0)
				{
					frames.Append(",");
				}
				if ((Object)(object)val7 == (Object)null)
				{
					frames.Append("null");
					continue;
				}
				Vector3 val8 = ((Matrix4x4)(ref toRoot)).MultiplyPoint3x4(val7.position);
				Quaternion val9 = rootInv * val7.rotation;
				frames.Append("[").Append(F(val8.x)).Append(",")
					.Append(F(val8.y))
					.Append(",")
					.Append(F(val8.z))
					.Append(",")
					.Append(F(val9.x))
					.Append(",")
					.Append(F(val9.y))
					.Append(",")
					.Append(F(val9.z))
					.Append(",")
					.Append(F(val9.w))
					.Append("]");
			}
			frames.Append("],\"cape\":[");
			for (int num2 = 0; num2 < cape.Count; num2++)
			{
				if (num2 > 0)
				{
					frames.Append(",");
				}
				frames.Append("[");
				SkinnedMeshRenderer val10 = cape[num2];
				if ((Object)(object)val10 != (Object)null)
				{
					Mesh val11 = new Mesh();
					val10.BakeMesh(val11, true);
					Matrix4x4 val12 = toRoot * ((Component)val10).transform.localToWorldMatrix;
					Vector3[] vertices = val11.vertices;
					for (int num3 = 0; num3 < vertices.Length; num3++)
					{
						Vector3 val13 = ((Matrix4x4)(ref val12)).MultiplyPoint3x4(vertices[num3]);
						if (num3 > 0)
						{
							frames.Append(",");
						}
						frames.Append(F(val13.x)).Append(",").Append(F(val13.y))
							.Append(",")
							.Append(F(val13.z));
					}
					Object.Destroy((Object)(object)val11);
				}
				frames.Append("]");
			}
			frames.Append("],\"cm\":[");
			for (int num4 = 0; num4 < cape.Count; num4++)
			{
				if (num4 > 0)
				{
					frames.Append(",");
				}
				frames.Append("[");
				Mesh val14 = null;
				if ((Object)(object)clothOf[num4] != (Object)null)
				{
					try
					{
						val14 = clothOf[num4].GetCustomMesh((Renderer)(object)cape[num4]);
					}
					catch (Exception)
					{
					}
				}
				if ((Object)(object)val14 != (Object)null && val14.isReadable)
				{
					Matrix4x4 val15 = toRoot * ((Component)cape[num4]).transform.localToWorldMatrix;
					Vector3[] vertices2 = val14.vertices;
					for (int num5 = 0; num5 < vertices2.Length; num5++)
					{
						Vector3 val16 = ((Matrix4x4)(ref val15)).MultiplyPoint3x4(vertices2[num5]);
						if (num5 > 0)
						{
							frames.Append(",");
						}
						frames.Append(F(val16.x)).Append(",").Append(F(val16.y))
							.Append(",")
							.Append(F(val16.z));
					}
				}
				frames.Append("]");
			}
			frames.Append("]}");
			n++;
		}
		if (n < 10)
		{
			Plugin.Log.LogInfo((object)("[record] only " + n + " frames: the glide was too short, waiting for a longer one"));
			((Character)p).Message((MessageType)1, "Skysail: glide too short to record, glide a bit longer", 0, (Sprite)null, false);
			_running = false;
			yield break;
		}
		StringBuilder sb = new StringBuilder("{\"tier\":").Append(tier).Append(",\"tilt\":").Append(F(Plugin.TiltFor(tier)))
			.Append(",\"bones\":[");
		for (int num6 = 0; num6 < bones.Count; num6++)
		{
			Transform val17 = bones[num6];
			int value = (((Object)(object)val17.parent != (Object)null) ? bones.IndexOf(val17.parent) : (-1));
			if (num6 > 0)
			{
				sb.Append(",");
			}
			Matrix4x4 val18 = root.worldToLocalMatrix * val17.localToWorldMatrix;
			Vector3 lossyScale = ((Matrix4x4)(ref val18)).lossyScale;
			sb.Append("{\"n\":\"").Append(((Object)val17).name).Append("\",\"p\":")
				.Append(value)
				.Append(",\"s\":[")
				.Append(F(lossyScale.x))
				.Append(",")
				.Append(F(lossyScale.y))
				.Append(",")
				.Append(F(lossyScale.z))
				.Append("]}");
		}
		sb.Append("],\"cape\":[");
		Dictionary<Texture, string> texCache = new Dictionary<Texture, string>();
		for (int num7 = 0; num7 < cape.Count; num7++)
		{
			SkinnedMeshRenderer val19 = cape[num7];
			if (num7 > 0)
			{
				sb.Append(",");
			}
			Mesh val20 = new Mesh();
			if ((Object)(object)val19 != (Object)null)
			{
				val19.BakeMesh(val20, true);
			}
			sb.Append("{\"name\":\"").Append(((Object)(object)val19 != (Object)null) ? ((Object)val19).name : "?").Append("\",\"cloth\":")
				.Append(((Object)(object)val19 != (Object)null && (Object)(object)((Component)val19).GetComponent<Cloth>() != (Object)null) ? "true" : "false")
				.Append(",\"uv\":[");
			Vector2[] uv = val20.uv;
			for (int num8 = 0; num8 < uv.Length; num8++)
			{
				if (num8 > 0)
				{
					sb.Append(",");
				}
				sb.Append(F(uv[num8].x)).Append(",").Append(F(uv[num8].y));
			}
			sb.Append("],\"t\":[");
			int[] triangles = val20.triangles;
			for (int num9 = 0; num9 < triangles.Length; num9++)
			{
				if (num9 > 0)
				{
					sb.Append(",");
				}
				sb.Append(triangles[num9]);
			}
			sb.Append("]");
			Object.Destroy((Object)(object)val20);
			Skin(sb, val19, bones, root);
			Material val21 = (((Object)(object)val19 != (Object)null) ? ((Renderer)val19).sharedMaterial : null);
			Texture val22 = (((Object)(object)val21 != (Object)null && val21.HasProperty("_MainTex")) ? val21.mainTexture : null);
			if ((Object)(object)val22 != (Object)null)
			{
				if (!texCache.TryGetValue(val22, out var value2))
				{
					value2 = (texCache[val22] = Exporter.Png(val22, 512));
				}
				if (value2 != null)
				{
					sb.Append(",\"tex\":\"").Append(value2).Append("\"");
				}
			}
			sb.Append("}");
		}
		sb.Append("],\"frames\":[").Append(frames.ToString()).Append("]}");
		try
		{
			string text2 = Path.Combine(Paths.ConfigPath, "Skysail_editor");
			Directory.CreateDirectory(text2);
			string text3 = Path.Combine(text2, "glide_rec.json");
			File.WriteAllText(text3, sb.ToString());
			Plugin.Log.LogInfo((object)("[record] " + n + " frames saved to " + text3));
			((Character)p).Message((MessageType)1, "Skysail: glide recorded (" + n + " frames)", 0, (Sprite)null, false);
		}
		catch (Exception ex4)
		{
			Plugin.Log.LogWarning((object)("[record] " + ex4));
		}
		Plugin.RecordGlide.Value = false;
		_running = false;
	}
}
internal class GlideView : MonoBehaviour
{
	private const float HoldAfter = 1f;

	private const string PoseTurns = "";

	private Player _p;

	private ZNetView _nv;

	private Animator _anim;

	private Transform _hips;

	private int _tier;

	private float _next;

	private float _open;

	private float _airT;

	private float _glideT;

	private bool _held;

	private Transform[] _bones;

	private Quaternion[] _pose;

	private WindLines _wind;

	private Quaternion[] _off;

	private string _offFrom;

	private static readonly List<GlideView> Active = new List<GlideView>();

	private static bool _hooked;

	private int _poseFrame = -1;

	private int _preCount;

	private int _lateCount;

	private Quaternion _leftHips;

	internal float Weight
	{
		get
		{
			if (_tier <= 0)
			{
				return 0f;
			}
			return Mathf.SmoothStep(0f, 1f, _open);
		}
	}

	private void ReadOffsets()
	{
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: Unknown result type (might be due to invalid IL or missing references)
		//IL_0173: 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)
		string text = "";
		if (_off != null && _offFrom == text && _off.Length == _bones.Length)
		{
			return;
		}
		_offFrom = text;
		Dictionary<string, Quaternion> dictionary = new Dictionary<string, Quaternion>();
		string[] array = text.Split(';');
		foreach (string text2 in array)
		{
			int num = text2.IndexOf('=');
			if (num > 0)
			{
				string[] array2 = text2.Substring(num + 1).Split(',');
				if (array2.Length != 3 || !float.TryParse(array2[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || !float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) || !float.TryParse(array2[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result3))
				{
					Plugin.Log.LogWarning((object)("PoseTurns: can't read '" + text2 + "'"));
				}
				else
				{
					dictionary[text2.Substring(0, num).Trim()] = Quaternion.Euler(result, result2, result3);
				}
			}
		}
		_off = (Quaternion[])(object)new Quaternion[_bones.Length];
		for (int j = 0; j < _bones.Length; j++)
		{
			ref Quaternion reference = ref _off[j];
			reference = (((Object)(object)_bones[j] != (Object)null && dictionary.TryGetValue(((Object)_bones[j]).name, out var value)) ? value : Quaternion.identity);
		}
		if (dictionary.Count > 0)
		{
			Plugin.Debug("[glide] pose turns: " + text);
		}
	}

	private void Awake()
	{
		_p = ((Component)this).GetComponent<Player>();
		_nv = ((Component)this).GetComponent<ZNetView>();
	}

	private void Update()
	{
		int num;
		if ((Object)(object)_p == (Object)(object)Player.m_localPlayer)
		{
			num = Flight.OpenTier;
		}
		else
		{
			if (Time.time < _next)
			{
				return;
			}
			_next = Time.time + 0.2f;
			ZDO val = (((Object)(object)_nv != (Object)null) ? _nv.GetZDO() : null);
			num = ((val != null) ? val.GetInt("Skysail_glide", 0) : 0);
		}
		num = Mathf.Clamp(num, 0, Sails.Count);
		if (num != _tier)
		{
			_tier = num;
			if (num == 0)
			{
				Release();
				return;
			}
			_open = 0f;
			_glideT = 0f;
		}
	}

	private bool Find()
	{
		if ((Object)(object)_anim == (Object)null)
		{
			_anim = ((Component)this).GetComponentInChildren<Animator>();
		}
		if ((Object)(object)_hips == (Object)null)
		{
			_hips = Utils.FindChild(((Component)this).transform, "Hips", (IterativeSearchType)0);
			if ((Object)(object)_hips != (Object)null)
			{
				_bones = ((Component)_hips).GetComponentsInChildren<Transform>(true);
			}
		}
		if ((Object)(object)_anim != (Object)null)
		{
			return (Object)(object)_hips != (Object)null;
		}
		return false;
	}

	private void Release()
	{
		if ((Object)(object)_wind != (Object)null)
		{
			_wind.Set(0f);
		}
		_held = false;
		Active.Remove(this);
	}

	private void OnDestroy()
	{
		Release();
	}

	private static void PreSimulation()
	{
		for (int num = Active.Count - 1; num >= 0; num--)
		{
			GlideView glideView = Active[num];
			if ((Object)(object)glideView == (Object)null)
			{
				Active.RemoveAt(num);
			}
			else if (glideView._tier > 0 && glideView.Find())
			{
				glideView.ApplyPose();
				glideView._preCount++;
			}
		}
	}

	private void ApplyPose()
	{
		//IL_015c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0171: Unknown result type (might be due to invalid IL or missing references)
		//IL_018d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0192: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fc: 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_0086: 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_008b: Unknown result type (might be due to invalid IL or missing references)
		float num = 1f;
		if (!_held && num >= 0f)
		{
			float num2 = (((Object)(object)_p == (Object)(object)Player.m_localPlayer) ? _airT : _glideT);
			if (num2 >= num)
			{
				_pose = (Quaternion[])(object)new Quaternion[_bones.Length];
				for (int i = 0; i < _bones.Length; i++)
				{
					ref Quaternion reference = ref _pose[i];
					reference = (((Object)(object)_bones[i] != (Object)null) ? _bones[i].localRotation : Quaternion.identity);
				}
				_held = true;
				Plugin.Debug("[glide] fall pose held, " + num2.ToString("0.00") + " s after leaving the ground");
			}
		}
		if (_held)
		{
			ReadOffsets();
			for (int j = 0; j < _bones.Length; j++)
			{
				if ((Object)(object)_bones[j] != (Object)null)
				{
					_bones[j].localRotation = _pose[j] * _off[j];
				}
			}
		}
		float num3 = Mathf.SmoothStep(0f, 1f, _open);
		_hips.rotation = Quaternion.AngleAxis(Plugin.TiltFor(_tier) * num3, ((Component)this).transform.right) * _hips.rotation;
		_poseFrame = Time.frameCount;
		_leftHips = _hips.localRotation;
	}

	private void LateUpdate()
	{
		//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
		if (!_hooked)
		{
			_hooked = true;
			MagicaManager.OnPreSimulation = (Action)Delegate.Combine(MagicaManager.OnPreSimulation, new Action(PreSimulation));
		}
		float deltaTime = Time.deltaTime;
		if ((Object)(object)_p == (Object)(object)Player.m_localPlayer && ((Character)_p).IsOnGround())
		{
			_airT = 0f;
		}
		else
		{
			_airT += deltaTime;
		}
		if (_tier == 0 || !Find())
		{
			return;
		}
		if (!Active.Contains(this))
		{
			Active.Add(this);
			_preCount = (_lateCount = 0);
		}
		_glideT += deltaTime;
		_open = Mathf.MoveTowards(_open, 1f, deltaTime * 2f);
		if (_poseFrame != Time.frameCount || _hips.localRotation != _leftHips)
		{
			ApplyPose();
			_lateCount++;
		}
		if (_glideT > 2f && _glideT - deltaTime <= 2f)
		{
			Plugin.Debug("[glide] pose put on before the cloth " + _preCount + " times, after it " + _lateCount + " times (first 2 s)");
		}
		if (Plugin.WindLines.Value)
		{
			if ((Object)(object)_wind == (Object)null)
			{
				_wind = WindLines.On(((Component)this).transform);
			}
			_wind.Set(_tier);
		}
		else if ((Object)(object)_wind != (Object)null)
		{
			_wind.Set(0f);
		}
	}
}
[HarmonyPatch]
internal static class GlideHook
{
	[HarmonyPatch(typeof(Player), "Awake")]
	[HarmonyPostfix]
	private static void PlayerAwake(Player __instance)
	{
		if ((Object)(object)((Component)__instance).GetComponent<GlideView>() == (Object)null)
		{
			((Component)__instance).gameObject.AddComponent<GlideView>();
		}
	}
}
internal class CustomItem
{
	internal string PrefabName;

	internal string[] Sources;

	internal Action<GameObject> Setup;

	internal string Cost;

	internal string Station;

	internal int Level;

	internal GameObject Prefab;
}
[HarmonyPatch]
internal static class Items
{
	private static readonly MethodInfo UpdateRegisters = AccessTools.Method(typeof(ObjectDB), "UpdateRegisters", (Type[])null, (Type[])null);

	private static readonly FieldInfo NamedPrefabs = AccessTools.Field(typeof(ZNetScene), "m_namedPrefabs");

	internal static readonly List<CustomItem> All = new List<CustomItem>();

	private static GameObject _holder;

	private static GameObject Build(CustomItem item, Func<string, GameObject> find)
	{
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		if ((Object)(object)item.Prefab != (Object)null)
		{
			return item.Prefab;
		}
		GameObject val = null;
		string[] sources = item.Sources;
		foreach (string arg in sources)
		{
			val = find(arg);
			if ((Object)(object)val != (Object)null)
			{
				break;
			}
		}
		if ((Object)(object)val == (Object)null)
		{
			return null;
		}
		if ((Object)(object)_holder == (Object)null)
		{
			_holder = new GameObject("Skysail_Prefabs");
			_holder.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)_holder);
		}
		GameObject val2 = Object.Instantiate<GameObject>(val, _holder.transform, false);
		((Object)val2).name = item.PrefabName;
		val2.GetComponent<ItemDrop>().m_itemData.m_dropPrefab = val2;
		item.Prefab = val2;
		item.Setup(val2);
		Plugin.Debug("[items] built " + item.PrefabName + " from " + ((Object)val).name);
		return val2;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	private static void ObjectDBAwake(ObjectDB __instance)
	{
		Register(__instance);
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")]
	private static void ObjectDBCopy(ObjectDB __instance)
	{
		Register(__instance);
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(ZNetScene), "Awake")]
	private static void ZNetSceneAwake(ZNetScene __instance)
	{
		Dictionary<int, GameObject> dictionary = ((NamedPrefabs != null) ? (NamedPrefabs.GetValue(__instance) as Dictionary<int, GameObject>) : null);
		foreach (CustomItem item in All)
		{
			GameObject val = Build(item, (string n) => __instance.m_prefabs.Find((GameObject g) => (Object)(object)g != (Object)null && ((Object)g).name == n));
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)("Could not build " + item.PrefabName + ": no source item found."));
				continue;
			}
			if (!__instance.m_prefabs.Contains(val))
			{
				__instance.m_prefabs.Add(val);
			}
			if (dictionary != null)
			{
				dictionary[StringExtensionMethods.GetStableHashCode(item.PrefabName)] = val;
			}
		}
		if ((Object)(object)ObjectDB.instance != (Object)null)
		{
			Register(ObjectDB.instance);
		}
	}

	private static void Register(ObjectDB db)
	{
		if ((Object)(object)db == (Object)null || db.m_items == null || db.m_items.Count == 0)
		{
			return;
		}
		bool flag = false;
		foreach (CustomItem item in All)
		{
			GameObject val = Build(item, (string n) => db.m_items.Find((GameObject g) => (Object)(object)g != (Object)null && ((Object)g).name == n));
			if (!((Object)(object)val == (Object)null) && !db.m_items.Contains(val))
			{
				db.m_items.Add(val);
				flag = true;
			}
		}
		if (flag && UpdateRegisters != null)
		{
			UpdateRegisters.Invoke(db, null);
		}
		foreach (CustomItem item2 in All)
		{
			if ((Object)(object)item2.Prefab != (Object)null)
			{
				AddRecipe(db, item2);
			}
		}
	}

	private static void AddRecipe(ObjectDB db, CustomItem item)
	{
		//IL_0113: Unknown result type (might be due to invalid IL or missing references)
		//IL_011a: Expected O, but got Unknown
		ItemDrop drop = item.Prefab.GetComponent<ItemDrop>();
		Recipe val = db.m_recipes.Find((Recipe r) => (Object)(object)r != (Object)null && (Object)(object)r.m_item == (Object)(object)drop);
		CraftingStation craftingStation = null;
		string text = (item.Station ?? "").Trim();
		if (text.Length > 0)
		{
			GameObject val2 = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(text) : null);
			if ((Object)(object)val2 == (Object)null)
			{
				return;
			}
			craftingStation = val2.GetComponent<CraftingStation>();
		}
		List<Requirement> list = new List<Requirement>();
		string[] array = (item.Cost ?? "").Split(',');
		foreach (string text2 in array)
		{
			string[] array2 = text2.Split(':');
			if (array2.Length == 2)
			{
				GameObject itemPrefab = db.GetItemPrefab(array2[0].Trim());
				if ((Object)(object)itemPrefab == (Object)null || !int.TryParse(array2[1].Trim(), out var result))
				{
					Plugin.Log.LogWarning((object)(item.PrefabName + " recipe: unknown item '" + text2 + "'."));
					continue;
				}
				Requirement val3 = new Requirement();
				val3.m_resItem = itemPrefab.GetComponent<ItemDrop>();
				val3.m_amount = result;
				val3.m_recover = true;
				list.Add(val3);
			}
		}
		if ((Object)(object)val == (Object)null)
		{
			val = ScriptableObject.CreateInstance<Recipe>();
			((Object)val).name = "Recipe_" + item.PrefabName;
			db.m_recipes.Add(val);
		}
		val.m_item = drop;
		val.m_amount = 1;
		val.m_enabled = true;
		val.m_craftingStation = craftingStation;
		val.m_minStationLevel = Mathf.Max(1, item.Level);
		val.m_resources = list.ToArray();
	}
}
[BepInPlugin("felih.Skysail", "Skysail", "0.1.0")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "felih.Skysail";

	public const string NAME = "Skysail";

	public const string VERSION = "0.1.0";

	internal static ManualLogSource Log;

	internal static ConfigEntry<float> MinHeight;

	internal static ConfigEntry<float> MinStamina;

	internal static ConfigEntry<bool> DetailedLog;

	internal static ConfigEntry<bool> ExportPlayer;

	internal static ConfigEntry<bool> ExportPoses;

	internal static ConfigEntry<bool> ExportFall;

	internal static ConfigEntry<float> SoftFallShare;

	internal static ConfigEntry<float> LandHeight;

	internal static ConfigEntry<bool> WindLines;

	internal static ConfigEntry<bool> RecordGlide;

	internal static ConfigEntry<float> CapeStream;

	internal static ConfigEntry<float> CapeGravity;

	internal static ConfigEntry<float> CapeFlutter;

	internal static ConfigEntry<float> CapeTurbulence;

	internal static ConfigEntry<float> CapeFrequency;

	internal static ConfigEntry<float> CapeMovingWind;

	private void Awake()
	{
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0044: Expected O, but got Unknown
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Expected O, but got Unknown
		//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Expected O, but got Unknown
		//IL_0114: Unknown result type (might be due to invalid IL or missing references)
		//IL_011e: Expected O, but got Unknown
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_015c: Expected O, but got Unknown
		//IL_0190: Unknown result type (might be due to invalid IL or missing references)
		//IL_019a: Expected O, but got Unknown
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Expected O, but got Unknown
		//IL_020c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0216: Expected O, but got Unknown
		//IL_024a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0254: Expected O, but got Unknown
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_0292: Expected O, but got Unknown
		//IL_033c: Unknown result type (might be due to invalid IL or missing references)
		Log = ((BaseUnityPlugin)this).Logger;
		MinHeight = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "MinHeight", 3f, new ConfigDescription("Metres above the ground needed to open the sail (press Jump in the air).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), new object[0]));
		MinStamina = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "MinStamina", 5f, new ConfigDescription("Stamina needed to open the sail.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 50f), new object[0]));
		LandHeight = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "LandHeight", 1f, new ConfigDescription("The sail closes by itself this many metres above the ground, so you land with the game's own landing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), new object[0]));
		WindLines = ((BaseUnityPlugin)this).Config.Bind<bool>("2 - Look", "WindLines", true, "White wind streaks along your sides while gliding.");
		SoftFallShare = ((BaseUnityPlugin)this).Config.Bind<float>("1 - General", "SoftFallShare", 0.5f, new ConfigDescription("After you close the sail in the air, the next fall does this share of its damage (0.5 = half), until you touch the ground.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		CapeStream = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeStream", 0.6f, new ConfigDescription("While gliding, how far the cape's gravity turns from straight down (0) to straight behind you (1): the air pushing it back.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		CapeGravity = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeGravity", 1f, new ConfigDescription("While gliding, the cape's gravity strength (1 = the game's).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), new object[0]));
		CapeFlutter = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeFlutter", 1.5f, new ConfigDescription("While gliding, how much the wind moves the cape (the game uses about 1).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), new object[0]));
		CapeTurbulence = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeTurbulence", 1f, new ConfigDescription("While gliding, how uneven the wind on the cape is.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 2f), new object[0]));
		CapeFrequency = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeFrequency", 1.5f, new ConfigDescription("While gliding, how fast the cape flutters.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), new object[0]));
		CapeMovingWind = ((BaseUnityPlugin)this).Config.Bind<float>("3 - Cape", "CapeMovingWind", 0.5f, new ConfigDescription("While gliding, how much your own speed blows on the cape.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), new object[0]));
		DetailedLog = ((BaseUnityPlugin)this).Config.Bind<bool>("9 - Debug", "DetailedLog", false, "Writes glide details to the BepInEx log.");
		ExportPlayer = ((BaseUnityPlugin)this).Config.Bind<bool>("9 - Debug", "ExportCharacterAndCapes", false, "Saves your character and every vanilla cape once (standing still for 3 s) for the capes editor, then turns itself off.");
		ExportPoses = ((BaseUnityPlugin)this).Config.Bind<bool>("9 - Debug", "ExportPoses", false, "Plays every emote once (standing still for 3 s) and saves each pose with your cape for the pose picker, then turns itself off.");
		RecordGlide = ((BaseUnityPlugin)this).Config.Bind<bool>("9 - Debug", "RecordGlide", false, "Records 4 s of your next glide (body, cape) for the glide editor, then turns itself off.");
		ExportFall = ((BaseUnityPlugin)this).Config.Bind<bool>("9 - Debug", "ExportFallPose", false, "Saves your skeleton about 1 s into every fall (without opening the sail) for the editor; each fall replaces the last.");
		new Harmony("felih.Skysail").PatchAll(typeof(Plugin).Assembly);
		Log.LogInfo((object)"Skysail 0.1.0 loaded");
	}

	internal static float TiltFor(int tier)
	{
		return 35f + 5f * (float)Mathf.Max(0, tier - 1);
	}

	internal static void Debug(string s)
	{
		if (DetailedLog.Value)
		{
			Log.LogInfo((object)s);
		}
	}
}
[HarmonyPatch]
internal static class PoseExport
{
	private static float _stillSince = -1f;

	private static bool _running;

	[HarmonyPostfix]
	[HarmonyPatch(typeof(Player), "Update")]
	private static void Tick(Player __instance)
	{
		//IL_004c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || _running || !Plugin.ExportPoses.Value)
		{
			return;
		}
		Rigidbody component = ((Component)__instance).GetComponent<Rigidbody>();
		if (((Character)__instance).IsOnGround() && !((Character)__instance).IsAttached() && !((Character)__instance).InWater() && (Object)(object)component != (Object)null)
		{
			Vector3 linearVelocity = component.linearVelocity;
			if (((Vector3)(ref linearVelocity)).magnitude < 0.1f)
			{
				if (_stillSince < 0f)
				{
					_stillSince = Time.time;
				}
				else if (!(Time.time - _stillSince < 3f))
				{
					Plugin.ExportPoses.Value = false;
					_running = true;
					((Character)__instance).Message((MessageType)2, "Skysail: saving the emote poses, stand still...", 0, (Sprite)null, false);
					((MonoBehaviour)__instance).StartCoroutine(Run(__instance));
				}
				return;
			}
		}
		_stillSince = -1f;
	}

	private static string F(float f)
	{
		return f.ToString("0.###", CultureInfo.InvariantCulture);
	}

	private static IEnumerator Run(Player p)
	{
		Transform root = ((Component)p).transform;
		Vector3 startPos = root.position;
		MethodInfo doEmote = AccessTools.Method(typeof(Emote), "DoEmote", (Type[])null, (Type[])null);
		MethodInfo stopEmote = AccessTools.Method(typeof(Character), "StopEmote", (Type[])null, (Type[])null);
		List<SkinnedMeshRenderer> sks = new List<SkinnedMeshRenderer>();
		SkinnedMeshRenderer[] componentsInChildren = ((Component)p).GetComponentsInChildren<SkinnedMeshRenderer>(false);
		foreach (SkinnedMeshRenderer val in componentsInChildren)
		{
			if (((Renderer)val).enabled && (Object)(object)val.sharedMesh != (Object)null)
			{
				sks.Add(val);
			}
		}
		StringBuilder poses = new StringBuilder();
		int count = 0;
		bool aborted = false;
		Snap(poses, "stand", sks, root, ref count);
		foreach (object e in Enum.GetValues(typeof(Emotes)))
		{
			string name = e.ToString();
			bool oneshot = true;
			FieldInfo fi = typeof(Emotes).GetField(name);
			object[] at = ((fi != null) ? fi.GetCustomAttributes(typeof(Emote), inherit: false) : new object[0]);
			if (at.Length > 0)
			{
				oneshot = ((Emote)at[0]).OneShot;
			}
			try
			{
				if (doEmote != null)
				{
					doEmote.Invoke(null, new object[1] { e });
				}
				else
				{
					p.StartEmote(name.ToLower(), oneshot);
				}
			}
			catch (Exception ex)
			{
				Plugin.Debug("[poses] " + name + ": " + ex.Message);
				continue;
			}
			float[] moments = ((!oneshot) ? new float[1] { 1.8f } : new float[3] { 0.5f, 1f, 1.6f });
			float t0 = Time.time;
			try
			{
				float[] array = moments;
				foreach (float m in array)
				{
					while (Time.time - t0 < m)
					{
						yield return null;
					}
					Vector3 val2 = root.position - startPos;
					if (((Vector3)(ref val2)).sqrMagnitude > 0.25f || ((Character)p).IsDead())
					{
						aborted = true;
						break;
					}
					string name2;
					if (!oneshot)
					{
						name2 = name;
					}
					else
					{
						float num = m;
						name2 = name + " " + num.ToString("0.0", CultureInfo.InvariantCulture) + "s";
					}
					Snap(poses, name2, sks, root, ref count);
				}
			}
			finally
			{
			}
			if (stopEmote != null)
			{
				stopEmote.Invoke(p, null);
			}
			if (aborted)
			{
				break;
			}
			float t1 = Time.time;
			while (Time.time - t1 < 0.6f)
			{
				yield return null;
			}
		}
		_running = false;
		if (aborted)
		{
			((Character)p).Message((MessageType)2, "Skysail: you moved, the poses were not saved", 0, (Sprite)null, false);
			Plugin.ExportPoses.Value = true;
			yield break;
		}
		StringBuilder sb = new StringBuilder("{\"parts\":[");
		Dictionary<Texture, string> texCache = new Dictionary<Texture, string>();
		for (int k = 0; k < sks.Count; k++)
		{
			SkinnedMeshRenderer val3 = sks[k];
			if (k > 0)
			{
				sb.Append(",");
			}
			Mesh val4 = new Mesh();
			val3.BakeMesh(val4, true);
			Vector2[] uv = val4.uv;
			int[] triangles = val4.triangles;
			Object.Destroy((Object)(object)val4);
			sb.Append("{\"name\":\"").Append(((Object)val3).name).Append("\",\"uv\":[");
			for (int l = 0; l < uv.Length; l++)
			{
				if (l > 0)
				{
					sb.Append(",");
				}
				sb.Append(F(uv[l].x)).Append(",").Append(F(uv[l].y));
			}
			sb.Append("],\"t\":[");
			for (int n = 0; n < triangles.Length; n++)
			{
				if (n > 0)
				{
					sb.Append(",");
				}
				sb.Append(triangles[n]);
			}
			sb.Append("]");
			Material sharedMaterial = ((Renderer)val3).sharedMaterial;
			Texture val5 = (((Object)(object)sharedMaterial != (Object)null && sharedMaterial.HasProperty("_MainTex")) ? sharedMaterial.mainTexture : null);
			if ((Object)(object)val5 != (Object)null)
			{
				if (!texCache.TryGetValue(val5, out var value))
				{
					value = (texCache[val5] = Exporter.Png(val5, 512));
				}
				if (value != null)
				{
					sb.Append(",\"tex\":\"").Append(value).Append("\"");
				}
			}
			if ((Object)(object)sharedMaterial != (Object)null && sharedMaterial.HasProperty("_Color"))
			{
				Color color = sharedMaterial.color;
				sb.Append(",\"col\":[").Append(F(color.r)).Append(",")
					.Append(F(color.g))
					.Append(",")
					.Append(F(color.b))
					.Append("]");
			}
			sb.Append("}");
		}
		sb.Append("],\"poses\":[").Append(poses.ToString()).Append("]}");
		string dir = Path.Combine(Paths.ConfigPath, "Skysail_editor");
		Directory.CreateDirectory(dir);
		string path = Path.Combine(dir, "poses.json");
		File.WriteAllText(path, sb.ToString());
		Plugin.Log.LogInfo((object)("[poses] " + count + " poses saved to " + path));
		((Character)p).Message((MessageType)2, "Skysail: " + count + " poses saved for the pose picker", 0, (Sprite)null, false);
	}

	private static void Snap(StringBuilder sb, string name, List<SkinnedMeshRenderer> sks, Transform root, ref int count)
	{
		//IL_0001: 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_006c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0072: Expected O, but got Unknown
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		Matrix4x4 worldToLocalMatrix = root.worldToLocalMatrix;
		if (count > 0)
		{
			sb.Append(",");
		}
		sb.Append("{\"name\":\"").Append(name).Append("\",\"v\":[");
		for (int i = 0; i < sks.Count; i++)
		{
			SkinnedMeshRenderer val = sks[i];
			if (i > 0)
			{
				sb.Append(",");
			}
			sb.Append("[");
			if ((Object)(object)val != (Object)null)
			{
				Mesh val2 = new Mesh();
				val.BakeMesh(val2, true);
				Matrix4x4 val3 = worldToLocalMatrix * ((Component)val).transform.localToWorldMatrix;
				Vector3[] vertices = val2.vertices;
				for (int j = 0; j < vertices.Length; j++)
				{
					Vector3 val4 = ((Matrix4x4)(ref val3)).MultiplyPoint3x4(vertices[j]);
					if (j > 0)
					{
						sb.Append(",");
					}
					sb.Append(F(val4.x)).Append(",").Append(F(val4.y))
						.Append(",")
						.Append(F(val4.z));
				}
				Object.Destroy((Object)(object)val2);
			}
			sb.Append("]");
		}
		sb.Append("]}");
		count++;
	}
}
internal class Tier
{
	internal string Prefab;

	internal string Name;

	internal string Desc;

	internal string[] Sources;

	internal string Cost;

	internal string Station;

	internal int Level;

	internal float Forward;

	internal float Descent;

	internal float Turn;

	internal float Stamina;

	internal Color Hide;

	internal Color Trim;

	internal int Feathers;

	internal float FeatherLen = 0.3f;

	internal Color Feather = Color.black;

	internal string CapeLook;
}
internal static class Sails
{
	internal static readonly Tier[] Tiers = new Tier[7]
	{
		null,
		new Tier
		{
			Prefab = "Skysail_DeerHide",
			Name = "Deer hide wingcape",
			Sources = new string[1] { "CapeDeerHide" },
			Desc = "Raw deer hide sewn between your arms and legs. It won't take you far, but it beats the fall.",
			Cost = "DeerHide:6, Wood:10, LeatherScraps:6",
			Station = "piece_workbench",
			Level = 2,
			CapeLook = "CapeDeerHide",
			Forward = 8f,
			Descent = -2.4f,
			Turn = 80f,
			Stamina = 3f,
			Feathers = 0,
			FeatherLen = 0f,
			Hide = new Color(0.62f, 0.46f, 0.3f),
			Trim = new Color(0.36f, 0.25f, 0.15f)
		},
		new Tier
		{
			Prefab = "Skysail_TrollHide",
			Name = "Troll hide wingcape",
			Sources = new string[2] { "CapeTrollHide", "CapeDeerHide" },
			Desc = "Tough troll hide stretched like a bat's wing, stiffened with bronze ribs.",
			Cost = "TrollHide:6, FineWood:8, Bronze:2",
			Station = "piece_workbench",
			Level = 3,
			CapeLook = "CapeTrollHide",
			Forward = 10f,
			Descent = -2.4f,
			Turn = 90f,
			Stamina = 2.4f,
			Feathers = 0,
			FeatherLen = 0f,
			Hide = new Color(0.38f, 0.45f, 0.55f),
			Trim = new Color(0.22f, 0.24f, 0.3f)
		},
		new Tier
		{
			Prefab = "Skysail_WolfPelt",
			Name = "Wolf pelt wingcape",
			Sources = new string[2] { "CapeWolf", "CapeDeerHide" },
			Desc = "Wolf pelts with a fringe of grey feathers along the trailing edge. Made for mountain winds.",
			Cost = "WolfPelt:6, FineWood:10, Silver:4",
			Station = "piece_workbench",
			Level = 4,
			Forward = 12f,
			Descent = -2.4f,
			Turn = 100f,
			Stamina = 1.9f,
			Feathers = 1,
			FeatherLen = 0.22f,
			Feather = new Color(0.62f, 0.62f, 0.64f),
			Hide = new Color(0.72f, 0.72f, 0.74f),
			Trim = new Color(0.92f, 0.9f, 0.86f)
		},
		new Tier
		{
			Prefab = "Skysail_LoxPelt",
			Name = "Lox pelt wingcape",
			Sources = new string[2] { "CapeLox", "CapeDeerHide" },
			Desc = "Lox pelt and linen, edged with long brown feathers.",
			Cost = "LoxPelt:4, LinenThread:10, FineWood:10, BlackMetal:4",
			Station = "piece_workbench",
			Level = 4,
			Forward = 14f,
			Descent = -2.4f,
			Turn = 110f,
			Stamina = 1.4f,
			Feathers = 1,
			FeatherLen = 0.32f,
			Feather = new Color(0.4f, 0.27f, 0.16f),
			Hide = new Color(0.76f, 0.62f, 0.42f),
			Trim = new Color(0.55f, 0.18f, 0.12f)
		},
		new Tier
		{
			Prefab = "Skysail_Carapace",
			Name = "Mistfeather wingcape",
			Sources = new string[3] { "CapeFeather", "CapeLox", "CapeDeerHide" },
			Desc = "Grey feathers over a thin scale hide, ribbed with carapace. Light as mist.",
			Cost = "Carapace:8, ScaleHide:6, YggdrasilWood:10, Feathers:10",
			Station = "blackforge",
			Level = 1,
			Forward = 16f,
			Descent = -2.4f,
			Turn = 120f,
			Stamina = 1f,
			Feathers = 2,
			FeatherLen = 0.36f,
			Feather = new Color(0.5f, 0.48f, 0.56f),
			Hide = new Color(0.45f, 0.4f, 0.6f),
			Trim = new Color(0.25f, 0.55f, 0.6f)
		},
		new Tier
		{
			Prefab = "Skysail_Ashwing",
			Name = "Ravenwing cape",
			Sources = new string[3] { "CapeAsksvin", "CapeFeather", "CapeDeerHide" },
			Desc = "Black feathers like the raven who watched over you from the start. It opens wide and carries you far.",
			Cost = "AskHide:8, FlametalNew:4, CelestialFeather:2, YggdrasilWood:10",
			Station = "blackforge",
			Level = 2,
			Forward = 18f,
			Descent = -2.4f,
			Turn = 130f,
			Stamina = 0.7f,
			Feathers = 2,
			FeatherLen = 0.46f,
			Feather = new Color(0.07f, 0.07f, 0.085f),
			Hide = new Color(0.1f, 0.1f, 0.12f),
			Trim = new Color(0.05f, 0.05f, 0.06f)
		}
	};

	private static readonly Dictionary<string, int> Extra = new Dictionary<string, int>
	{
		{ "CapeLinen", 4 },
		{ "CapeOdin", 3 },
		{ "CapeAsh", 6 },
		{ "CapeDeepNorth", 6 },
		{ "CapeDeepNorthMage", 6 },
		{ "CapeTest", 0 }
	};

	internal static int Count => Tiers.Length - 1;

	internal static void Register()
	{
		for (int i = 1; i <= Count; i++)
		{
			Tier tier = Tiers[i];
			int tier2 = i;
			Items.All.Add(new CustomItem
			{
				PrefabName = tier.Prefab,
				Sources = tier.Sources,
				Cost = tier.Cost,
				Station = tier.Station,
				Level = tier.Level,
				Setup = delegate(GameObject p)
				{
					SetupItem(p, tier2);
				}
			});
		}
	}

	private static void SetupItem(GameObject p, int tier)
	{
		//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
		Tier tier2 = Tiers[tier];
		SharedData shared = p.GetComponent<ItemDrop>().m_itemData.m_shared;
		shared.m_name = tier2.Name;
		shared.m_description = tier2.Desc + "\n\nWear it as your cape. Jump in the air to spread it into wings, jump again to fold it. Hold forward to dive, back to slow down.";
		shared.m_armor = 1f;
		shared.m_armorPerLevel = 0f;
		shared.m_maxQuality = 1;
		shared.m_movementModifier = 0f;
		shared.m_equipStatusEffect = null;
		shared.m_setStatusEffect = null;
		shared.m_setName = "";
		shared.m_setSize = 0;
		shared.m_damageModifiers = new List<DamageModPair>();
		shared.m_weight = 4f;
		shared.m_value = 0;
		if (shared.m_icons != null && shared.m_icons.Length > 0)
		{
			shared.m_icons = (Sprite[])(object)new Sprite[1] { Tint(shared.m_icons[0], tier2.Hide, tier2.Prefab + "_icon") };
		}
		p.AddComponent<SailTier>().Tier = tier;
	}

	internal static int TierOf(ItemData item)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Invalid comparison between Unknown and I4
		if (item == null || (Object)(object)item.m_dropPrefab == (Object)null)
		{
			return 0;
		}
		string name = ((Object)item.m_dropPrefab).name;
		for (int i = 1; i <= Count; i++)
		{
			if (Tiers[i].Sources[0] == name)
			{
				return i;
			}
		}
		if (Extra.TryGetValue(name, out var value))
		{
			return value;
		}
		if ((int)item.m_shared.m_itemType != 17)
		{
			return 0;
		}
		string text = name.ToLowerInvariant();
		if (text.Contains("deer") || text.Contains("meadow"))
		{
			return 1;
		}
		if (text.Contains("troll") || text.Contains("bforest") || text.Contains("swamp"))
		{
			return 2;
		}
		if (text.Contains("wolf") || text.Contains("mountain"))
		{
			return 3;
		}
		if (text.Contains("lox") || text.Contains("linen") || text.Contains("plains"))
		{
			return 4;
		}
		if (text.Contains("feather") || text.Contains("mist"))
		{
			return 5;
		}
		if (text.Contains("asksvin") || text.Contains("ash"))
		{
			return 6;
		}
		return 3;
	}

	private static Sprite Tint(Sprite s, Color tint, string name)
	{
		//IL_0008: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Unknown result type (might be due to invalid IL or missing references)
		//IL_004c: Expected O, but got Unknown
		//IL_007a: 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_00b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_014e: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Texture2D texture = s.texture;
			Rect textureRect = s.textureRect;
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height);
			Graphics.Blit((Texture)(object)texture, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D((int)((Rect)(ref textureRect)).width, (int)((Rect)(ref textureRect)).height, (TextureFormat)4, false);
			val.ReadPixels(new Rect(((Rect)(ref textureRect)).x, (float)((Texture)texture).height - ((Rect)(ref textureRect)).y - ((Rect)(ref textureRect)).height, ((Rect)(ref textureRect)).width, ((Rect)(ref textureRect)).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			Color[] pixels = val.GetPixels();
			for (int i = 0; i < pixels.Length; i++)
			{
				Color val2 = pixels[i];
				float num = (val2.r + val2.g + val2.b) / 3f * 1.6f;
				ref Color reference = ref pixels[i];
				reference = new Color(tint.r * num, tint.g * num, tint.b * num, val2.a);
			}
			val.SetPixels(pixels);
			val.Apply();
			Sprite val3 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f));
			((Object)val3).name = name;
			return val3;
		}
		catch (Exception ex)
		{
			Plugin.Debug("[items] icon tint failed: " + ex.Message);
			return s;
		}
	}
}
internal class SailTier : MonoBehaviour
{
	public int Tier = 1;
}
internal class WindLines : MonoBehaviour
{
	private static Material _mat;

	private static bool _looked;

	private ParticleSystem[] _ps = (ParticleSystem[])(object)new ParticleSystem[2];

	internal static WindLines On(Transform player)
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Expected O, but got Unknown
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		WindLines componentInChildren = ((Component)player).GetComponentInChildren<WindLines>(true);
		if ((Object)(object)componentInChildren != (Object)null)
		{
			return componentInChildren;
		}
		GameObject val = new GameObject("Skysail_WindLines");
		val.transform.SetParent(player, false);
		val.transform.localPosition = new Vector3(0f, 1f, 0f);
		componentInChildren = val.AddComponent<WindLines>();
		componentInChildren.Build();
		return componentInChildren;
	}

	private static Material FindMaterial()
	{
		//IL_0148: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Expected O, but got Unknown
		if (_looked)
		{
			return _mat;
		}
		_looked = true;
		Material val = null;
		ParticleSystemRenderer[] array = Resources.FindObjectsOfTypeAll<ParticleSystemRenderer>();
		foreach (ParticleSystemRenderer val2 in array)
		{
			Material sharedMaterial = ((Renderer)val2).sharedMaterial;
			if (!((Object)(object)sharedMaterial == (Object)null) && !((Object)(object)sharedMaterial.shader == (Object)null))
			{
				string text = (((Object)((Component)val2).gameObject).name + " " + ((Object)sharedMaterial).name).ToLowerInvariant();
				if (text.Contains("wind") && !text.Contains("leaf") && !text.Contains("leaves"))
				{
					_mat = sharedMaterial;
					break;
				}
				if ((Object)(object)val == (Object)null && ((Object)sharedMaterial.shader).name.ToLowerInvariant().Contains("particle"))
				{
					val = sharedMaterial;
				}
			}
		}
		if ((Object)(object)_mat == (Object)null)
		{
			_mat = val;
		}
		Plugin.Debug("[wind] streak material: " + (((Object)(object)_mat != (Object)null) ? (((Object)_mat).name + " (" + ((Object)_mat.shader).name + ")") : "none, using a plain one"));
		if ((Object)(object)_mat == (Object)null)
		{
			_mat = new Material(Shader.Find("Sprites/Default"));
		}
		return _mat;
	}

	private void Build()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < 2; i++)
		{
			GameObject val = new GameObject((i == 0) ? "left" : "right");
			val.transform.SetParent(((Component)this).transform, false);
			val.transform.localPosition = new Vector3((i == 0) ? (-0.6f) : 0.6f, 0f, 0f);
			_ps[i] = Side(val);
		}
	}

	private static ParticleSystem Side(GameObject go)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		//IL_009a: Unknown result type (might be due to invalid IL or missing references)
		//IL_009f: 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_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e4: 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_0107: 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_0133: Unknown result type (might be due to invalid IL or missing references)
		//IL_013e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0143: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Expected O, but got Unknown
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_0170: Unknown result type (might be due to invalid IL or missing references)
		//IL_0175: 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_018c: 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_01b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ff: Unknown result type (might be due to invalid IL or missing references)
		ParticleSystem val = go.AddComponent<ParticleSystem>();
		val.Stop(true, (ParticleSystemStopBehavior)0);
		MainModule main = val.main;
		((MainModule)(ref main)).loop = true;
		((MainModule)(ref main)).playOnAwake = false;
		((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)0;
		((MainModule)(ref main)).startLifetime = new MinMaxCurve(0.18f, 0.32f);
		((MainModule)(ref main)).startSpeed = MinMaxCurve.op_Implicit(0f);
		((MainModule)(ref main)).startSize = new MinMaxCurve(0.012f, 0.025f);
		((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(1f, 1f, 1f, 0.55f));
		((MainModule)(ref main)).maxParticles = 70;
		EmissionModule emission = val.emission;
		((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
		ShapeModule shape = val.shape;
		((ShapeModule)(ref shape)).enabled = true;
		((ShapeModule)(ref shape)).shapeType = (ParticleSystemShapeType)5;
		((ShapeModule)(ref shape)).scale = new Vector3(0.35f, 1.5f, 0.6f);
		VelocityOverLifetimeModule velocityOverLifetime = val.velocityOverLifetime;
		((VelocityOverLifetimeModule)(ref velocityOverLifetime)).enabled = true;
		((VelocityOverLifetimeModule)(ref velocityOverLifetime)).space = (ParticleSystemSimulationSpace)0;
		((VelocityOverLifetimeModule)(ref velocityOverLifetime)).x = new MinMaxCurve(0f, 0f);
		((VelocityOverLifetimeModule)(ref velocityOverLifetime)).y = new MinMaxCurve(-1f, 1f);
		((VelocityOverLifetimeModule)(ref velocityOverLifetime)).z = new MinMaxCurve(-16f, -11f);
		ColorOverLifetimeModule colorOverLifetime = val.colorOverLifetime;
		((ColorOverLifetimeModule)(ref colorOverLifetime)).enabled = true;
		Gradient val2 = new Gradient();
		val2.SetKeys((GradientColorKey[])(object)new GradientColorKey[2]
		{
			new GradientColorKey(Color.white, 0f),
			new GradientColorKey(Color.white, 1f)
		}, (GradientAlphaKey[])(object)new GradientAlphaKey[3]
		{
			new GradientAlphaKey(0f, 0f),
			new GradientAlphaKey(0.6f, 0.25f),