Decompiled source of Eclipse AdvancedSkins v0.1.6

BepInEx/plugins/EclipseAdvancedSkins/Eclipse.AdvancedSkins.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using EntityStates;
using EntityStates.Croco;
using KinematicCharacterController;
using On.RoR2;
using RoR2;
using RoR2.ContentManagement;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Audio;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.1.6.0")]
[assembly: AssemblyInformationalVersion("0.1.6-native-presentation-fabric")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace Eclipse.AdvancedSkins;

public sealed class AdvancedSkinApplicationBridge : IDisposable
{
	private static bool installed;

	private readonly HashSet<SkinDef> ownedSkins = new HashSet<SkinDef>();

	private bool disposed;

	public AdvancedSkinApplicationBridge()
	{
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0039: Expected O, but got Unknown
		if (installed)
		{
			throw new InvalidOperationException("Advanced skin bridge already installed");
		}
		NativeItemDisplayOrigins.Install();
		SkinDef.ApplyAsync += new hook_ApplyAsync(Apply);
		CharacterBody.onBodyAwakeGlobal += BodyAwake;
		installed = true;
	}

	private void BodyAwake(CharacterBody body)
	{
		if (Object.op_Implicit((Object)(object)body) && Object.op_Implicit((Object)(object)body.modelLocator) && Object.op_Implicit((Object)(object)body.modelLocator.modelTransform))
		{
			AdvancedSkinModel component = ((Component)body.modelLocator.modelTransform).GetComponent<AdvancedSkinModel>();
			if (Object.op_Implicit((Object)(object)component))
			{
				component.BindBody(body);
			}
		}
	}

	public void Register(SkinDef skin, Mesh mesh)
	{
		if (disposed || !Object.op_Implicit((Object)(object)skin) || !AdvancedSkinRegistry.TryGet(mesh, out var _) || !ownedSkins.Add(skin))
		{
			throw new ArgumentException("Register a unique skin with a registered custom mesh");
		}
	}

	private IEnumerator Apply(orig_ApplyAsync orig, SkinDef skin, GameObject model, List<AssetReferenceT<Material>> materials, List<AssetReferenceT<Mesh>> meshes, AsyncReferenceHandleUnloadType unload)
	{
		//IL_008c: Unknown result type (might be due to invalid IL or missing references)
		AdvancedSkinModel advancedSkinModel = (Object.op_Implicit((Object)(object)model) ? model.GetComponent<AdvancedSkinModel>() : null);
		SkinRigDriver driver = null;
		if (ownedSkins.Contains(skin) && !Object.op_Implicit((Object)(object)advancedSkinModel))
		{
			throw new InvalidOperationException("Advanced skin requires its own validated body/display template");
		}
		if (Object.op_Implicit((Object)(object)advancedSkinModel))
		{
			try
			{
				driver = advancedSkinModel.Prepare();
			}
			catch (Exception ex)
			{
				if (ownedSkins.Contains(skin))
				{
					throw;
				}
				Debug.LogError((object)("ECLIPSE_NATIVE_SNAPSHOT_FAILED " + ex));
			}
		}
		IEnumerator enumerator = orig.Invoke(skin, model, materials, meshes, unload);
		if (!Object.op_Implicit((Object)(object)driver) || enumerator == null)
		{
			return enumerator;
		}
		return SkinApplyObservation.Observe(enumerator, delegate
		{
			if (Object.op_Implicit((Object)(object)driver))
			{
				driver.SynchronizeSkin();
			}
		}, delegate(Exception ex2)
		{
			Debug.LogError((object)("ECLIPSE_SKIN_RECONCILE_FAILED " + ex2));
		});
	}

	internal void Remove(SkinDef skin)
	{
		ownedSkins.Remove(skin);
	}

	public void Dispose()
	{
		//IL_0015: Unknown result type (might be due to invalid IL or missing references)
		//IL_001f: Expected O, but got Unknown
		if (!disposed)
		{
			NativeItemDisplayOrigins.Remove();
			SkinDef.ApplyAsync -= new hook_ApplyAsync(Apply);
			CharacterBody.onBodyAwakeGlobal -= BodyAwake;
			ownedSkins.Clear();
			installed = false;
			disposed = true;
		}
	}
}
public static class AdvancedSkinApplications
{
	private sealed class Registration : IDisposable
	{
		private SkinDef skin;

		private bool disposed;

		public Registration(SkinDef skin)
		{
			this.skin = skin;
		}

		public void Dispose()
		{
			if (!disposed)
			{
				bridge.Remove(skin);
				registrations--;
				if (registrations == 0)
				{
					bridge.Dispose();
					bridge = null;
				}
				skin = null;
				disposed = true;
			}
		}
	}

	private static AdvancedSkinApplicationBridge bridge;

	private static int registrations;

	public static IDisposable Register(SkinDef skin, Mesh mesh)
	{
		if (bridge == null)
		{
			bridge = new AdvancedSkinApplicationBridge();
		}
		try
		{
			bridge.Register(skin, mesh);
		}
		catch
		{
			if (registrations == 0)
			{
				bridge.Dispose();
				bridge = null;
			}
			throw;
		}
		registrations++;
		return new Registration(skin);
	}
}
public sealed class AdvancedSkinModel : MonoBehaviour
{
	[SerializeField]
	private SkinnedMeshRenderer target;

	[SerializeField]
	private Animator source;

	[SerializeField]
	private Mesh nativeMesh;

	[SerializeField]
	private Material[] nativeMaterials;

	[SerializeField]
	private Transform[] nativeBones;

	[SerializeField]
	private Transform nativeRoot;

	[SerializeField]
	private Bounds nativeBounds;

	[SerializeField]
	private bool nativeOffscreen;

	[SerializeField]
	private bool captured;

	[NonSerialized]
	private CharacterBody associatedBody;

	public CharacterBody AssociatedBody
	{
		get
		{
			if (!Object.op_Implicit((Object)(object)associatedBody) || !Object.op_Implicit((Object)(object)associatedBody.modelLocator) || !((Object)(object)associatedBody.modelLocator.modelTransform == (Object)(object)((Component)this).transform))
			{
				return null;
			}
			return associatedBody;
		}
	}

	public bool HasNativeSnapshot => captured;

	internal void BindBody(CharacterBody body)
	{
		if (!Object.op_Implicit((Object)(object)body) || !Object.op_Implicit((Object)(object)body.modelLocator) || (Object)(object)body.modelLocator.modelTransform != (Object)(object)((Component)this).transform)
		{
			throw new ArgumentException("Body does not own this model");
		}
		associatedBody = body;
	}

	private bool Owns(Transform value)
	{
		if (Object.op_Implicit((Object)(object)value))
		{
			if (!((Object)(object)value == (Object)(object)((Component)this).transform))
			{
				return value.IsChildOf(((Component)this).transform);
			}
			return true;
		}
		return false;
	}

	private void Validate()
	{
		if (!captured || !Object.op_Implicit((Object)(object)target) || !Object.op_Implicit((Object)(object)source) || !Object.op_Implicit((Object)(object)nativeMesh) || !Owns(((Component)target).transform) || !Owns(((Component)source).transform) || nativeBones == null || nativeBones.Length != nativeMesh.bindposes.Length || Array.Exists(nativeBones, (Transform b) => !Owns(b)) || (Object.op_Implicit((Object)(object)nativeRoot) && !Owns(nativeRoot)) || nativeMaterials == null || nativeMaterials.Length == 0 || Array.Exists(nativeMaterials, (Material m) => !Object.op_Implicit((Object)(object)m)))
		{
			throw new InvalidOperationException("Invalid or cross-instance native skin snapshot");
		}
	}

	public void CaptureNativeTemplate(SkinnedMeshRenderer renderer, Animator animator, Mesh fallback = null, Material[] fallbackMaterials = null)
	{
		//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		if (captured)
		{
			throw new InvalidOperationException("Native template already captured");
		}
		if (!Object.op_Implicit((Object)(object)renderer) || !Object.op_Implicit((Object)(object)animator) || (!Object.op_Implicit((Object)(object)renderer.sharedMesh) && !Object.op_Implicit((Object)(object)fallback)) || AdvancedSkinRegistry.TryGet(renderer.sharedMesh, out var _))
		{
			throw new ArgumentException("Capture the native template before advanced skin application");
		}
		target = renderer;
		source = animator;
		nativeMesh = (Object.op_Implicit((Object)(object)fallback) ? fallback : renderer.sharedMesh);
		nativeMaterials = fallbackMaterials ?? ((Renderer)renderer).sharedMaterials;
		nativeBones = renderer.bones;
		nativeRoot = renderer.rootBone;
		nativeBounds = ((Renderer)renderer).localBounds;
		nativeOffscreen = renderer.updateWhenOffscreen;
		captured = true;
		try
		{
			Validate();
		}
		catch
		{
			captured = false;
			throw;
		}
	}

	public SkinRigDriver Prepare()
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		Validate();
		SkinRigDriver skinRigDriver = ((Component)this).GetComponent<SkinRigDriver>();
		if (!Object.op_Implicit((Object)(object)skinRigDriver))
		{
			skinRigDriver = ((Component)this).gameObject.AddComponent<SkinRigDriver>();
		}
		if (!skinRigDriver.IsConfigured)
		{
			skinRigDriver.ConfigureSnapshot(target, nativeMesh, source, nativeBones, nativeRoot, nativeBounds, nativeOffscreen, nativeMaterials);
		}
		return skinRigDriver;
	}

	private void Awake()
	{
		if (captured)
		{
			try
			{
				Prepare();
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("ECLIPSE_NATIVE_SNAPSHOT_FAILED " + ex));
			}
		}
	}
}
public static class AirTransitionRoles
{
	public static bool Collect(IEnumerable<NativeMotionCandidate> chosen, bool[] exempt)
	{
		Array.Clear(exempt, 0, exempt.Length);
		bool result = false;
		foreach (NativeMotionCandidate item in chosen)
		{
			MotionLayer motion = item.Motion;
			WeightedMotion[] samples = motion.Samples;
			foreach (WeightedMotion weightedMotion in samples)
			{
				if (weightedMotion.Weight <= 0.001f)
				{
					continue;
				}
				Track[] tracks = weightedMotion.Clip.Tracks;
				foreach (Track track in tracks)
				{
					if (motion.BoneMask == null || Array.IndexOf(motion.BoneMask, track.Bone) >= 0)
					{
						if (motion.Group == "death")
						{
							result = true;
						}
						if (motion.Group == "attack" || motion.Group == "mouth")
						{
							exempt[track.Bone] = true;
						}
					}
				}
			}
		}
		return result;
	}
}
public sealed class GroundedLandingClock
{
	private bool initialized;

	private bool wasGrounded;

	private bool landing;

	private double last;

	private double started;

	private long serial;

	public long Serial => serial;

	public double Phase { get; private set; }

	public bool Observe(bool grounded, bool dead, double now, float duration)
	{
		if (!Limits.Finite(now) || !Limits.Finite(duration) || duration <= 0f)
		{
			throw new ArgumentException("Landing clock");
		}
		if (!initialized || now < last || now - last > 0.25)
		{
			initialized = true;
			wasGrounded = grounded;
			landing = false;
		}
		else if (!wasGrounded && grounded && !dead)
		{
			landing = true;
			started = now;
			serial++;
		}
		if (!grounded || dead)
		{
			landing = false;
		}
		wasGrounded = grounded;
		last = now;
		Phase = (landing ? Math.Max(0.0, (now - started) / (double)duration) : 0.0);
		if (Phase >= 1.0)
		{
			landing = false;
		}
		return landing;
	}
}
public sealed class AirPoseTransition
{
	private Pose[] previous;

	private Pose[] from;

	private bool[] bypass;

	private bool initialized;

	private bool air;

	private double lastTime;

	private double changedAt;

	private bool blending;

	private float blendAmount;

	public void BlendUnderlying(Pose[] pose)
	{
		if (!blending)
		{
			return;
		}
		for (int i = 0; i < pose.Length; i++)
		{
			if (!bypass[i])
			{
				pose[i] = Pose.Blend(from[i], pose[i], blendAmount);
			}
		}
	}

	public void Reset()
	{
		initialized = false;
		blending = false;
	}

	public void CaptureDisplayed(Pose[] pose)
	{
		if (initialized)
		{
			if (pose == null || pose.Length != previous.Length)
			{
				throw new ArgumentException("Displayed pose size");
			}
			Array.Copy(pose, previous, pose.Length);
		}
	}

	public void Apply(Pose[] pose, bool airborne, double now, float seconds, bool[] exempt = null)
	{
		if (pose == null || !Limits.Finite(now) || !Limits.Finite(seconds) || seconds <= 0f || (exempt != null && exempt.Length != pose.Length))
		{
			throw new ArgumentException("Air pose transition context");
		}
		if (!initialized || previous.Length != pose.Length || now < lastTime || now - lastTime > 0.25)
		{
			previous = (Pose[])pose.Clone();
			from = new Pose[pose.Length];
			bypass = new bool[pose.Length];
			initialized = true;
			air = airborne;
			blending = false;
		}
		else if (air != airborne)
		{
			Array.Copy(previous, from, pose.Length);
			Array.Clear(bypass, 0, bypass.Length);
			changedAt = now;
			air = airborne;
			blending = true;
		}
		if (blending)
		{
			float num = (float)Math.Max(0.0, Math.Min(1.0, (now - changedAt) / (double)seconds));
			num = (blendAmount = num * num * (3f - 2f * num));
			for (int i = 0; i < pose.Length; i++)
			{
				ref bool reference = ref bypass[i];
				reference |= exempt != null && exempt[i];
				if (!bypass[i])
				{
					pose[i] = Pose.Blend(from[i], pose[i], num);
				}
			}
			if (now - changedAt >= (double)seconds)
			{
				blending = false;
			}
		}
		Array.Copy(pose, previous, pose.Length);
		lastTime = now;
	}
}
internal static class AttachmentMatching
{
	internal static bool Valid(V3 p, Q4 q, V3 s)
	{
		if (Limits.Finite(p.X) && Limits.Finite(p.Y) && Limits.Finite(p.Z) && Limits.Finite(q.X) && Limits.Finite(q.Y) && Limits.Finite(q.Z) && Limits.Finite(q.W) && Math.Abs(q.Dot(q) - 1f) < 0.001f && Limits.Finite(s.X) && Limits.Finite(s.Y) && Limits.Finite(s.Z) && Math.Abs(s.X) > 1E-05f && Math.Abs(s.Y) > 1E-05f)
		{
			return Math.Abs(s.Z) > 1E-05f;
		}
		return false;
	}

	internal static bool ScaleMatches(V3 a, V3 b)
	{
		if (Math.Abs(a.X - b.X) <= Math.Abs(b.X) * 0.001f && Math.Abs(a.Y - b.Y) <= Math.Abs(b.Y) * 0.001f)
		{
			return Math.Abs(a.Z - b.Z) <= Math.Abs(b.Z) * 0.001f;
		}
		return false;
	}

	internal static int[] Unique(int[][] candidates)
	{
		return candidates.Select((int[] row) => (row.Length != 1 || candidates.Count((int[] other) => other.Contains(row[0])) != 1) ? (-1) : row[0]).ToArray();
	}
}
internal sealed class AuthorityOwnedTiming<T> : IDisposable where T : class, IDisposable
{
	private object owner;

	public T Current { get; private set; }

	public void Update(object motor, bool hasAuthority, Func<T> create)
	{
		if (!hasAuthority || motor == null || create == null)
		{
			Dispose();
			return;
		}
		if (owner != motor)
		{
			Dispose();
		}
		if (Current == null)
		{
			Current = create();
			owner = motor;
		}
	}

	public void Dispose()
	{
		T current = Current;
		Current = null;
		owner = null;
		current?.Dispose();
	}
}
internal static class CrocoModelActor
{
	public static CharacterBody Resolve(Component member)
	{
		if (!Object.op_Implicit((Object)(object)member))
		{
			return null;
		}
		CharacterModel componentInParent = member.GetComponentInParent<CharacterModel>();
		if (Object.op_Implicit((Object)(object)componentInParent) && Object.op_Implicit((Object)(object)componentInParent.body) && Object.op_Implicit((Object)(object)componentInParent.body.modelLocator) && (Object)(object)componentInParent.body.modelLocator.modelTransform == (Object)(object)((Component)componentInParent).transform)
		{
			return componentInParent.body;
		}
		AdvancedSkinModel componentInParent2 = member.GetComponentInParent<AdvancedSkinModel>();
		if (Object.op_Implicit((Object)(object)componentInParent2) && Object.op_Implicit((Object)(object)componentInParent2.AssociatedBody))
		{
			return componentInParent2.AssociatedBody;
		}
		return null;
	}
}
public sealed class CrocoModelMotionSource : ISkinMotionSource, IDisposable
{
	private readonly Animator animator;

	private readonly MotionBank bank;

	private CharacterBody actor;

	private CrocoStateMotionSource source;

	private bool disposed;

	private readonly bool observeLanding;

	public CrocoModelMotionSource(Animator animator, MotionBank bank)
		: this(animator, bank, observeLanding: false)
	{
	}

	public CrocoModelMotionSource(Animator animator, MotionBank bank, bool observeLanding)
	{
		if (!Object.op_Implicit((Object)(object)animator))
		{
			throw new ArgumentException("Missing model Animator");
		}
		CrocoStateMotionSource.ValidateBank(bank);
		this.animator = animator;
		this.bank = bank;
		this.observeLanding = observeLanding;
	}

	public void Observe(List<NativeMotionCandidate> candidates, HashSet<string> replaceNativeClips)
	{
		if (disposed)
		{
			return;
		}
		CharacterBody val = CrocoModelActor.Resolve((Component)(object)animator);
		if ((Object)(object)val != (Object)(object)actor)
		{
			source?.Dispose();
			source = null;
			actor = val;
		}
		if (!Object.op_Implicit((Object)(object)actor))
		{
			return;
		}
		if (source == null)
		{
			if (((Component)actor).GetComponents<EntityStateMachine>().Length == 0)
			{
				return;
			}
			source = new CrocoStateMotionSource(actor, bank, observeLanding);
		}
		source.Observe(candidates, replaceNativeClips);
	}

	public void Dispose()
	{
		if (!disposed)
		{
			disposed = true;
			source?.Dispose();
			source = null;
			actor = null;
		}
	}
}
public sealed class CrocoModelGaitTiming : ISkinMotionTiming, IDisposable, ISkinPresentationOffset
{
	private readonly SkinnedMeshRenderer renderer;

	private readonly MotionBank bank;

	private readonly GaitCalibration calibration;

	private CharacterBody actor;

	private CharacterMotor motor;

	private CrocoGaitTiming timing;

	private bool disposed;

	public Vector3 LocalPresentationOffset
	{
		get
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (disposed || timing == null)
			{
				return Vector3.zero;
			}
			return timing.LocalPresentationOffset;
		}
	}

	public bool Restarted
	{
		get
		{
			if (!disposed && timing != null)
			{
				return timing.Restarted;
			}
			return false;
		}
	}

	public void ResetPresentation()
	{
		timing?.ResetPresentation();
	}

	public CrocoModelGaitTiming(SkinnedMeshRenderer renderer, MotionBank bank, GaitCalibration calibration)
	{
		if (!Object.op_Implicit((Object)(object)renderer) || calibration == null)
		{
			throw new ArgumentException("Missing model gait context");
		}
		calibration.Validate(bank);
		this.renderer = renderer;
		this.bank = bank;
		this.calibration = calibration;
	}

	public void Retime(MotionLayer[] composed, IEnumerable<NativeMotionCandidate> observed)
	{
		if (disposed)
		{
			return;
		}
		CharacterBody val = CrocoModelActor.Resolve((Component)(object)renderer);
		CharacterMotor val2 = (Object.op_Implicit((Object)(object)val) ? val.characterMotor : null);
		if ((Object)(object)val != (Object)(object)actor || (Object)(object)val2 != (Object)(object)motor)
		{
			timing?.Dispose();
			timing = null;
			actor = val;
			motor = val2;
		}
		if (!Object.op_Implicit((Object)(object)actor) || !Object.op_Implicit((Object)(object)actor.characterMotor))
		{
			timing?.Dispose();
			timing = null;
			return;
		}
		if (timing == null)
		{
			timing = new CrocoGaitTiming(actor, ((Component)renderer).transform, bank, calibration);
		}
		timing.Retime(composed, observed);
	}

	public bool OwnsCues(MotionClip clip)
	{
		if (!disposed && timing != null)
		{
			return timing.OwnsCues(clip);
		}
		return false;
	}

	public void AdvanceCues(Action<string> emit)
	{
		if (!disposed)
		{
			timing?.AdvanceCues(emit);
		}
	}

	public void Dispose()
	{
		if (!disposed)
		{
			disposed = true;
			timing?.Dispose();
			timing = null;
			actor = null;
		}
	}
}
internal static class FabricSpring
{
	internal static void Limit(ref float x, ref float z, float maximum)
	{
		float num = (float)Math.Sqrt(x * x + z * z);
		if (num > maximum && num > 0f)
		{
			float num2 = maximum / num;
			x *= num2;
			z *= num2;
		}
	}

	internal static void Gravity(float x, float y, float z, float bendDegrees, float strength, out float lateral, out float foreAft)
	{
		float num = 180f / (float)Math.PI / bendDegrees * strength;
		lateral = (float)Math.Atan2(x, 0f - y) * num;
		foreAft = (float)Math.Atan2(0f - z, 0f - y) * num;
	}

	internal static void Step(ref float position, ref float speed, float target, float omega, float dt)
	{
		float num = position - target;
		float num2 = (speed + omega * num) * dt;
		float num3 = (float)Math.Exp((0f - omega) * dt);
		position = target + (num + num2) * num3;
		speed = (speed - omega * num2) * num3;
	}
}
public sealed class GaitCalibration
{
	public int ReferenceFoot;

	public readonly Dictionary<string, V3> TravelPerCycle = new Dictionary<string, V3>();

	public Cue[] ContactCues;

	public readonly Dictionary<string, Cue[]> ContactCuesByClip = new Dictionary<string, Cue[]>();

	public readonly Dictionary<string, float> CyclesPerWorldMetre = new Dictionary<string, float>();

	public double MaximumCyclesPerSecond = 12.0;

	public double Acceleration;

	public double RestartPhase = -1.0;

	public GaitPresentationSettings Presentation;

	public Cue[] ContactsFor(string clip)
	{
		if (!ContactCuesByClip.ContainsKey(clip))
		{
			return ContactCues;
		}
		return ContactCuesByClip[clip];
	}

	public string EffectiveContactClip(IEnumerable<MotionLayer> layers)
	{
		Dictionary<string, float> dictionary = new Dictionary<string, float>();
		foreach (MotionLayer item in layers.OrderBy((MotionLayer l) => l.Priority))
		{
			if (item.BoneMask != null && Array.IndexOf(item.BoneMask, ReferenceFoot) < 0)
			{
				continue;
			}
			WeightedMotion[] array = item.Samples.Where((WeightedMotion s) => s.Clip.Tracks.Any((Track t) => t.Bone == ReferenceFoot)).ToArray();
			if (array.Any((WeightedMotion s) => !Limits.Finite(s.Weight) || s.Weight < 0f))
			{
				throw new ArgumentException("Gait weight");
			}
			float num = array.Sum((WeightedMotion s) => s.Weight);
			if (num <= 0f || item.Blend != MotionBlend.Override)
			{
				continue;
			}
			float num2 = Math.Min(1f, num);
			string[] array2 = dictionary.Keys.ToArray();
			for (int num3 = 0; num3 < array2.Length; num3++)
			{
				dictionary[array2[num3]] *= 1f - num2;
			}
			WeightedMotion[] array3 = array;
			foreach (WeightedMotion weightedMotion in array3)
			{
				if (TravelPerCycle.ContainsKey(weightedMotion.Clip.Id))
				{
					dictionary.TryGetValue(weightedMotion.Clip.Id, out var value);
					dictionary[weightedMotion.Clip.Id] = value + weightedMotion.Weight * num2 / num;
				}
			}
		}
		return (from p in (from p in dictionary
				where p.Value > 0.001f
				orderby p.Value descending
				select p).ThenBy<KeyValuePair<string, float>, string>((KeyValuePair<string, float> p) => p.Key, StringComparer.Ordinal)
			select p.Key).FirstOrDefault();
	}

	public float EffectivePresentationWeight(IEnumerable<MotionLayer> layers)
	{
		if (Presentation == null)
		{
			return 0f;
		}
		float num = 0f;
		foreach (MotionLayer item in layers.OrderBy((MotionLayer l) => l.Priority))
		{
			if (item.BoneMask != null && Array.IndexOf(item.BoneMask, ReferenceFoot) < 0)
			{
				continue;
			}
			WeightedMotion[] source = item.Samples.Where((WeightedMotion s) => s.Clip.Tracks.Any((Track t) => t.Bone == ReferenceFoot)).ToArray();
			float num2 = source.Sum((WeightedMotion s) => s.Weight);
			if (!(num2 <= 0f) && item.Blend == MotionBlend.Override)
			{
				float num3 = Math.Min(1f, num2);
				float num4 = source.Where((WeightedMotion s) => Array.IndexOf(Presentation.Clips, s.Clip.Id) >= 0).Sum((WeightedMotion s) => s.Weight);
				num = num * (1f - num3) + num4 * (num3 / num2);
			}
		}
		return num;
	}

	public double EffectiveCadence(IEnumerable<MotionLayer> layers, double worldSpeed)
	{
		if (!Limits.Finite(worldSpeed) || worldSpeed < 0.0)
		{
			throw new ArgumentException("World gait speed");
		}
		double num = 0.0;
		foreach (MotionLayer item in layers.OrderBy((MotionLayer l) => l.Priority))
		{
			if (item.BoneMask != null && Array.IndexOf(item.BoneMask, ReferenceFoot) < 0)
			{
				continue;
			}
			float num2 = 0f;
			double num3 = 0.0;
			WeightedMotion[] samples = item.Samples;
			foreach (WeightedMotion weightedMotion in samples)
			{
				if (weightedMotion.Clip.Tracks.Any((Track t) => t.Bone == ReferenceFoot))
				{
					if (!Limits.Finite(weightedMotion.Weight) || weightedMotion.Weight < 0f)
					{
						throw new ArgumentException("Gait weight");
					}
					num2 += weightedMotion.Weight;
					if (CyclesPerWorldMetre.TryGetValue(weightedMotion.Clip.Id, out var value))
					{
						num3 += (double)value * worldSpeed * (double)weightedMotion.Weight;
					}
				}
			}
			if (!(num2 <= 0f))
			{
				double num5 = Math.Min(1f, num2);
				if (item.Blend == MotionBlend.Override)
				{
					num = num * (1.0 - num5) + num3 * (num5 / (double)num2);
				}
				else if (num3 != 0.0)
				{
					throw new ArgumentException("Additive gait cadence unsupported");
				}
			}
		}
		return num;
	}

	public void Validate(MotionBank bank)
	{
		if (RestartPhase != -1.0 && (!Limits.Finite(RestartPhase) || RestartPhase < 0.0 || RestartPhase >= 1.0))
		{
			throw new ArgumentException("Gait restart phase");
		}
		if (Presentation != null)
		{
			Presentation.Validate();
			string[] clips = Presentation.Clips;
			foreach (string key in clips)
			{
				if (!TravelPerCycle.ContainsKey(key))
				{
					throw new ArgumentException("Presentation gait clip");
				}
			}
		}
		if (bank == null || ReferenceFoot < 0 || ReferenceFoot >= bank.Bones.Length || TravelPerCycle.Count == 0 || ContactCuesByClip.Keys.Any((string k) => !TravelPerCycle.ContainsKey(k)))
		{
			throw new ArgumentException("Gait calibration");
		}
		if (!Limits.Finite(MaximumCyclesPerSecond) || MaximumCyclesPerSecond <= 0.0 || !Limits.Finite(Acceleration) || Acceleration < 0.0)
		{
			throw new ArgumentException("Gait cadence limits");
		}
		if (CyclesPerWorldMetre.Count > 0 && (CyclesPerWorldMetre.Count != TravelPerCycle.Count || CyclesPerWorldMetre.Any((KeyValuePair<string, float> p) => !TravelPerCycle.ContainsKey(p.Key) || !Limits.Finite(p.Value) || p.Value <= 0f)))
		{
			throw new ArgumentException("Complete visual gait calibration required");
		}
		foreach (KeyValuePair<string, V3> item in TravelPerCycle)
		{
			MotionClip motionClip = bank.Find(item.Key);
			V3 value = item.Value;
			Cue[] contacts = ContactsFor(item.Key);
			new GaitContactClock(contacts);
			if (!motionClip.Loop || !Limits.Finite(value.X) || !Limits.Finite(value.Y) || !Limits.Finite(value.Z) || value.X * value.X + value.Y * value.Y + value.Z * value.Z < 0.0001f)
			{
				throw new ArgumentException("Gait stride");
			}
			if (motionClip.Cues.Length != contacts.Length || motionClip.Cues.Where((Cue c, int num) => c.Phase != contacts[num].Phase || c.Sound != contacts[num].Sound).Any())
			{
				throw new ArgumentException("Gait contact schedule must match its authored clip");
			}
		}
	}

	public V3 EffectiveTravel(IEnumerable<MotionLayer> layers)
	{
		V3 v = default(V3);
		foreach (MotionLayer item in layers.OrderBy((MotionLayer l) => l.Priority))
		{
			if (item.BoneMask != null && Array.IndexOf(item.BoneMask, ReferenceFoot) < 0)
			{
				continue;
			}
			float num = 0f;
			V3 v2 = default(V3);
			WeightedMotion[] samples = item.Samples;
			foreach (WeightedMotion weightedMotion in samples)
			{
				if (weightedMotion.Clip.Tracks.Any((Track t) => t.Bone == ReferenceFoot))
				{
					if (!Limits.Finite(weightedMotion.Weight) || weightedMotion.Weight < 0f)
					{
						throw new ArgumentException("Gait weight");
					}
					num += weightedMotion.Weight;
					if (TravelPerCycle.TryGetValue(weightedMotion.Clip.Id, out var value))
					{
						v2 += value * weightedMotion.Weight;
					}
				}
			}
			if (!(num <= 0f))
			{
				float num3 = Math.Min(1f, num);
				if (item.Blend == MotionBlend.Override)
				{
					v = v * (1f - num3) + v2 * (num3 / num);
				}
				else if (v2.X != 0f || v2.Y != 0f || v2.Z != 0f)
				{
					throw new ArgumentException("Additive gait calibration unsupported");
				}
			}
		}
		return v;
	}
}
public sealed class GaitContactSet
{
	private readonly Dictionary<string, GaitContactClock> byClip = new Dictionary<string, GaitContactClock>();

	public GaitContactSet(GaitCalibration calibration)
	{
		List<Tuple<Cue[], GaitContactClock>> list = new List<Tuple<Cue[], GaitContactClock>>();
		foreach (string key in calibration.TravelPerCycle.Keys)
		{
			Cue[] cues = calibration.ContactsFor(key);
			Tuple<Cue[], GaitContactClock> tuple = list.FirstOrDefault((Tuple<Cue[], GaitContactClock> p) => p.Item1.Length == cues.Length && !p.Item1.Where((Cue c, int i) => c.Phase != cues[i].Phase || c.Sound != cues[i].Sound).Any());
			if (tuple == null)
			{
				tuple = Tuple.Create(cues, new GaitContactClock(cues));
				list.Add(tuple);
			}
			byClip.Add(key, tuple.Item2);
		}
	}

	public void Advance(string selected, double phase, bool audible, Action<string> emit)
	{
		GaitContactClock value = null;
		if (selected != null)
		{
			byClip.TryGetValue(selected, out value);
		}
		foreach (GaitContactClock item in byClip.Values.Distinct())
		{
			item.Advance(phase, audible && item == value, emit);
		}
	}
}
public sealed class GaitContactClock
{
	private readonly CueCursor cursor = new CueCursor();

	private readonly MotionClip schedule;

	public GaitContactClock(Cue[] cues)
	{
		if (cues == null || cues.Length == 0 || cues.Length > 128)
		{
			throw new ArgumentException("Contact cues");
		}
		float num = -1f;
		foreach (Cue cue in cues)
		{
			if (cue == null || !Limits.Finite(cue.Phase) || cue.Phase < 0f || cue.Phase >= 1f || cue.Phase < num || string.IsNullOrWhiteSpace(cue.Sound))
			{
				throw new ArgumentException("Contact cue schedule");
			}
			num = cue.Phase;
		}
		schedule = new MotionClip
		{
			Id = "gait_contacts",
			Loop = true,
			Cues = cues.Select((Cue c) => new Cue
			{
				Phase = c.Phase,
				Sound = c.Sound
			}).ToArray()
		};
	}

	public void Advance(double phase, bool audible, Action<string> emit)
	{
		cursor.Advance(schedule, "gait_contacts", phase, delegate(string id)
		{
			if (audible)
			{
				emit(id);
			}
		});
	}
}
public sealed class GaitCycleClock
{
	private bool initialized;

	private bool running;

	private double previous;

	public double MaximumCyclesPerSecond = 12.0;

	public double RestartPhase = -1.0;

	public double Phase { get; private set; } = 1.0;

	public double CyclesPerSecond { get; private set; }

	public double UnmatchedSpeed { get; private set; }

	public bool RateLimited { get; private set; }

	public bool Rephased { get; private set; }

	public void Reset()
	{
		initialized = (running = false);
		CyclesPerSecond = 0.0;
		Rephased = false;
	}

	private static double Dot(V3 a, V3 b)
	{
		return (double)a.X * (double)b.X + (double)a.Y * (double)b.Y + (double)a.Z * (double)b.Z;
	}

	public double AdvanceAtRate(double desiredRate, double now, bool grounded, double acceleration = 0.0)
	{
		if (!Limits.Finite(desiredRate) || desiredRate < 0.0 || !Limits.Finite(now) || !Limits.Finite(MaximumCyclesPerSecond) || MaximumCyclesPerSecond <= 0.0 || !Limits.Finite(acceleration) || acceleration < 0.0)
		{
			throw new ArgumentException("Visual gait clock input");
		}
		Rephased = false;
		double num = (initialized ? (now - previous) : 0.0);
		initialized = true;
		previous = now;
		RateLimited = desiredRate > MaximumCyclesPerSecond;
		UnmatchedSpeed = 0.0;
		if (!grounded || desiredRate == 0.0 || num < 0.0 || num > 0.25)
		{
			CyclesPerSecond = 0.0;
			running = false;
			return Phase;
		}
		double num2 = Math.Min(MaximumCyclesPerSecond, desiredRate);
		double cyclesPerSecond = CyclesPerSecond;
		if (!running && RestartPhase >= 0.0)
		{
			Phase = Math.Floor(Phase) + 1.0 + RestartPhase;
			Rephased = true;
		}
		running = true;
		CyclesPerSecond = ((acceleration == 0.0) ? num2 : Math.Max(cyclesPerSecond - acceleration * num, Math.Min(cyclesPerSecond + acceleration * num, num2)));
		Phase += num * ((acceleration == 0.0) ? num2 : ((cyclesPerSecond + CyclesPerSecond) * 0.5));
		return Phase;
	}

	public double Advance(V3 localVelocity, V3 travel, double now, bool grounded)
	{
		if (!Limits.Finite(now) || !Limits.Finite(Dot(localVelocity, localVelocity)) || !Limits.Finite(Dot(travel, travel)) || !Limits.Finite(MaximumCyclesPerSecond) || MaximumCyclesPerSecond <= 0.0)
		{
			throw new ArgumentException("Gait clock input");
		}
		double num = (initialized ? (now - previous) : 0.0);
		initialized = true;
		previous = now;
		CyclesPerSecond = 0.0;
		RateLimited = false;
		UnmatchedSpeed = Math.Sqrt(Dot(localVelocity, localVelocity));
		if (!grounded || num < 0.0 || num > 0.25)
		{
			return Phase;
		}
		double num2 = Dot(travel, travel);
		if (num2 < 0.0001)
		{
			return Phase;
		}
		double num3 = Math.Max(0.0, Dot(localVelocity, travel) / num2);
		CyclesPerSecond = Math.Min(MaximumCyclesPerSecond, num3);
		RateLimited = num3 > MaximumCyclesPerSecond;
		V3 v = localVelocity - travel * (float)CyclesPerSecond;
		UnmatchedSpeed = Math.Sqrt(Dot(v, v));
		Phase += num * CyclesPerSecond;
		return Phase;
	}
}
public sealed class GaitPresentationSettings
{
	public float MaximumLag = 0.05f;

	public float MaximumSpeed = 1f;

	public float ContactPhase = 0.82f;

	public float TakeoffPhase = 0.12f;

	public float RecoveryPhase = 0.38f;

	public string[] Clips = new string[2] { "run", "sprint" };

	public void Validate()
	{
		float[] array = new float[5] { MaximumLag, MaximumSpeed, ContactPhase, TakeoffPhase, RecoveryPhase };
		for (int i = 0; i < array.Length; i++)
		{
			if (!Limits.Finite(array[i]))
			{
				throw new ArgumentException("Presentation input");
			}
		}
		if (MaximumLag <= 0f || MaximumLag > 0.1f || MaximumSpeed <= 0f || ContactPhase <= RecoveryPhase || ContactPhase >= 1f || TakeoffPhase < 0f || RecoveryPhase <= TakeoffPhase || Clips == null || Clips.Length == 0)
		{
			throw new ArgumentException("Presentation bounds");
		}
	}

	private static double Smooth(double x)
	{
		x = Math.Max(0.0, Math.Min(1.0, x));
		return x * x * (3.0 - 2.0 * x);
	}

	public float LagAt(double phase)
	{
		double num = phase - Math.Floor(phase);
		if (num < (double)ContactPhase)
		{
			num += 1.0;
		}
		if (num <= (double)(1f + TakeoffPhase))
		{
			return (float)Smooth((num - (double)ContactPhase) / (double)(1f + TakeoffPhase - ContactPhase));
		}
		return (float)(1.0 - Smooth((num - 1.0 - (double)TakeoffPhase) / (double)(RecoveryPhase - TakeoffPhase)));
	}
}
public sealed class GaitPresentationOffset
{
	private readonly GaitPresentationSettings settings;

	private bool initialized;

	private double previous;

	private V3 position;

	private V3 lastPosition;

	public V3 Offset => position;

	private static float Length(V3 v)
	{
		return (float)Math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z);
	}

	private static V3 Clamp(V3 v, float max)
	{
		float num = Length(v);
		if (!(num > max))
		{
			return v;
		}
		return v * (max / num);
	}

	public GaitPresentationOffset(GaitPresentationSettings settings)
	{
		settings.Validate();
		this.settings = settings;
	}

	public void Reset()
	{
		initialized = false;
		position = default(V3);
	}

	public V3 Advance(double now, double phase, V3 actorPosition, V3 travelVelocity, float weight, bool eligible)
	{
		if (!Limits.Finite(now) || !Limits.Finite(phase) || !Limits.Finite(Length(actorPosition)) || !Limits.Finite(Length(travelVelocity)) || !Limits.Finite(weight))
		{
			Reset();
			return position;
		}
		double num = (initialized ? (now - previous) : 0.0);
		bool num2 = initialized && (num < 0.0 || num > 0.25 || Length(actorPosition - lastPosition) > Math.Max(2f, Length(travelVelocity) * (float)Math.Max(0.0, num) * 3f + 0.5f));
		previous = now;
		lastPosition = actorPosition;
		initialized = true;
		if (num2)
		{
			position = default(V3);
			return position;
		}
		V3 v = default(V3);
		float num3 = Length(travelVelocity);
		if (eligible && num3 > 0.05f)
		{
			v = travelVelocity * ((0f - settings.MaximumLag) * settings.LagAt(phase) * Math.Max(0f, Math.Min(1f, weight)) / num3);
		}
		int num4 = Math.Max(1, (int)Math.Ceiling(num / 0.004));
		float num5 = (float)(num / (double)num4);
		for (int i = 0; i < num4; i++)
		{
			position += Clamp((v - position) * (float)(1.0 - Math.Exp(-65f * num5)), settings.MaximumSpeed * num5);
		}
		if (Length(v) == 0f && Length(position) < 1E-05f)
		{
			position = default(V3);
		}
		return position;
	}
}
public interface ISkinPoseConstraint
{
	void Apply(MotionLayer[] layers, Pose[] pose, bool grounded);
}
public interface ITransitionAwareSkinPoseConstraint : ISkinPoseConstraint
{
	void ApplyWithTransition(MotionLayer[] layers, Pose[] pose, bool grounded, Action<Pose[]> blendUnderlying);
}
public sealed class GroundedAimConstraint : ITransitionAwareSkinPoseConstraint, ISkinPoseConstraint
{
	private readonly MotionBank bank;

	private readonly PoseMixer mixer;

	private readonly Pose[] baseline;

	private readonly HashSet<string> aims;

	private readonly HashSet<string> terminal;

	private readonly int body;

	private readonly int[][] limbs;

	private readonly V3[] floor;

	private readonly float clearance;

	public float AppliedAimFraction { get; private set; } = 1f;

	public bool UsedUnderlyingFallback { get; private set; }

	public GroundedAimConstraint(MotionBank bank, string fallback, string[] aimClips, int body, int[][] limbs, V3[] bodySurface, float clearance, string[] terminalClips = null)
	{
		if (bank == null || body < 0 || body >= bank.Bones.Length || limbs == null || limbs.Length == 0 || limbs.Length > 8 || bodySurface == null || bodySurface.Length > 65536 || !Limits.Finite(clearance))
		{
			throw new ArgumentException("Aim constraint context");
		}
		this.bank = bank;
		this.body = body;
		this.clearance = clearance;
		this.limbs = limbs.Select((int[] x) => (int[])x.Clone()).ToArray();
		floor = bodySurface.Distinct().ToArray();
		aims = new HashSet<string>(aimClips);
		if (aims.Count == 0)
		{
			throw new ArgumentException("Aim clips");
		}
		foreach (string aim in aims)
		{
			bank.Find(aim);
		}
		terminal = new HashSet<string>((from b in bank.Bindings
			where b.Group == "death"
			select b.Clip).Concat(terminalClips ?? new string[0]));
		foreach (string item in terminal)
		{
			bank.Find(item);
		}
		int[][] array = this.limbs;
		foreach (int[] array2 in array)
		{
			if (array2.Length != 3 || array2.Any((int i) => i < 0 || i >= bank.Bones.Length) || bank.Bones[array2[1]].Parent != array2[0] || bank.Bones[array2[2]].Parent != array2[1] || Length(bank.Bones[array2[1]].Rest.Position) < 0.0001f || Length(bank.Bones[array2[2]].Rest.Position) < 0.0001f)
			{
				throw new ArgumentException("Two-segment aim limb");
			}
		}
		Bone[] bones = bank.Bones;
		for (int num = 0; num < bones.Length; num++)
		{
			if (Length(bones[num].Rest.Scale - new V3(1f, 1f, 1f)) > 1E-05f)
			{
				throw new ArgumentException("Aim constraint requires unit-scale skeleton");
			}
		}
		if (floor.Any((V3 v) => !Limits.Finite(v.X) || !Limits.Finite(v.Y) || !Limits.Finite(v.Z)))
		{
			throw new ArgumentException("Aim floor surface");
		}
		mixer = new PoseMixer(bank, fallback);
		baseline = new Pose[bank.Bones.Length];
	}

	private static float Dot(V3 a, V3 b)
	{
		return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
	}

	private static float Length(V3 v)
	{
		return (float)Math.Sqrt(Dot(v, v));
	}

	private static V3 Cross(V3 a, V3 b)
	{
		return new V3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X);
	}

	private static V3 Unit(V3 v)
	{
		float num = Length(v);
		if (!(num < 1E-08f))
		{
			return v * (1f / num);
		}
		return new V3(1f, 0f, 0f);
	}

	private static V3 Rotate(Q4 q, V3 v)
	{
		Q4 q2 = q * new Q4(v.X, v.Y, v.Z, 0f) * q.Inverse;
		return new V3(q2.X, q2.Y, q2.Z);
	}

	private static Q4 FromTo(V3 a, V3 b)
	{
		a = Unit(a);
		b = Unit(b);
		float num = Dot(a, b);
		if (num < -0.99999f)
		{
			V3 v = Unit(Cross(a, ((double)Math.Abs(a.X) < 0.8) ? new V3(1f, 0f, 0f) : new V3(0f, 1f, 0f)));
			return new Q4(v.X, v.Y, v.Z, 0f);
		}
		V3 v2 = Cross(a, b);
		return new Q4(v2.X, v2.Y, v2.Z, 1f + num).Normalized();
	}

	private Pose World(Pose[] p, int i)
	{
		Pose result = p[i];
		int parent = bank.Bones[i].Parent;
		if (parent < 0)
		{
			return result;
		}
		Pose pose = World(p, parent);
		return new Pose(pose.Position + Rotate(pose.Rotation, result.Position), (pose.Rotation * result.Rotation).Normalized(), new V3(1f, 1f, 1f));
	}

	private void Floor(Pose[] p)
	{
		Pose pose = World(p, body);
		V3 a = Rotate(pose.Rotation.Inverse, new V3(0f, 0f, 1f));
		float num = float.PositiveInfinity;
		V3[] array = floor;
		foreach (V3 b in array)
		{
			num = Math.Min(num, pose.Position.Z + Dot(a, b));
		}
		float num2 = Math.Max(0f, clearance - num);
		if (num2 > 0f)
		{
			int parent = bank.Bones[body].Parent;
			Q4 q = ((parent < 0) ? Q4.Identity : World(p, parent).Rotation);
			p[body].Position += Rotate(q.Inverse, new V3(0f, 0f, num2));
		}
	}

	private bool Reachable(Pose[] p, Pose[] targets)
	{
		for (int i = 0; i < limbs.Length; i++)
		{
			int[] array = limbs[i];
			float num = Length(targets[i].Position - World(p, array[0]).Position);
			float num2 = Length(p[array[1]].Position);
			float num3 = Length(p[array[2]].Position);
			if (num > num2 + num3 + 0.0002f || num < Math.Abs(num2 - num3) - 0.0002f)
			{
				return false;
			}
		}
		return true;
	}

	private void Solve(Pose[] p, int[] c, Pose target)
	{
		Pose pose = World(p, c[0]);
		Pose pose2 = World(p, c[1]);
		World(p, c[2]);
		V3 v = target.Position - pose.Position;
		float num = Length(p[c[1]].Position);
		float num2 = Length(p[c[2]].Position);
		float val = Length(v);
		V3 v2 = Unit(v);
		float num3 = Math.Max(Math.Abs(num - num2) + 1E-05f, Math.Min(num + num2 - 1E-05f, val));
		V3 v3 = pose2.Position - pose.Position;
		v3 -= v2 * Dot(v3, v2);
		if (Length(v3) < 0.0001f)
		{
			v3 = Cross(v2, ((double)Math.Abs(v2.Z) < 0.8) ? new V3(0f, 0f, 1f) : new V3(0f, 1f, 0f));
		}
		v3 = Unit(v3);
		float num4 = (num * num + num3 * num3 - num2 * num2) / (2f * num3);
		V3 v4 = pose.Position + v2 * num4 + v3 * (float)Math.Sqrt(Math.Max(0f, num * num - num4 * num4));
		V3 v5 = pose.Position + v2 * num3;
		Q4 q = (FromTo(Rotate(pose.Rotation, p[c[1]].Position), v4 - pose.Position) * pose.Rotation).Normalized();
		Q4 q2 = (FromTo(Rotate(pose2.Rotation, p[c[2]].Position), v5 - v4) * pose2.Rotation).Normalized();
		int parent = bank.Bones[c[0]].Parent;
		Q4 q3 = ((parent < 0) ? Q4.Identity : World(p, parent).Rotation);
		p[c[0]].Rotation = (q3.Inverse * q).Normalized();
		p[c[1]].Rotation = (q.Inverse * q2).Normalized();
		p[c[2]].Rotation = (q2.Inverse * target.Rotation).Normalized();
	}

	public void Apply(MotionLayer[] layers, Pose[] pose, bool grounded)
	{
		ApplyWithTransition(layers, pose, grounded, null);
	}

	public void ApplyWithTransition(MotionLayer[] layers, Pose[] pose, bool grounded, Action<Pose[]> blendUnderlying)
	{
		AppliedAimFraction = 1f;
		UsedUnderlyingFallback = false;
		if (!grounded || layers.Any((MotionLayer l) => l.Samples.Any((WeightedMotion s) => s.Weight > 0.001f && terminal.Contains(s.Clip.Id))) || !layers.Any((MotionLayer l) => l.Samples.Any((WeightedMotion s) => s.Weight > 0f && aims.Contains(s.Clip.Id))))
		{
			return;
		}
		MotionLayer[] layers2 = layers.Select((MotionLayer l) => new MotionLayer
		{
			Group = l.Group,
			Priority = l.Priority,
			Blend = l.Blend,
			BoneMask = l.BoneMask,
			Samples = l.Samples.Where((WeightedMotion s) => !aims.Contains(s.Clip.Id)).ToArray()
		}).ToArray();
		mixer.Evaluate(layers2, baseline);
		blendUnderlying?.Invoke(baseline);
		int[][] array = limbs;
		foreach (int[] array2 in array)
		{
			foreach (int num3 in array2)
			{
				if (Length(pose[num3].Scale - new V3(1f, 1f, 1f)) > 1E-05f)
				{
					throw new ArgumentException("Aim limb scale animation unsupported");
				}
			}
		}
		for (int parent = body; parent >= 0; parent = bank.Bones[parent].Parent)
		{
			if (Length(pose[parent].Scale - new V3(1f, 1f, 1f)) > 1E-05f)
			{
				throw new ArgumentException("Aim body scale animation unsupported");
			}
		}
		Pose[] array3 = limbs.Select((int[] c) => World(baseline, c[2])).ToArray();
		Pose b = pose[body];
		for (int num4 = 0; num4 <= 12; num4++)
		{
			AppliedAimFraction = ((num4 == 12) ? 0f : ((float)Math.Pow(0.5, num4)));
			pose[body] = Pose.Blend(baseline[body], b, AppliedAimFraction);
			Floor(pose);
			if (Reachable(pose, array3))
			{
				break;
			}
		}
		if (!Reachable(pose, array3))
		{
			Array.Copy(baseline, pose, pose.Length);
			AppliedAimFraction = 0f;
			UsedUnderlyingFallback = true;
			return;
		}
		if (AppliedAimFraction < 1f)
		{
			float num5 = AppliedAimFraction;
			float num6 = ((num5 == 0f) ? 0.00048828125f : (num5 * 2f));
			for (int num7 = 0; num7 < 10; num7++)
			{
				float num8 = (num5 + num6) * 0.5f;
				pose[body] = Pose.Blend(baseline[body], b, num8);
				Floor(pose);
				if (Reachable(pose, array3))
				{
					num5 = num8;
				}
				else
				{
					num6 = num8;
				}
			}
			AppliedAimFraction = num5;
			pose[body] = Pose.Blend(baseline[body], b, num5);
			Floor(pose);
		}
		for (int num9 = 0; num9 < limbs.Length; num9++)
		{
			Solve(pose, limbs[num9], array3[num9]);
		}
	}
}
[Serializable]
public sealed class NativeClothRegion
{
	public string id;

	public string driveBone;

	public float gravity;

	public Vector3 anchor;

	public int[] vertices;

	public float[] weights;

	public float bendDegrees = 20f;

	public float frequency = 2.8f;

	public float flutter = 0.04f;

	public float maxSwing = 0.65f;

	public float backLimit = 0.65f;
}
[Serializable]
public sealed class NativeClothDefinition
{
	public int schema = 1;

	public int vertexCount;

	public NativeClothRegion[] regions;
}
public sealed class NativeClothMotion : IDisposable
{
	private sealed class Region
	{
		public int first;

		public NativeClothRegion definition;

		public float x;

		public float z;

		public float vx;

		public float vz;

		public Transform drive;

		public Matrix4x4 inverseBind;
	}

	private readonly SkinnedMeshRenderer target;

	private readonly Mesh original;

	private readonly Bounds originalBounds;

	private readonly float[] originalBlendWeights;

	private Mesh owned;

	private readonly List<Region> regions = new List<Region>();

	private Vector3 previous;

	private Vector3 velocity;

	private Quaternion previousRotation;

	private float age;

	private bool disposed;

	public NativeClothMotion(SkinnedMeshRenderer renderer, NativeClothDefinition definition)
	{
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0088: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_05bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_05cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_05d4: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_05ea: Unknown result type (might be due to invalid IL or missing references)
		//IL_0448: Unknown result type (might be due to invalid IL or missing references)
		//IL_044d: Unknown result type (might be due to invalid IL or missing references)
		//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_04df: Unknown result type (might be due to invalid IL or missing references)
		//IL_04e4: Unknown result type (might be due to invalid IL or missing references)
		//IL_04e9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ee: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fb: Unknown result type (might be due to invalid IL or missing references)
		//IL_0500: Unknown result type (might be due to invalid IL or missing references)
		//IL_0509: Unknown result type (might be due to invalid IL or missing references)
		//IL_050e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0513: Unknown result type (might be due to invalid IL or missing references)
		//IL_051b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0520: Unknown result type (might be due to invalid IL or missing references)
		//IL_0525: Unknown result type (might be due to invalid IL or missing references)
		if (!Object.op_Implicit((Object)(object)renderer) || !Object.op_Implicit((Object)(object)renderer.sharedMesh) || definition == null || definition.schema != 1 || definition.vertexCount != renderer.sharedMesh.vertexCount || definition.regions == null || definition.regions.Length < 1 || definition.regions.Length > 8)
		{
			throw new ArgumentException("Invalid authored cloth contract");
		}
		target = renderer;
		original = renderer.sharedMesh;
		originalBounds = ((Renderer)renderer).localBounds;
		originalBlendWeights = new float[original.blendShapeCount];
		for (int i = 0; i < originalBlendWeights.Length; i++)
		{
			originalBlendWeights[i] = renderer.GetBlendShapeWeight(i);
		}
		owned = Object.Instantiate<Mesh>(original);
		((Object)owned).name = ((Object)original).name + "_OwnedFabric";
		try
		{
			Vector3[] vertices = original.vertices;
			Vector3[] normals = original.normals;
			if (normals.Length != vertices.Length)
			{
				throw new ArgumentException("Cloth normals missing");
			}
			HashSet<string> hashSet = new HashSet<string>();
			HashSet<int> hashSet2 = new HashSet<int>();
			NativeClothRegion[] array = definition.regions;
			foreach (NativeClothRegion nativeClothRegion in array)
			{
				if (nativeClothRegion == null || string.IsNullOrEmpty(nativeClothRegion.id) || !hashSet.Add(nativeClothRegion.id) || nativeClothRegion.vertices == null || nativeClothRegion.weights == null || nativeClothRegion.vertices.Length != nativeClothRegion.weights.Length || nativeClothRegion.vertices.Length < 1 || nativeClothRegion.bendDegrees < 1f || nativeClothRegion.bendDegrees > 60f || nativeClothRegion.frequency < 1f || nativeClothRegion.frequency > 8f || nativeClothRegion.flutter < 0f || nativeClothRegion.flutter > 0.12f || nativeClothRegion.maxSwing < 0f || nativeClothRegion.maxSwing > 0.8f || nativeClothRegion.backLimit < 0f || nativeClothRegion.backLimit > 0.8f || nativeClothRegion.gravity < 0f || nativeClothRegion.gravity > 1f)
				{
					throw new ArgumentException("Invalid cloth region");
				}
				float[] array2 = new float[9]
				{
					nativeClothRegion.anchor.x,
					nativeClothRegion.anchor.y,
					nativeClothRegion.anchor.z,
					nativeClothRegion.bendDegrees,
					nativeClothRegion.frequency,
					nativeClothRegion.flutter,
					nativeClothRegion.maxSwing,
					nativeClothRegion.backLimit,
					nativeClothRegion.gravity
				};
				foreach (float f in array2)
				{
					if (float.IsNaN(f) || float.IsInfinity(f))
					{
						throw new ArgumentException("Non-finite cloth property");
					}
				}
				for (int l = 0; l < nativeClothRegion.vertices.Length; l++)
				{
					int num = nativeClothRegion.vertices[l];
					float num2 = nativeClothRegion.weights[l];
					if (num < 0 || num >= vertices.Length || !hashSet2.Add(num) || float.IsNaN(num2) || float.IsInfinity(num2) || num2 < 0f || num2 > 1f)
					{
						throw new ArgumentException("Invalid or overlapping cloth vertex mask");
					}
				}
				Region region = new Region
				{
					first = owned.blendShapeCount,
					definition = nativeClothRegion
				};
				if (nativeClothRegion.gravity > 0f)
				{
					int num3 = -1;
					Transform[] bones = renderer.bones;
					for (int m = 0; m < bones.Length; m++)
					{
						if (Object.op_Implicit((Object)(object)bones[m]) && ((Object)bones[m]).name == nativeClothRegion.driveBone)
						{
							if (num3 >= 0)
							{
								throw new ArgumentException("Ambiguous cloth driving bone");
							}
							num3 = m;
						}
					}
					if (num3 < 0 || num3 >= original.bindposes.Length)
					{
						throw new ArgumentException("Cloth driving bone missing");
					}
					region.drive = bones[num3];
					region.inverseBind = original.bindposes[num3];
				}
				regions.Add(region);
				for (int n = 0; n < 4; n++)
				{
					Vector3[] array3 = (Vector3[])(object)new Vector3[vertices.Length];
					Vector3[] array4 = (Vector3[])(object)new Vector3[vertices.Length];
					for (int num4 = 0; num4 < nativeClothRegion.vertices.Length; num4++)
					{
						int num5 = nativeClothRegion.vertices[num4];
						float num6 = nativeClothRegion.bendDegrees * nativeClothRegion.weights[num4];
						Quaternion val = Quaternion.AngleAxis((n % 2 == 0) ? num6 : (0f - num6), (n < 2) ? Vector3.forward : Vector3.right);
						array3[num5] = nativeClothRegion.anchor + val * (vertices[num5] - nativeClothRegion.anchor) - vertices[num5];
						array4[num5] = val * normals[num5] - normals[num5];
					}
					owned.AddBlendShapeFrame("EclipseFabric_" + nativeClothRegion.id + "_" + n, 100f, array3, array4, (Vector3[])null);
				}
			}
			target.sharedMesh = owned;
			Bounds localBounds = originalBounds;
			((Bounds)(ref localBounds)).Expand(1f);
			((Renderer)target).localBounds = localBounds;
			previous = ((Component)target).transform.position;
			previousRotation = ((Component)target).transform.rotation;
		}
		catch
		{
			if (Object.op_Implicit((Object)(object)owned))
			{
				Object.Destroy((Object)(object)owned);
			}
			owned = null;
			throw;
		}
	}

	public void Update(float dt)
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_0075: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: 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_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_0148: 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_015a: Unknown result type (might be due to invalid IL or missing references)
		//IL_015d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: 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_0189: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Unknown result type (might be due to invalid IL or missing references)
		//IL_0215: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_02be: Unknown result type (might be due to invalid IL or missing references)
		//IL_02c5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d3: Unknown result type (might be due to invalid IL or missing references)
		//IL_02d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_02f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0301: Unknown result type (might be due to invalid IL or missing references)
		//IL_0308: Unknown result type (might be due to invalid IL or missing references)
		//IL_030f: Unknown result type (might be due to invalid IL or missing references)
		if (disposed)
		{
			return;
		}
		if (!Object.op_Implicit((Object)(object)target) || (Object)(object)target.sharedMesh != (Object)(object)owned)
		{
			Dispose();
		}
		else
		{
			if (dt <= 0f)
			{
				return;
			}
			Vector3 position = ((Component)target).transform.position;
			Vector3 val = position - previous;
			previous = position;
			Quaternion rotation = ((Component)target).transform.rotation;
			float num = Quaternion.Angle(previousRotation, rotation);
			previousRotation = rotation;
			if (dt > 0.2f || ((Vector3)(ref val)).sqrMagnitude > 25f)
			{
				velocity = Vector3.zero;
				{
					foreach (Region region2 in regions)
					{
						region2.x = (region2.z = (region2.vx = (region2.vz = 0f)));
						for (int i = 0; i < 4; i++)
						{
							target.SetBlendShapeWeight(region2.first + i, 0f);
						}
					}
					return;
				}
			}
			age += dt;
			Vector3 val2 = val / dt;
			Vector3 val3 = ((Component)target).transform.InverseTransformDirection((val2 - velocity) / dt);
			Vector3 val4 = ((Component)target).transform.InverseTransformDirection(val2);
			velocity = val2;
			for (int j = 0; j < regions.Count; j++)
			{
				Region region = regions[j];
				float num2 = Mathf.Sin(age * region.definition.frequency + (float)j * 1.7f) * region.definition.flutter;
				float num3 = Mathf.Clamp((0f - val3.x) * 0.012f - val4.x * 0.025f, -0.65f, 0.65f) + num2;
				float num4 = Mathf.Clamp(val3.z * 0.012f + val4.z * 0.025f, -0.65f, 0.65f) + Mathf.Sin(age * region.definition.frequency * 0.81f + (float)j) * region.definition.flutter + Mathf.Clamp(num * 0.005f, 0f, 0.12f);
				if (Object.op_Implicit((Object)(object)region.drive) && region.definition.gravity > 0f)
				{
					Matrix4x4 val5 = ((Component)target).transform.worldToLocalMatrix * region.drive.localToWorldMatrix * region.inverseBind;
					Matrix4x4 inverse = ((Matrix4x4)(ref val5)).inverse;
					Vector3 val6 = ((Matrix4x4)(ref inverse)).MultiplyVector(((Component)target).transform.InverseTransformDirection(Vector3.down));
					Vector3 normalized = ((Vector3)(ref val6)).normalized;
					FabricSpring.Gravity(normalized.x, normalized.y, normalized.z, region.definition.bendDegrees, region.definition.gravity, out var lateral, out var foreAft);
					num3 += lateral;
					num4 += foreAft;
				}
				num3 = Mathf.Clamp(num3, 0f - region.definition.maxSwing, region.definition.maxSwing);
				num4 = Mathf.Clamp(num4, 0f - region.definition.maxSwing, region.definition.backLimit);
				if (region.definition.gravity > 0f)
				{
					FabricSpring.Limit(ref num3, ref num4, region.definition.maxSwing);
				}
				FabricSpring.Step(ref region.x, ref region.vx, num3, region.definition.frequency * 2f * (float)Math.PI, dt);
				FabricSpring.Step(ref region.z, ref region.vz, num4, region.definition.frequency * 2f * (float)Math.PI, dt);
				target.SetBlendShapeWeight(region.first, Mathf.Max(0f, region.x) * 100f);
				target.SetBlendShapeWeight(region.first + 1, Mathf.Max(0f, 0f - region.x) * 100f);
				target.SetBlendShapeWeight(region.first + 2, Mathf.Max(0f, region.z) * 100f);
				target.SetBlendShapeWeight(region.first + 3, Mathf.Max(0f, 0f - region.z) * 100f);
			}
		}
	}

	public void Dispose()
	{
		//IL_0077: Unknown result type (might be due to invalid IL or missing references)
		if (disposed)
		{
			return;
		}
		disposed = true;
		if (Object.op_Implicit((Object)(object)target) && (Object)(object)target.sharedMesh == (Object)(object)owned)
		{
			for (int i = 0; i < owned.blendShapeCount; i++)
			{
				target.SetBlendShapeWeight(i, 0f);
			}
			target.sharedMesh = original;
			((Renderer)target).localBounds = originalBounds;
			for (int j = 0; j < originalBlendWeights.Length; j++)
			{
				target.SetBlendShapeWeight(j, originalBlendWeights[j]);
			}
		}
		if (Object.op_Implicit((Object)(object)owned))
		{
			Object.Destroy((Object)(object)owned);
		}
		owned = null;
		regions.Clear();
	}
}
internal static class NativeItemDisplayOrigins
{
	internal sealed class Origin
	{
		internal Transform Parent;

		internal Vector3 Position;

		internal Vector3 Scale;

		internal Quaternion Rotation;
	}

	private static readonly ConditionalWeakTable<Transform, Origin> origins = new ConditionalWeakTable<Transform, Origin>();

	internal static bool TryGet(Transform display, out Origin origin)
	{
		return origins.TryGetValue(display, out origin);
	}

	internal static void Install()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		CharacterModel.InstantiateDisplayRuleGroup += new hook_InstantiateDisplayRuleGroup(Observe);
	}

	internal static void Remove()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		CharacterModel.InstantiateDisplayRuleGroup -= new hook_InstantiateDisplayRuleGroup(Observe);
	}

	private static List<GameObject> Objects(CharacterModel model, ItemIndex item, EquipmentIndex equipment)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0002: Invalid comparison between Unknown and I4
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0004: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		if ((int)item == -1)
		{
			if ((int)equipment == -1)
			{
				return null;
			}
			return model.GetEquipmentDisplayObjects(equipment);
		}
		return model.GetItemDisplayObjects(item);
	}

	private static void Observe(orig_InstantiateDisplayRuleGroup orig, CharacterModel self, DisplayRuleGroup rules, ItemIndex item, EquipmentIndex equipment, KeyItemIndex key)
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		//IL_0054: 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_0018: 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_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c9: 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_00d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_00db: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		HashSet<GameObject> hashSet = null;
		if (Object.op_Implicit((Object)(object)self) && Object.op_Implicit((Object)(object)((Component)self).GetComponent<AdvancedSkinModel>()))
		{
			try
			{
				hashSet = new HashSet<GameObject>(Objects(self, item, equipment) ?? new List<GameObject>());
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("ECLIPSE_ATTACHMENT_OBSERVER_UNAVAILABLE " + ex));
			}
		}
		orig.Invoke(self, rules, item, equipment, key);
		if (hashSet == null)
		{
			return;
		}
		try
		{
			foreach (GameObject item2 in Objects(self, item, equipment) ?? new List<GameObject>())
			{
				if (Object.op_Implicit((Object)(object)item2) && !hashSet.Contains(item2))
				{
					Transform transform = item2.transform;
					if (!origins.TryGetValue(transform, out var _))
					{
						origins.Add(transform, new Origin
						{
							Parent = transform.parent,
							Position = transform.localPosition,
							Rotation = transform.localRotation,
							Scale = transform.localScale
						});
					}
				}
			}
		}
		catch (Exception ex2)
		{
			Debug.LogWarning((object)("ECLIPSE_ATTACHMENT_OBSERVATION_FAILED " + ex2));
		}
	}
}
internal sealed class NativeRazorwireBinding : IDisposable
{
	private readonly SkinnedMeshRenderer renderer;

	private readonly Transform display;

	private readonly Transform owner;

	private readonly Transform originalRoot;

	private readonly Transform[] original;

	private readonly Transform[] bones;

	private readonly Transform[] targets = (Transform[])(object)new Transform[3];

	private readonly float[] lengths;

	private readonly Vector3[] radial = (Vector3[])(object)new Vector3[3];

	private readonly bool offscreen;

	private bool installed;

	private bool disposed;

	public bool Alive
	{
		get
		{
			if (!disposed && installed && Object.op_Implicit((Object)(object)renderer) && Object.op_Implicit((Object)(object)display) && Object.op_Implicit((Object)(object)owner) && display.IsChildOf(owner) && targets.All((Transform t) => Object.op_Implicit((Object)(object)t)))
			{
				return Same(renderer.bones, targets);
			}
			return false;
		}
	}

	private static bool Finite(float f)
	{
		if (!float.IsNaN(f))
		{
			return !float.IsInfinity(f);
		}
		return false;
	}

	private static bool UniformPositive(Vector3 s)
	{
		//IL_0000: 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_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Unknown result type (might be due to invalid IL or missing references)
		if (Finite(s.x) && Finite(s.y) && Finite(s.z) && s.x > 1E-05f && Mathf.Abs(s.x - s.y) < 0.0001f)
		{
			return Mathf.Abs(s.x - s.z) < 0.0001f;
		}
		return false;
	}

	private static bool Same(Transform[] a, Transform[] b)
	{
		if (a != null && b != null && a.Length == b.Length)
		{
			return a.SequenceEqual(b);
		}
		return false;
	}

	public static NativeRazorwireBinding TryCreate(Transform display, Transform owner, Func<string, Transform> anchor, SkinItemAttachmentRule rule)
	{
		//IL_01a7: 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_01bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_01cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d0: 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_028d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02a7: Unknown result type (might be due to invalid IL or missing references)
		LimbMatcher[] componentsInChildren = ((Component)display).GetComponentsInChildren<LimbMatcher>(true);
		SkinnedMeshRenderer[] componentsInChildren2 = ((Component)display).GetComponentsInChildren<SkinnedMeshRenderer>(true);
		if (componentsInChildren.Length != 1 || (Object)(object)((Component)componentsInChildren[0]).transform != (Object)(object)display || componentsInChildren2.Length != 1)
		{
			return null;
		}
		LimbMatcher val = componentsInChildren[0];
		LimbPair[] p = val.limbPairs;
		SkinnedMeshRenderer val2 = componentsInChildren2[0];
		string[] children = new string[3] { "UpperArmL", "LowerArmL", "HandL" };
		string[] names = new string[3] { "upper_arm.l", "lower_arm.l", "hand.l" };
		if (p == null || p.Length != 3 || Enumerable.Range(0, 3).Any((int i) => !Object.op_Implicit((Object)(object)p[i].originalTransform) || !p[i].originalTransform.IsChildOf(display) || ((Object)p[i].originalTransform).name != names[i] || p[i].targetChildLimb != children[i] || (i > 0 && (Object)(object)p[i].originalTransform.parent != (Object)(object)p[i - 1].originalTransform)))
		{
			return null;
		}
		if (((Component)display).GetComponentsInChildren<Animator>(true).Any((Animator a) => Object.op_Implicit((Object)(object)a.runtimeAnimatorController)) || !Object.op_Implicit((Object)(object)val2.sharedMesh) || !Same(val2.bones, p.Select((LimbPair x) => x.originalTransform).ToArray()) || (Object)(object)val2.rootBone != (Object)(object)p[0].originalTransform)
		{
			return null;
		}
		Matrix4x4[] bindposes = val2.sharedMesh.bindposes;
		if (bindposes.Length != 3)
		{
			return null;
		}
		float[] array = new float[2];
		Vector3 val4;
		for (int num = 0; num < 2; num++)
		{
			int num2 = num;
			Matrix4x4 val3 = bindposes[num] * ((Matrix4x4)(ref bindposes[num + 1])).inverse;
			val4 = Vector4.op_Implicit(((Matrix4x4)(ref val3)).GetColumn(3));
			array[num2] = ((Vector3)(ref val4)).magnitude;
			if (!Finite(array[num]) || array[num] < 0.01f)
			{
				return null;
			}
		}
		Transform[] array2 = rule.razorwireBones.Select(anchor).ToArray();
		if (array2.Any((Transform b) => !Object.op_Implicit((Object)(object)b) || !b.IsChildOf(owner) || !UniformPositive(b.lossyScale)) || (Object)(object)array2[1].parent != (Object)(object)array2[0] || (Object)(object)array2[2].parent != (Object)(object)array2[1] || val2.bones.Any((Transform b) => !UniformPositive(b.lossyScale)))
		{
			return null;
		}
		int num3 = 1;
		while (num3 < 3)
		{
			val4 = array2[num3].localPosition;
			if (Finite(((Vector3)(ref val4)).magnitude))
			{
				val4 = array2[num3].localPosition;
				if (!(((Vector3)(ref val4)).magnitude < 0.01f))
				{
					num3++;
					continue;
				}
			}
			return null;
		}
		return new NativeRazorwireBinding(val2, display, owner, array2, array, rule.razorwireWidth);
	}

	private NativeRazorwireBinding(SkinnedMeshRenderer r, Transform display, Transform owner, Transform[] bones, float[] lengths, float width)
	{
		//IL_0073: 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_0097: Unknown result type (might be due to invalid IL or missing references)
		//IL_009d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		renderer = r;
		this.display = display;
		this.owner = owner;
		this.bones = bones;
		this.lengths = lengths;
		original = r.bones;
		originalRoot = r.rootBone;
		offscreen = r.updateWhenOffscreen;
		for (int i = 0; i < 3; i++)
		{
			float num = original[i].lossyScale.x / bones[i].lossyScale.x * width;
			radial[i] = Vector3.one * num;
		}
	}

	public void Install()
	{
		//IL_001c: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < 3; i++)
		{
			targets[i] = new GameObject("EclipseRazorwire_" + i).transform;
			targets[i].SetParent(bones[i], false);
		}
		PoseTargets();
		renderer.bones = targets;
		installed = true;
		renderer.rootBone = targets[0];
		renderer.updateWhenOffscreen = true;
	}

	private void PoseTargets()
	{
		//IL_002b: 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_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: 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_0077: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		for (int i = 0; i < 3; i++)
		{
			Vector3 val = (Vector3)((i < 2) ? bones[i + 1].localPosition : new Vector3(0f, -1f, 0f));
			targets[i].localRotation = ((i < 2) ? Quaternion.FromToRotation(Vector3.up, ((Vector3)(ref val)).normalized) : Quaternion.AngleAxis(180f, Vector3.forward));
			Vector3 val2 = radial[i];
			val2.y = ((i < 2) ? (((Vector3)(ref val)).magnitude / lengths[i]) : (val2.y * 0.4f));
			targets[i].localScale = val2;
		}
	}

	public void Update()
	{
		if (Alive)
		{
			PoseTargets();
		}
	}

	public void Dispose()
	{
		if (disposed)
		{
			return;
		}
		if (Object.op_Implicit((Object)(object)renderer))
		{
			Transform[] array = renderer.bones;
			if (Same(array, targets))
			{
				renderer.bones = original;
			}
			else if (array != null && array.Any((Transform t) => Object.op_Implicit((Object)(object)t) && targets.Contains(t)))
			{
				throw new InvalidOperationException("Razorwire bones still borrowed; retain cleanup lease");
			}
			if (Object.op_Implicit((Object)(object)renderer.rootBone) && targets.Contains(renderer.rootBone))
			{
				renderer.rootBone = originalRoot;
			}
			if (installed && renderer.updateWhenOffscreen)
			{
				renderer.updateWhenOffscreen = offscreen;
			}
		}
		Transform[] array2 = targets;
		foreach (Transform val in array2)
		{
			if (Object.op_Implicit((Object)(object)val))
			{
				for (int num2 = val.childCount - 1; num2 >= 0; num2--)
				{
					val.GetChild(num2).SetParent(owner, true);
				}
				Object.Destroy((Object)(object)((Component)val).gameObject);
			}
		}
		disposed = true;
	}
}
public interface ISkinCueEffectDriver : ISkinEffectDriver, IDisposable
{
	void Cue(string cue);
}
public sealed class NativeSkinPresentationDefinition
{
	public readonly string Id;

	public readonly Func<GameObject, SkinAudioRouter> CreateAudio;

	public readonly Func<GameObject, ISkinEffectDriver> CreateEffects;

	public NativeSkinPresentationDefinition(string id, Func<GameObject, SkinAudioRouter> audio, Func<GameObject, ISkinEffectDriver> effects)
	{
		if (string.IsNullOrWhiteSpace(id) || (audio == null && effects == null))
		{
			throw new ArgumentException("Presentation identity and at least one factory required");
		}
		Id = id;
		CreateAudio = audio;
		CreateEffects = effects;
	}
}
public sealed class NativeSkinPresentation : MonoBehaviour
{
	private NativeSkinPresentationDefinition definition;

	private SkinAudioRouter audio;

	private ISkinEffectDriver effects;

	private int generation;

	private bool active;

	private float retryAt;

	private int audioAttempts;

	public string Id
	{
		get
		{
			if (!active)
			{
				return null;
			}
			return definition?.Id;
		}
	}

	internal int BeginApply()
	{
		generation++;
		Release();
		definition = null;
		active = false;
		return generation;
	}

	internal void Commit(int token, NativeSkinPresentationDefinition next)
	{
		if (token != generation || !Object.op_Implicit((Object)(object)this))
		{
			return;
		}
		definition = next;
		active = next != null && ((Behaviour)this).isActiveAndEnabled;
		audioAttempts = 0;
		retryAt = 0f;
		if (active)
		{
			try
			{
				effects = next.CreateEffects?.Invoke(((Component)this).gameObject);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("ECLIPSE_PRESENTATION_EFFECTS_FAILED " + next.Id + " " + ex));
			}
			TryAudio();
		}
	}

	private void TryAudio()
	{
		if (!active || audio != null || definition.CreateAudio == null || audioAttempts >= 10 || Time.unscaledTime < retryAt)
		{
			return;
		}
		audioAttempts++;
		retryAt = Time.unscaledTime + 0.5f;
		try
		{
			audio = definition.CreateAudio(((Component)this).gameObject);
		}
		catch (SkinAudioContextUnavailableException)
		{
		}
		catch (Exception ex2)
		{
			audioAttempts = 10;
			Debug.LogError((object)("ECLIPSE_PRESENTATION_AUDIO_FAILED " + definition.Id + " " + ex2));
		}
	}

	public bool TryCue(string cue)
	{
		if (active && audio != null)
		{
			return audio.TryCue(cue, Time.unscaledTime);
		}
		return false;
	}

	public void PlayEffect(string cue)
	{
		if (active && effects is ISkinCueEffectDriver skinCueEffectDriver)
		{
			try
			{
				skinCueEffectDriver.Cue(cue);
			}
			catch (Exception ex)
			{
				Debug.LogError((object)("ECLIPSE_PRESENTATION_EFFECT_CUE " + ex));
			}
		}
	}

	public NativeSoundDecision TryReplaceNative(string name)
	{
		if (!active || audio == null)
		{
			return NativeSoundDecision.Forward;
		}
		return audio.TryReplaceNative(name, Time.unscaledTime);
	}

	private void Update()
	{
		if (!active)
		{
			return;
		}
		TryAudio();
		try
		{
			audio?.Update();
		}
		catch (Exception ex)
		{
			Debug.LogError((object)("ECLIPSE_PRESENTATION_AUDIO_UPDATE " + ex));
			SkinAudioCleanupPump.Release(audio);
			audio = null;
			audioAttempts = 10;
		}
		try
		{
			effects?.Update();
		}
		catch (Exception ex2)
		{
			Debug.LogError((object)("ECLIPSE_PRESENTATION_EFFECTS_UPDATE " + ex2));
			SkinAudioCleanupPump.Release(effects);
			effects = null;
		}
	}

	private void Release()
	{
		SkinAudioCleanupPump.Release(audio);
		audio = null;
		SkinAudioCleanupPump.Release(effects);
		effects = null;
	}

	private void OnDisable()
	{
		generation++;
		Release();
		active = false;
	}

	private void OnEnable()
	{
		if (definition != null)
		{
			Commit(generation, definition);
		}
	}

	private void OnDestroy()
	{
		generation++;
		Release();
		definition = null;
		active = false;
	}
}
public sealed class NativeSkinPresentationBridge : IDisposable
{
	private readonly Dictionary<SkinDef, NativeSkinPresentationDefinition> definitions = new Dictionary<SkinDef, NativeSkinPresentationDefinition>();

	private readonly HashSet<NativeSkinPresentation> instances = new HashSet<NativeSkinPresentation>();

	private static NativeSkinPresentationBridge owner;

	private bool disposed;

	public NativeSkinPresentationBridge()
	{
		//IL_0035: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		if (owner != null)
		{
			throw new InvalidOperationException("Native presentation bridge already installed");
		}
		SkinDef.ApplyAsync += new hook_ApplyAsync(Apply);
		owner = this;
	}

	public void Register(SkinDef skin, NativeSkinPresentationDefinition definition)
	{
		if (disposed || !Object.op_Implicit((Object)(object)skin) || definition == null || definitions.ContainsKey(skin))
		{
			throw new ArgumentException("Register one presentation per skin");
		}
		definitions.Add(skin, definition);
	}

	private IEnumerator Apply(orig_ApplyAsync orig, SkinDef skin, GameObject model, List<AssetReferenceT<Material>> materials, List<AssetReferenceT<Mesh>> meshes, AsyncReferenceHandleUnloadType unload)
	{
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
		NativeSkinPresentationDefinition next = null;
		if (Object.op_Implicit((Object)(object)skin))
		{
			definitions.TryGetValue(skin, out next);
		}
		instances.RemoveWhere((NativeSkinPresentation instance) => !Object.op_Implicit((Object)(object)instance));
		NativeSkinPresentation component = (Object.op_Implicit((Object)(object)model) ? model.GetComponent<NativeSkinPresentation>() : null);
		if (next != null && Object.op_Implicit((Object)(object)model) && !Object.op_Implicit((Object)(object)component))
		{
			component = model.AddComponent<NativeSkinPresentation>();
			instances.Add(component);
		}
		if (!Object.op_Implicit((Object)(object)component))
		{
			return orig.Invoke(skin, model, materials, meshes, unload);
		}
		int token = component.BeginApply();
		IEnumerator enumerator = orig.Invoke(skin, model, materials, meshes, unload);
		if (enumerator == null)
		{
			return null;
		}
		return SkinApplyCompletion.Observe(enumerator, delegate
		{
			if (!disposed && Object.op_Implicit((Object)(object)component))
			{
				try
				{
					component.Commit(token, next);
				}
				catch (Exception ex)
				{
					Debug.LogError((object)("ECLIPSE_PRESENTATION_COMMIT_FAILED " + ex));
				}
			}
		});
	}

	public void Dispose()
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		//IL_0021: Expected O, but got Unknown
		if (disposed)
		{
			return;
		}
		disposed = true;
		SkinDef.ApplyAsync -= new hook_ApplyAsync(Apply);
		foreach (NativeSkinPresentation instance in instances)
		{
			if (Object.op_Implicit((Object)(object)instance))
			{
				instance.BeginApply();
				Object.Destroy((Object)(object)instance);
			}
		}
		instances.Clear();
		definitions.Clear();
		if (owner == this)
		{
			owner = null;
		}
	}
}
public struct NativeSoundPlayback
{
	public readonly SoundResult Result;

	public readonly uint PlayingId;

	public NativeSoundPlayback(SoundResult result, uint playingId = 0u)
	{
		if (result == SoundResult.Played != (playingId != 0))
		{
			throw new ArgumentException("Played native sound requires an engine playing ID");
		}
		Result = result;
		PlayingId = playingId;
	}
}
public struct NativeSoundDecision
{
	public readonly bool SuppressNative;

	public readonly uint PlayingId;

	public static NativeSoundDecision Forward => new NativeSoundDecision(suppressNative: false);

	public NativeSoundDecision(bool suppressNative, uint playingId = 0u)
	{
		SuppressNative = suppressNative;
		PlayingId = playingId;
	}
}
public sealed class NativeSoundLoop
{
	public string StartEvent;

	public string StopEvent;

	public string Cue;
}
public sealed class NativeSoundRouter
{
	private sealed class LoopState
	{
		public string Cue;

		public bool NativeFallback;

		public bool HasStart;

		public readonly HashSet<uint> Playing = new HashSet<uint>();

		public readonly HashSet<uint> PendingStops = new HashSet<uint>();
	}

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

	private readonly Dictionary<string, LoopState> starts = new Dictionary<string, LoopState>(StringComparer.Ordinal);

	private readonly Dictionary<string, LoopState> stops = new Dictionary<string, LoopState>(StringComparer.Ordinal);

	private readonly Func<string, NativeSoundPlayback> play;

	private readonly Func<uint, bool> stop;

	public int PendingStopCount
	{
		get
		{
			int num = 0;
			foreach (LoopState value in starts.Values)
			{
				foreach (uint pendingStop in value.PendingStops)
				{
					if (pendingStop != 0)
					{
						num++;
					}
				}
			}
			return num;
		}
	}

	public NativeSoundRouter(IDictionary<string, string> replacements, IEnumerable<NativeSoundLoop> loops, Func<string, NativeSoundPlayback> play, Func<uint, bool> stop)
	{
		this.play = play ?? throw new ArgumentNullException("play");
		this.stop = stop ?? throw new ArgumentNullException("stop");
		HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
		foreach (KeyValuePair<string, string> replacement in replacements)
		{
			if (string.IsNullOrWhiteSpace(replacement.Key) || string.IsNullOrWhiteSpace(replacement.Value) || !hashSet.Add(replacement.Key))
			{
				throw new ArgumentException("Invalid native sound mapping");
			}
			oneShots.Add(replacement.Key, replacement.Value);
		}
		foreach (NativeSoundLoop loop in loops)
		{
			if (loop == null || string.IsNullOrWhiteSpace(loop.StartEvent) || string.IsNullOrWhiteSpace(loop.StopEvent) || string.IsNullOrWhiteSpace(loop.Cue) || !hashSet.Add(loop.StartEvent) || !hashSet.Add(loop.StopEvent))
			{
				throw new ArgumentException("Ambiguous native sound loop pair");
			}
			LoopState value = new LoopState
			{
				Cue = loop.Cue
			};
			starts.Add(loop.StartEvent, value);
			stops.Add(loop.StopEvent, value);
		}
	}

	private static NativeSoundDecision Decision(NativeSoundPlayback result)
	{
		return new NativeSoundDecision(result.Result != SoundResult.Unavailable, result.PlayingId);
	}

	public NativeSoundDecision Route(string exactEvent)
	{
		if (exactEvent == null)
		{
			return NativeSoundDecision.Forward;
		}
		if (stops.TryGetValue(exactEvent, out var value))
		{
			foreach (uint item in value.Playing)
			{
				value.PendingStops.Add(item);
			}
			value.Playing.Clear();
			value.NativeFallback = false;
			value.HasStart = false;
			Retry(value);
			return NativeSoundDecision.Forward;
		}
		if (starts.TryGetValue(exactEvent, out value))
		{
			NativeSoundPlayback result = play(value.Cue);
			value.HasStart = true;
			if (result.Result == SoundResult.Unavailable)
			{
				value.NativeFallback = true;
			}
			else if (result.Result == SoundResult.Played)
			{
				value.Playing.Add(result.PlayingId);
			}
			return Decision(result);
		}
		if (!oneShots.TryGetValue(exactEvent, out var value2))
		{
			return NativeSoundDecision.Forward;
		}
		return Decision(play(value2));
	}

	private void Retry(LoopState state)
	{
		foreach (uint item in new List<uint>(state.PendingStops))
		{
			try
			{
				if (stop(item))
				{
					state.PendingStops.Remove(item);
				}
			}
			catch
			{
			}
		}
	}

	public void RetryPendingStops()
	{
		foreach (LoopState value in starts.Values)
		{
			Retry(value);
		}
	}

	public void StopOwned()
	{
		foreach (LoopState value in starts.Values)
		{
			foreach (uint item in value.Playing)
			{
				value.PendingStops.Add(item);
			}
			value.Playing.Clear();
			Retry(value);
		}
	}
}
public sealed class OwnedNativeVoices
{
	public sealed class Ticket
	{
		internal readonly OwnedNativeVoices Owner;

		internal int completed;

		public readonly string Cue;

		public readonly object Emitter;

		public uint PlayingId { get; internal set; }

		public bool StopRequested { get; internal set; }

		public bool Completed => Volatile.Read(in completed) != 0;

		internal Ticket(OwnedNativeVoices owner, string cue, object emitter)
		{
			Owner = owner;
			Cue = cue;
			Emitter = emitter;
		}

		public void Complete()
		{
			Interlocked.Exchange(ref completed, 1);
		}
	}

	private readonly int capacity;

	private readonly List<Ticket> tickets = new List<Ticket>();

	public int Count
	{
		get
		{
			Drain();
			return tickets.Count;
		}
	}

	public OwnedNativeVoices(int capacity = 8)
	{
		if (capacity < 1 || capacity > 32)
		{
			throw new ArgumentOutOfRangeException("capacity");
		}
		this.capacity = capacity;
	}

	public Ticket Reserve(string cue, int cueLimit, object emitter)
	{
		if (string.IsNullOrWhiteSpace(cue) || cueLimit < 1 || cueLimit > 4 || emitter == null)
		{
			throw new ArgumentException("Invalid owned voice request");
		}
		Drain();
		if (tickets.Count >= capacity || tickets.Count((Ticket t) => t.Cue == cue) >= cueLimit)
		{
			return null;
		}
		Ticket ticket = new Ticket(this, cue, emitter);
		tickets.Add(ticket);
		return ticket;
	}

	private void Require(Ticket ticket)
	{
		if (ticket == null || ticket.Owner != this || !tickets.Contains(ticket))
		{
			throw new ArgumentException("Voice is not owned by this ledger");
		}
	}

	public void Commit(Ticket ticket, uint playingId)
	{
		Require(ticket);
		if (playingId == 0 || ticket.PlayingId != 0)
		{
			throw new ArgumentException("Invalid native playing ID");
		}
		ticket.PlayingId = playingId;
	}

	public void Abort(Ticket ticket)
	{
		Require(ticket);
		ticket.Complete();
		Drain();
	}

	public void MarkStopRequested(Ticket ticket)
	{
		Require(ticket);
		if (ticket.PlayingId == 0)
		{
			throw new InvalidOperationException("Cannot stop an unposted voice");
		}
		ticket.StopRequested = true;
	}

	public void Drain()
	{
		tickets.RemoveAll((Ticket t) => t.Completed);
	}

	public Ticket[] Active()
	{
		Drain();
		return tickets.ToArray();
	}

	public void EngineStopped()
	{
		foreach (Ticket ticket in tickets)
		{
			ticket.Complete();
		}
		tickets.Clear();
	}
}
internal sealed class TrackedDisposal : IDisposable
{
	private IDisposable value;

	internal TrackedDisposal(IDisposable value)
	{
		this.value = value;
	}

	public void Dispose()
	{
		if (value != null)
		{
			value.Dispose();
			value = null;
		}
	}
}
internal sealed class ResourceRetirement : IDisposable
{
	private readonly IList<TrackedDisposal> leases;

	private Action destroy;

	internal ResourceRetirement(IList<TrackedDisposal> leases, Action destroy)
	{
		this.leases = leases;
		this.destroy = destroy;
	}

	public void Dispose()
	{
		Exception ex = null;
		foreach (TrackedDisposal lease in leases)
		{
			try
			{
				lease.Dispose();
			}
			catch (Exception ex2)
			{
				ex = ex2;
			}
		}
		if (ex != null)
		{
			throw new InvalidOperationException("Resource retirement waiting for leases", ex);
		}
		destroy?.Invoke();
		destroy = null;
	}
}
public sealed class RetryDisposalQueue
{
	private sealed class Entry
	{
		public IDisposable Value;

		public double Next;

		public int Attempts;
	}

	private readonly List<Entry> entries = new List<Entry>();

	private bool draining;

	public int Count => entries.Count;

	public void Add(IDisposable value)
	{
		if (value == null)
		{
			return;
		}
		foreach (Entry entry in entries)
		{
			if (entry.Value == value)
			{
				return;
			}
		}
		entries.Add(new Entry
		{
			Value = value
		});
	}

	public void Tick(double now, Action<Exception> failed = null)
	{
		if (draining || double.IsNaN(now) || double.IsInfinity(now))
		{
			return;
		}
		draining = true;
		try
		{
			Entry[] array = entries.ToArray();
			foreach (Entry entry in array)
			{
				if (now < entry.Next)
				{
					continue;
				}
				entry.Attempts++;
				entry.Next = now + Math.Min(30.0, Math.Pow(2.0, Math.Min(5, entry.Attempts)));
				try
				{
					entry.Value.Dispose();
					entries.Remove(entry);
				}
				catch (Exception obj)
				{
					if (failed != null)
					{
						try
						{
							failed(obj);
						}
						catch
						{
						}
					}
				}
			}
		}
		finally
		{
			draining = false;
		}
	}
}
public static class SkinApplyCompletion
{
	private sealed class State
	{
		public bool Failed;
	}

	private sealed class Completion : IEnumerator, IDisposable
	{
		private readonly IEnumerator source;

		private readonly Action completed;

		private readonly State state;

		private Completion child;

		private object current;

		private bool disposed;

		private bool finished;

		public object Current => current;

		internal Completion(IEnumerator source, Action completed, State state)
		{
			this.source = source;
			this.completed = completed;
			this.state = state;
		}

		public bool MoveNext()
		{
			if (disposed)
			{
				return false;
			}
			try
			{
				if (child != null)
				{
					if (!child.finished)
					{
						state.Failed = true;
					}
					child.Dispose();
					child = null;
				}
				if (!source.MoveNext())
				{
					finished = true;
					Dispose();
					if (!state.Failed)
					{
						completed?.Invoke();
					}
					return false;
				}
				current = source.Current;
				if (current is IEnumerator enumerator)
				{
					child = new Completion(enumerator, null, state);
					current = child;
				}
				return true;
			}
			catch
			{
				state.Failed = true;
				Dispose();
				throw;
			}
		}

		public void Reset()
		{
			throw new NotSupportedException();
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			disposed = true;
			if (!finished)
			{
				state.Failed = true;
			}
			try
			{
				child?.Dispose();
			}
			finally
			{
				child = null;
				current = null;
				(source as IDisposable)?.Dispose();
			}
		}
	}

	public static IEnumerator Observe(IEnumerator source, Action completed)
	{
		if (source == null)
		{
			throw new ArgumentNullException("source");
		}
		return new Completion(source, completed, new State());
	}
}
public static class SkinApplyObservation
{
	private sealed class Observed : IEnumerator, IDisposable
	{
		private readonly IEnumerator source;

		private readonly Action after;

		private readonly Action<Exception> failed;

		private Observed nested;

		private object current;

		private bool disposed;

		public object Current => current;

		public Observed(IEnumerator source, Action after, Action<Exception> failed)
		{
			this.source = source;
			this.after = after;
			this.failed = failed;
		}

		private void Report(Exception ex)
		{
			try
			{
				failed?.Invoke(ex);
			}
			catch
			{
			}
		}

		private void Notify()
		{
			try
			{
				after?.Invoke();
			}
			catch (Exception ex)
			{
				Report(ex);
			}
		}

		public bool MoveNext()
		{
			if (disposed)
			{
				return false;
			}
			try
			{
				if (nested != null)
				{
					nested.Dispose();
					nested = null;
				}
				if (source == null || !source.MoveNext())
				{
					Dispose();
					return false;
				}
				Notify();
				current = source.Current;
				if (current is IEnumerator enumerator)
				{
					nested = new Observed(enumerator, after, failed);
					current = nested;
				}
				return true;
			}
			catch
			{
				try
				{
					Dispose();
				}
				catch (Exception ex)
				{
					Report(ex);
				}
				throw;
			}
		}

		public void Reset()
		{
			throw new NotSupportedException();
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			disposed = true;
			try
			{
				nested?.Dispose();
			}
			finally
			{
				nested = null;
				try
				{
					(source as IDisposable)?.Dispose();
				}
				finally
				{
					current = null;
					Notify();
				}
			}
		}
	}

	public static IEnumerator Observe(IEnumerator source, Action after, Action<Exception> failed)
	{
		return new Observed(source, after, failed);
	}
}
public abstract class SkinSoundAsset
{
}
public sealed class UnityClipSoundAsset : SkinSoundAsset
{
	public AudioClip[] Clips;
}
public sealed class WwiseEventSoundAsset : SkinSoundAsset
{
	public string BankId;

	public string[] Events;
}
public sealed class SkinAudioContextUnavailableException : Exception
{
	public SkinAudioContextUnavailableException(string message)
		: base(message)
	{
	}
}
public sealed class SkinSound
{
	public string Id;

	public string Anchor;

	public string Provenance;

	public SkinSoundAsset Asset;

	public float Gain = 0.7f;

	public float Cooldown = 0.15f;

	public float MinDistance = 3f;

	public float MaxDistance = 60f;

	public int MaxVoices = 2;

	public bool Loop;
}
public sealed class SkinSoundProfile
{
	public readonly Dictionary<string, SkinSound> Cues = new Dictionary<string, SkinSound>();

	public readonly Dictionary<string, string> NativeEventReplacements = new Dictionary<string, string>();

	public readonly List<NativeSoundLoop> NativeLoops = new List<NativeSoundLoop>();

	public void Validate()
	{
		foreach (KeyValuePair<string, SkinSound> cue in Cues)
		{
			SkinSound value = cue.Value;
			if (value == null || cue.Key != value.Id || string.IsNullOrWhiteSpace(value.Anchor) || string.IsNullOrWhiteSpace(value.Provenance) || value.Asset == null || !Limits.Finite(value.Gain) || value.Gain < 0f || value.Gain > 1f || !Limits.Finite(value.Cooldown) || value.Cooldown < 0f || !Limits.Finite(value.MinDistance) || value.MinDistance <= 0f || !Limits.Finite(value.MaxDistance) || value.MaxDistance <= value.MinDistance || value.MaxVoices < 1 || value.MaxVoices > 4)
			{
				throw new ArgumentException("Invalid species sound " + cue.Key);
			}
		}
		foreach (KeyValuePair<string, string> nativeEventReplacement in NativeEventReplacements)
		{
			if (!Cues.ContainsKey(nativeEventReplacement.Value) || Cues[nativeEventReplacement.Value].Loop)
			{
				throw new ArgumentException("Missing/non-one-shot replacement cue " + nativeEventReplacement.Key);
			}
		}
		foreach (NativeSoundLoop nativeLoop in NativeLoops)
		{
			if (nativeLoop == null || !Cues.ContainsKey(nativeLoop.Cue) || !Cues[nativeLoop.Cue].Loop)
			{
				throw new ArgumentException("Loop replacement requires an explicit loop cue");
			}
		}
	}
}
public interface ISkinSoundBackend : IDisposable
{
	bool Available { get; }

	void Validate(SkinSound sound);

	SoundResult Play(SkinSound sound, Transform anchor);
}
public interface ISkinNativeSoundBackend
{
	NativeSoundPlayback PlayNative(SkinSound sound, Transform anchor);

	bool StopNative(uint playingId);
}
public interface ISkinSoundBackendUpdate
{
	void Update();
}
public sealed class SkinAudioRouter : IDisposable
{
	private readonly SkinSoundProfile profile;

	private readonly ISkinSoundBackend backend;

	private readonly Func<string, Transform> anchor;

	private readonly SoundGate gate = new SoundGate();

	private readonly NativeSoundRouter native;

	private double nativeNow;

	private bool disposed;

	public SkinAudioRouter(SkinSoundProfile profile, ISkinSoundBackend backend, Func<string, Transform> anchor)
	{
		SkinAudioRouter skinAudioRouter = this;
		if (profile == null || backend == null || anchor == null)
		{
			throw new ArgumentNullException("Audio routing context");
		}
		try
		{
			profile.Validate();
			foreach (SkinSound value in profile.Cues.Values)
			{
				backend.Validate(value);
			}
			native = new NativeSoundRouter(profile.NativeEventReplacements, profile.NativeLoops, (string id) => skinAudioRouter.NativeCue(id, skinAudioRouter.nativeNow), (uint id) => ((ISkinNativeSoundBackend)backend).StopNative(id));
		}
		catch
		{
			SkinAudioCleanupPump.Release(backend);
			throw;
		}
		this.profile = profile;
		this.backend = backend;
		this.anchor = anchor;
	}

	private SoundResult Cue(string id, double now)
	{
		if (!profile.Cues.TryGetValue(id, out var sound) || sound.Loop || !backend.Available)
		{
			return SoundResult.Unavailable;
		}
		Transform target = anchor(sound.Anchor);
		if (!Object.op_Implicit((Object)(object)target))
		{
			return SoundResult.Unavailable;
		}
		return gate.Dispatch(id, now, sound.Cooldown, () => backend.Play(sound, target));
	}

	public bool TryCue(string id, double now)
	{
		return Cue(id, now) == SoundResult.Played;
	}

	private NativeSoundPlayback NativeCue(string id, double now)
	{
		ISkinNativeSoundBackend nativeBackend = backend as ISkinNativeSoundBackend;
		if (nativeBackend == null || !backend.Available || !profile.Cues.TryGetValue(id, out var sound))
		{
			return new NativeSoundPlayback(SoundResult.Unavailable);
		}
		Transform target = anchor(sound.Anchor);
		if (!Object.op_Implicit((Object)(object)target))
		{
			return new NativeSoundPlayback(SoundResult.Unavailable);
		}
		NativeSoundPlayback playback = default(NativeSoundPlayback);
		SoundResult num = gate.Dispatch(id, now, sound.Cooldown, delegate
		{
			playback = nativeBackend.PlayNative(sound, target);
			return playback.Result;
		});
		return new NativeSoundPlayback(num, (num == SoundResult.Played) ? playback.PlayingId : 0u);
	}

	public NativeSoundDecision TryReplaceNative(string exactEvent, double now)
	{
		nativeNow = now;
		return native.Route(exactEvent);
	}

	public void Update()
	{
		(backend as ISkinSoundBackendUpdate)?.Update();
		native.RetryPendingStops();
	}

	public void Dispose()
	{
		if (!disposed)
		{
			native.StopOwned();
			backend.Dispose();
			gate.Reset();
			disposed = true;
		}
	}
}
public sealed class SkinAudioCleanupPump : MonoBehaviour
{
	private static readonly RetryDisposalQueue pending = new RetryDisposalQueue();

	private static SkinAudioCleanupPump instance;

	private static bool quitting;

	public static void Release(IDisposable backend)
	{
		//IL_005f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: 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_0071: Expected O, but got Unknown
		pending.Add(backend);
		pending.Tick(Time.unscaledTime, delegate(Exception ex2)
		{
			Debug.LogError((object)("ECLIPS