Decompiled source of ValheimVR Dev v0.9.17006
plugins/ValheimVRMod.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Timers; using AmplifyOcclusion; using BepInEx; using BepInEx.Configuration; using Bhaptics.Tact; using GUIFramework; using HarmonyLib; using Microsoft.CodeAnalysis; using NDesk.Options; using RootMotion.FinalIK; using TMPro; using Unity.XR.OpenVR; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.UI; using UnityEngine.PostProcessing; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.SpatialTracking; using UnityEngine.UI; using UnityEngine.XR; using UnityEngine.XR.Management; using UnityStandardAssets.ImageEffects; using Valheim.SettingsGui; using ValheimVRMod.Patches; using ValheimVRMod.Scripts; using ValheimVRMod.Scripts.Block; using ValheimVRMod.Scripts.PostProcessing; using ValheimVRMod.Utilities; using ValheimVRMod.VRCore; using ValheimVRMod.VRCore.UI; using ValheimVRMod.VRCore.UI.HudElements; using Valve.Newtonsoft.Json; using Valve.VR; using Valve.VR.Extras; using Valve.VR.InteractionSystem; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("ValheimVRMod")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ValheimVRMod")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("86b846a5-747b-47dc-ac73-fda218e4361f")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } internal class FogComponentPatches { [HarmonyPatch(typeof(FogComponent), "PopulateCommandBuffer")] private class FogComponent_PopulateCommandBuffer_Patch { private static class Uniforms { internal static readonly int _FogColor = Shader.PropertyToID("_FogColor"); internal static readonly int _Density = Shader.PropertyToID("_Density"); internal static readonly int _Start = Shader.PropertyToID("_Start"); internal static readonly int _End = Shader.PropertyToID("_End"); internal static readonly int _TempRT = Shader.PropertyToID("_TempRT"); internal static readonly int _TopLeft = Shader.PropertyToID("_TopLeft"); internal static readonly int _TopRight = Shader.PropertyToID("_TopRight"); internal static readonly int _BottomLeft = Shader.PropertyToID("_BottomLeft"); internal static readonly int _BottomRight = Shader.PropertyToID("_BottomRight"); internal static readonly int _SunDir = Shader.PropertyToID("_SunDir"); internal static readonly int _SunFogColor = Shader.PropertyToID("_SunFogColor"); } private static Vector3[] _frustumCornersBuffer = (Vector3[])(object)new Vector3[4]; private static bool Prefix(CommandBuffer cb, FogComponent __instance) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0184: 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_018d: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Expected I4, but got Unknown //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) if (VHVRConfig.NonVrPlayer()) { return true; } Settings settings = ((PostProcessingComponent<FogModel>)(object)__instance).model.settings; Material val = ((PostProcessingComponentBase)__instance).context.materialFactory.Get("Hidden/Post FX/Fog"); val.shaderKeywords = null; int fogColor = Uniforms._FogColor; Color val2; if (!GraphicsUtils.isLinearColorSpace) { val2 = RenderSettings.fogColor; } else { Color fogColor2 = RenderSettings.fogColor; val2 = ((Color)(ref fogColor2)).linear; } val.SetColor(fogColor, val2); val.SetFloat(Uniforms._Density, UnderwaterEffectsUpdater.UsingUnderwaterEffects ? 0.125f : RenderSettings.fogDensity); val.SetFloat(Uniforms._Start, RenderSettings.fogStartDistance); val.SetFloat(Uniforms._End, RenderSettings.fogEndDistance); Camera camera = ((PostProcessingComponentBase)__instance).context.camera; Transform transform = ((Component)camera).transform; camera.CalculateFrustumCorners(new Rect(0f, 0f, 1f, 1f), camera.farClipPlane, camera.stereoActiveEye, _frustumCornersBuffer); Vector3 val3 = transform.TransformVector(_frustumCornersBuffer[1]); Vector3 val4 = transform.TransformVector(_frustumCornersBuffer[2]); Vector3 val5 = transform.TransformVector(_frustumCornersBuffer[0]); Vector3 val6 = transform.TransformVector(_frustumCornersBuffer[3]); val.SetVector(Uniforms._TopLeft, Vector4.op_Implicit(val3)); val.SetVector(Uniforms._TopRight, Vector4.op_Implicit(val4)); val.SetVector(Uniforms._BottomLeft, Vector4.op_Implicit(val5)); val.SetVector(Uniforms._BottomRight, Vector4.op_Implicit(val6)); FogMode fogMode = RenderSettings.fogMode; FogMode val7 = fogMode; switch (val7 - 1) { case 0: val.EnableKeyword("FOG_LINEAR"); break; case 1: val.EnableKeyword("FOG_EXP"); break; case 2: val.EnableKeyword("FOG_EXP2"); break; } RenderTextureFormat val8 = (RenderTextureFormat)(((PostProcessingComponentBase)__instance).context.isHdr ? 9 : 7); cb.GetTemporaryRT(Uniforms._TempRT, ((PostProcessingComponentBase)__instance).context.width, ((PostProcessingComponentBase)__instance).context.height, 24, (FilterMode)1, val8); cb.Blit(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2), RenderTargetIdentifier.op_Implicit(Uniforms._TempRT)); cb.Blit(RenderTargetIdentifier.op_Implicit(Uniforms._TempRT), RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2), val, settings.excludeSkybox ? 1 : 0); cb.ReleaseTemporaryRT(Uniforms._TempRT); return false; } } } [DisallowMultipleComponent] public class Outline : MonoBehaviour { public enum Mode { OutlineAll, OutlineVisible, OutlineHidden, OutlineAndSilhouette, SilhouetteOnly } [Serializable] private class ListVector3 { public List<Vector3> data; } private static HashSet<Mesh> registeredMeshes = new HashSet<Mesh>(); [SerializeField] private Mode outlineMode; [SerializeField] private Color outlineColor = Color.white; [SerializeField] [Range(0f, 10f)] private float outlineWidth = 2f; [Header("Optional")] [SerializeField] [Tooltip("Precompute enabled: Per-vertex calculations are performed in the editor and serialized with the object. Precompute disabled: Per-vertex calculations are performed at runtime in Awake(). This may cause a pause for large meshes.")] private bool precomputeOutline; [SerializeField] [HideInInspector] private List<Mesh> bakeKeys = new List<Mesh>(); [SerializeField] [HideInInspector] private List<ListVector3> bakeValues = new List<ListVector3>(); private Renderer[] renderers; private static Material sharedOutlineMaskMaterial; private static Material sharedOutlineFillMaterial; private Material outlineMaskMaterial; private Material outlineFillMaterial; private bool needsUpdate; public Mode OutlineMode { get { return outlineMode; } set { outlineMode = value; needsUpdate = true; } } public Color OutlineColor { get { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) return outlineColor; } set { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) outlineColor = value; needsUpdate = true; } } public float OutlineWidth { get { return outlineWidth; } set { outlineWidth = value; needsUpdate = true; } } private void Awake() { renderers = ((Component)this).GetComponentsInChildren<Renderer>(); tryInitMaterials(); LoadSmoothNormals(); needsUpdate = true; } private void tryInitMaterials() { //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Expected O, but got Unknown if (!((Object)(object)outlineMaskMaterial != (Object)null) || !((Object)(object)outlineFillMaterial != (Object)null)) { if ((Object)(object)sharedOutlineMaskMaterial == (Object)null) { sharedOutlineMaskMaterial = Object.Instantiate<Material>(VRAssetManager.GetAsset<Material>("OutlineMask")); ((Object)sharedOutlineMaskMaterial).name = "OutlineMask (Instance)"; } if ((Object)(object)sharedOutlineFillMaterial == (Object)null) { sharedOutlineFillMaterial = Object.Instantiate<Material>(VRAssetManager.GetAsset<Material>("OutlineFill")); ((Object)sharedOutlineMaskMaterial).name = "OutlineFill (Instance)"; } outlineMaskMaterial = new Material(sharedOutlineMaskMaterial); outlineFillMaterial = new Material(sharedOutlineFillMaterial); } } private bool IsPlayerHairMaterials(List<Material> materials) { foreach (Material material in materials) { if (((Object)material).name.StartsWith("PlayerHair")) { return true; } } return false; } private void OnEnable() { Renderer[] array = renderers; foreach (Renderer val in array) { if (!(((object)val).GetType() == typeof(ParticleSystemRenderer))) { List<Material> list = val.sharedMaterials.ToList(); if (!IsPlayerHairMaterials(list)) { list.Add(outlineMaskMaterial); list.Add(outlineFillMaterial); val.materials = list.ToArray(); } } } } private void OnValidate() { needsUpdate = true; if ((!precomputeOutline && bakeKeys.Count != 0) || bakeKeys.Count != bakeValues.Count) { bakeKeys.Clear(); bakeValues.Clear(); } if (precomputeOutline && bakeKeys.Count == 0) { Bake(); } } private void Update() { if (needsUpdate) { needsUpdate = false; UpdateMaterialProperties(); } } private void OnDisable() { Renderer[] array = renderers; foreach (Renderer val in array) { if (!((Object)(object)val == (Object)null) && !(((object)val).GetType() == typeof(ParticleSystemRenderer)) && val.sharedMaterials != null) { List<Material> list = val.sharedMaterials.ToList(); list.Remove(outlineMaskMaterial); list.Remove(outlineFillMaterial); val.materials = list.ToArray(); } } } private void Bake() { HashSet<Mesh> hashSet = new HashSet<Mesh>(); MeshFilter[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshFilter>(); foreach (MeshFilter val in componentsInChildren) { if (hashSet.Add(val.sharedMesh)) { List<Vector3> data = SmoothNormals(val.sharedMesh); bakeKeys.Add(val.sharedMesh); bakeValues.Add(new ListVector3 { data = data }); } } } private void LoadSmoothNormals() { MeshFilter[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshFilter>(); foreach (MeshFilter val in componentsInChildren) { if (val.sharedMesh.isReadable && registeredMeshes.Add(val.sharedMesh)) { int num = bakeKeys.IndexOf(val.sharedMesh); List<Vector3> list = ((num >= 0) ? bakeValues[num].data : SmoothNormals(val.sharedMesh)); val.sharedMesh.SetUVs(3, list); } } SkinnedMeshRenderer[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer val2 in componentsInChildren2) { if (val2.sharedMesh.isReadable && registeredMeshes.Add(val2.sharedMesh)) { val2.sharedMesh.uv4 = (Vector2[])(object)new Vector2[val2.sharedMesh.vertexCount]; } } } private List<Vector3> SmoothNormals(Mesh mesh) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) IEnumerable<IGrouping<Vector3, KeyValuePair<Vector3, int>>> enumerable = from pair in mesh.vertices.Select((Vector3 vertex, int index) => new KeyValuePair<Vector3, int>(vertex, index)) group pair by pair.Key; List<Vector3> list = new List<Vector3>(mesh.normals); foreach (IGrouping<Vector3, KeyValuePair<Vector3, int>> item in enumerable) { if (item.Count() == 1) { continue; } Vector3 val = Vector3.zero; foreach (KeyValuePair<Vector3, int> item2 in item) { val += mesh.normals[item2.Value]; } ((Vector3)(ref val)).Normalize(); foreach (KeyValuePair<Vector3, int> item3 in item) { list[item3.Value] = val; } } return list; } private void UpdateMaterialProperties() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) outlineFillMaterial.SetColor("_OutlineColor", outlineColor); switch (outlineMode) { case Mode.OutlineAll: outlineMaskMaterial.SetFloat("_ZTest", 8f); outlineFillMaterial.SetFloat("_ZTest", 8f); outlineFillMaterial.SetFloat("_OutlineWidth", outlineWidth); break; case Mode.OutlineVisible: outlineMaskMaterial.SetFloat("_ZTest", 8f); outlineFillMaterial.SetFloat("_ZTest", 4f); outlineFillMaterial.SetFloat("_OutlineWidth", outlineWidth); break; case Mode.OutlineHidden: outlineMaskMaterial.SetFloat("_ZTest", 8f); outlineFillMaterial.SetFloat("_ZTest", 5f); outlineFillMaterial.SetFloat("_OutlineWidth", outlineWidth); break; case Mode.OutlineAndSilhouette: outlineMaskMaterial.SetFloat("_ZTest", 4f); outlineFillMaterial.SetFloat("_ZTest", 8f); outlineFillMaterial.SetFloat("_OutlineWidth", outlineWidth); break; case Mode.SilhouetteOnly: outlineMaskMaterial.SetFloat("_ZTest", 4f); outlineFillMaterial.SetFloat("_ZTest", 5f); outlineFillMaterial.SetFloat("_OutlineWidth", 0f); break; } } } namespace ValheimVRMod { [BepInPlugin("org.bepinex.plugins.valheimvrmod", "ValheimVR Mod", "0.9.16")] public class ValheimVRMod : BaseUnityPlugin { private static Version _version; private GameObject vrPlayer; private GameObject vrGui; private GameObject BhapticsTactsuit; public static Version PLUGIN_VERSION => _version; public static bool failedToInitializeVR { get; private set; } private void Awake() { _version = ((BaseUnityPlugin)this).Info.Metadata.Version; VHVRConfig.InitializeConfiguration(((BaseUnityPlugin)this).Config); LogUtils.LogInfo("Pre-release VHVR"); if (!VHVRConfig.ModEnabled()) { LogUtils.LogInfo("ValheimVRMod is disabled via configuration."); ((Behaviour)this).enabled = false; } else { Game.isModded = true; LogUtils.LogInfo("ValheimVR Mod Awakens!"); } } private void Start() { StartValheimVR(); } private void Update() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) if (!VHVRConfig.NonVrPlayer()) { if (Input.GetKeyDown(VHVRConfig.GetRecenterKey())) { VRManager.tryRecenter(); } if (!Input.GetKeyDown((KeyCode)92)) { } } } private void StartValheimVR() { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected O, but got Unknown bool flag = false; if (!VHVRConfig.NonVrPlayer()) { flag = VRManager.InitializeVR(); if (!flag) { LogUtils.LogError("Could not initialize VR."); failedToInitializeVR = true; } } HarmonyPatcher.DoPatching(); if (!VRAssetManager.Initialize()) { LogUtils.LogError("Problem initializing VR Assets"); flag = false; } if (!flag) { LogUtils.LogDebug("Non VR Mode Patching Complete."); return; } VRManager.StartVR(); vrPlayer = new GameObject("VRPlayer"); Object.DontDestroyOnLoad((Object)(object)vrPlayer); vrPlayer.AddComponent<VRPlayer>(); vrGui = new GameObject("VRGui"); Object.DontDestroyOnLoad((Object)(object)vrGui); vrGui.AddComponent<VRGUI>(); if (VHVRConfig.RecenterOnStart()) { VRManager.tryRecenter(); } if (VHVRConfig.BhapticsEnabled()) { BhapticsTactsuit = new GameObject("BhapticsTactsuit"); Object.DontDestroyOnLoad((Object)(object)BhapticsTactsuit); BhapticsTactsuit.AddComponent<BhapticsTactsuit>(); } } private void dumpall() { GameObject[] array = Object.FindObjectsOfType<GameObject>(); foreach (GameObject val in array) { LogUtils.LogDebug("Name + " + ((Object)val).name + " Layer = " + val.layer); } } } } namespace ValheimVRMod.VRCore { internal class VRManager { public static bool InitializeVR() { LogUtils.LogDebug("PreInitializing SteamVR Actions..."); SteamVR_Actions.PreInitialize(); LogUtils.LogInfo("Initializing VR..."); if (!InitXRSDK()) { LogUtils.LogError("Failed to initialize VR!."); return false; } if (!InitializeSteamVR()) { LogUtils.LogError("Problem initializing SteamVR"); return false; } return true; } public static bool StartVR() { LogUtils.LogInfo("Starting VR..."); return StartXRSDK(); } public static bool InitializeSteamVR() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 LogUtils.LogInfo("Initializing SteamVR..."); SteamVR.Initialize(false); if ((int)SteamVR.initializedState != 2) { LogUtils.LogError("Problem Initializing SteamVR"); return false; } if (!SteamVR_Input.initialized) { LogUtils.LogError("Problem Initializing SteamVR_Input"); return false; } ApplicationManifestHelper.UpdateManifest(Path.Combine(Application.streamingAssetsPath, "valheim.vrmanifest"), "steam.app.892970", "https://steamcdn-a.akamaihd.net/steam/apps/892970/header.jpg", "Valheim VR", "VR mod for Valheim", 892970, steamBuild: true); return true; } private static bool StartXRSDK() { LogUtils.LogInfo("Starting XRSDK!"); if ((Object)(object)XRGeneralSettings.Instance != (Object)null && (Object)(object)XRGeneralSettings.Instance.Manager != (Object)null && (Object)(object)XRGeneralSettings.Instance.Manager.activeLoader != (Object)null) { XRGeneralSettings.Instance.Manager.StartSubsystems(); } else { LogUtils.LogError("Error Starting XRSDK!"); if ((Object)(object)XRGeneralSettings.Instance == (Object)null) { LogUtils.LogError("XRGeneralSettings Instance is null!"); return false; } if ((Object)(object)XRGeneralSettings.Instance.Manager == (Object)null) { LogUtils.LogError("XRManager instance is null!"); return false; } if ((Object)(object)XRGeneralSettings.Instance.Manager.activeLoader == (Object)null) { LogUtils.LogError("Active loader is null!"); return false; } } return true; } private static bool InitXRSDK() { XRGeneralSettings val = LoadXRSettingsFromAssetBundle(); if ((Object)(object)val == (Object)null) { LogUtils.LogInfo("XRGeneralSettings Instance is null!"); return false; } LogUtils.LogDebug("Loaded XRGeneralSettings!"); return InitializeXRSDKLoaders(val.Manager); } private static XRGeneralSettings LoadXRSettingsFromAssetBundle() { string text = Path.Combine(Application.streamingAssetsPath, "xrmanager"); LogUtils.LogDebug("Loading XR Settings from AssetBundle: " + text); AssetBundle val = AssetBundle.LoadFromFile(text); Object[] array = val.LoadAllAssets(); foreach (Object val2 in array) { LogUtils.LogDebug("XRManagement Asset Loaded: " + val2.name); } XRGeneralSettings instance = XRGeneralSettings.Instance; if ((Object)(object)instance == (Object)null) { LogUtils.LogError("XRGeneralSettings Instance is null!"); return null; } LogUtils.LogDebug("XRGeneralSettings Instance is non-null."); return instance; } private static bool InitializeXRSDKLoaders(XRManagerSettings managerSettings) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) LogUtils.LogDebug("Initializing XRSDK Loaders..."); if ((Object)(object)managerSettings == (Object)null) { LogUtils.LogError("XRManagerSettings instance is null, cannot initialize loader."); return false; } int num = 0; do { managerSettings.InitializeLoaderSync(); num++; } while ((Object)(object)managerSettings.activeLoader == (Object)null && num < VHVRConfig.MaxVRInitializationTries()); if ((Object)(object)managerSettings.activeLoader == (Object)null) { LogUtils.LogError("managerSettings.activeLoader is null after " + num + " tries."); return false; } OpenVRSettings settings = OpenVRSettings.GetSettings(false); if ((Object)(object)settings != (Object)null) { MirrorViewModes mirrorViewMode = VHVRConfig.GetMirrorViewMode(); LogUtils.LogInfo("Mirror View Mode: " + ((object)(MirrorViewModes)(ref mirrorViewMode)).ToString()); settings.SetMirrorViewMode(mirrorViewMode); } LogUtils.LogDebug("Got non-null Active Loader."); return true; } public static void tryRecenter() { if (VRPlayer.ShouldPauseMovement) { return; } List<XRInputSubsystem> list = new List<XRInputSubsystem>(); SubsystemManager.GetInstances<XRInputSubsystem>(list); foreach (XRInputSubsystem item in list) { LogUtils.LogDebug("Recentering Input Subsystem: " + (object)item); item.TryRecenter(); } VRPlayer.headPositionInitialized = false; VRPlayer.vrPlayerInstance?.ResetRoomscaleCamera(); } private static void PrintSteamVRSettings() { SteamVR_Settings instance = SteamVR_Settings.instance; if ((Object)(object)instance == (Object)null) { LogUtils.LogWarning("SteamVR Settings are null."); return; } LogUtils.LogDebug("SteamVR Settings:"); LogUtils.LogDebug(" actionsFilePath: " + instance.actionsFilePath); LogUtils.LogDebug(" editorAppKey: " + instance.editorAppKey); LogUtils.LogDebug(" activateFirstActionSetOnStart: " + instance.activateFirstActionSetOnStart); LogUtils.LogDebug(" autoEnableVR: " + instance.autoEnableVR); LogUtils.LogDebug(" inputUpdateMode: " + ((object)(SteamVR_UpdateModes)(ref instance.inputUpdateMode)).ToString()); LogUtils.LogDebug(" legacyMixedRealityCamera: " + instance.legacyMixedRealityCamera); LogUtils.LogDebug(" mixedRealityCameraPose: " + (object)instance.mixedRealityCameraPose); LogUtils.LogDebug(" lockPhysicsUpdateRateToRenderFrequency: " + instance.lockPhysicsUpdateRateToRenderFrequency); LogUtils.LogDebug(" mixedRealityActionSetAutoEnable: " + instance.mixedRealityActionSetAutoEnable); LogUtils.LogDebug(" mixedRealityCameraInputSource: " + ((object)(SteamVR_Input_Sources)(ref instance.mixedRealityCameraInputSource)).ToString()); LogUtils.LogDebug(" mixedRealityCameraPose: " + (object)instance.mixedRealityCameraPose); LogUtils.LogDebug(" pauseGameWhenDashboardVisible: " + instance.pauseGameWhenDashboardVisible); LogUtils.LogDebug(" poseUpdateMode: " + ((object)(SteamVR_UpdateModes)(ref instance.poseUpdateMode)).ToString()); LogUtils.LogDebug(" previewHandLeft: " + (object)instance.previewHandLeft); LogUtils.LogDebug(" previewHandRight: " + (object)instance.previewHandRight); LogUtils.LogDebug(" steamVRInputPath: " + instance.steamVRInputPath); } private static void PrintOpenVRSettings() { OpenVRSettings settings = OpenVRSettings.GetSettings(false); if ((Object)(object)settings == (Object)null) { LogUtils.LogWarning("OpenVRSettings are null."); return; } LogUtils.LogDebug("OpenVR Settings:"); LogUtils.LogDebug(" StereoRenderingMode: " + ((object)(StereoRenderingModes)(ref settings.StereoRenderingMode)).ToString()); LogUtils.LogDebug(" InitializationType: " + ((object)(InitializationTypes)(ref settings.InitializationType)).ToString()); LogUtils.LogDebug(" ActionManifestFileRelativeFilePath: " + settings.ActionManifestFileRelativeFilePath); LogUtils.LogDebug(" MirrorView: " + ((object)(MirrorViewModes)(ref settings.MirrorView)).ToString()); } private static void PrintUnityXRSettings() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_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_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) LogUtils.LogDebug("Unity.XR.XRSettings: "); LogUtils.LogDebug(" enabled: " + XRSettings.enabled); TextureDimension deviceEyeTextureDimension = XRSettings.deviceEyeTextureDimension; LogUtils.LogDebug(" deviceEyeTextureDimension: " + ((object)(TextureDimension)(ref deviceEyeTextureDimension)).ToString()); RenderTextureDescriptor eyeTextureDesc = XRSettings.eyeTextureDesc; LogUtils.LogDebug(" eyeTextureDesc: " + ((object)(RenderTextureDescriptor)(ref eyeTextureDesc)).ToString()); LogUtils.LogDebug(" eyeTextureHeight: " + XRSettings.eyeTextureHeight); LogUtils.LogDebug(" eyeTextureResolutionScale: " + XRSettings.eyeTextureResolutionScale); LogUtils.LogDebug(" eyeTextureWidth: " + XRSettings.eyeTextureWidth); GameViewRenderMode gameViewRenderMode = XRSettings.gameViewRenderMode; LogUtils.LogDebug(" gameViewRenderMode: " + ((object)(GameViewRenderMode)(ref gameViewRenderMode)).ToString()); LogUtils.LogDebug(" isDeviceActive: " + XRSettings.isDeviceActive); LogUtils.LogDebug(" loadedDeviceName: " + XRSettings.loadedDeviceName); LogUtils.LogDebug(" occlusionMaskScale: " + XRSettings.occlusionMaskScale); LogUtils.LogDebug(" renderViewportScale: " + XRSettings.renderViewportScale); LogUtils.LogDebug(" showDeviceView: " + XRSettings.showDeviceView); StereoRenderingMode stereoRenderingMode = XRSettings.stereoRenderingMode; LogUtils.LogDebug(" stereoRenderingMode: " + ((object)(StereoRenderingMode)(ref stereoRenderingMode)).ToString()); LogUtils.LogDebug(" supportedDevices: " + XRSettings.supportedDevices); LogUtils.LogDebug(" useOcclusionMesh: " + XRSettings.useOcclusionMesh); } } internal class VRPlayer : MonoBehaviour { private enum HeadZoomLevel { FirstPerson, ThirdPerson0, ThirdPerson1, ThirdPerson2, ThirdPerson3 } private static readonly string PLAYER_PREFAB_NAME = "ValheimVRPlayer"; private static readonly string START_SCENE = "start"; public static readonly string RIGHT_HAND = "RightHand"; public static readonly string LEFT_HAND = "LeftHand"; private const float MAX_ROOMSCALE_MOVEMENT_SPEED = 4f; private static Vector3 FIRST_PERSON_OFFSET = Vector3.zero; private static float CROUCH_HEIGHT_ADJUST = -0.4f; private static float RIDE_HEIGHT_ADJUST = -0.85f; private static float SIT_ATTACH_HEIGHT_ADJUST = -0.4f; private static float SIT_HEIGHT_ADJUST = -0.7f; private static Vector3 THIRD_PERSON_0_OFFSET = new Vector3(0f, 1f, -0.6f); private static Vector3 THIRD_PERSON_1_OFFSET = new Vector3(0f, 1.4f, -1.5f); private static Vector3 THIRD_PERSON_2_OFFSET = new Vector3(0f, 1.9f, -2.6f); private static Vector3 THIRD_PERSON_3_OFFSET = new Vector3(0f, 3.2f, -4.4f); private static Vector3 THIRD_PERSON_CONFIG_OFFSET = Vector3.zero; private const float NECK_OFFSET = 0.2f; public const float ROOMSCALE_STEP_ANIMATION_SMOOTHING = 0.3f; public const float ROOMSCALE_ANIMATION_WEIGHT = 2f; private static VRIK _vrik; private static bool _isRoomscaleSneaking = false; private static GameObject _prefab; private static GameObject _instance; private static VRPlayer _vrPlayerInstance; private static HeadZoomLevel _headZoomLevel = HeadZoomLevel.FirstPerson; private Camera _vrCam; private Camera _handsCam; private Camera _skyboxCam; private Camera _thirdPersonCamera; private Transform _vrCameraRig; private Vector3 _lastCamPosition = Vector3.zero; private Vector3 _lastPlayerPosition = Vector3.zero; private Vector3 _lastPlayerAttachmentPosition = Vector3.zero; private FadeToBlackManager _fadeManager; private float _forwardSmoothVel = 0f; private float _sideSmoothVel = 0f; private static float _roomscaleAnimationForwardSpeed = 0f; private static float _roomscaleAnimationSideSpeed = 0f; private static SteamVR_LaserPointer _leftPointer; private static SteamVR_LaserPointer _rightPointer; private string _preferredHand; private Vector3 roomLocalPositionBeforeDodge; private Transform _dodgingRoom; private bool pausedMovement = false; private float timerLeft; private float timerRight; public static bool attachedToPlayer = false; private static float FIRST_PERSON_HEIGHT_OFFSET = 0f; private static bool _headPositionInitialized = false; public static VRIK vrikRef => _vrik; public static float referencePlayerHeight { get; private set; } public static bool isRoomscaleSneaking => _isRoomscaleSneaking; public static float roomscaleAnimationForwardSpeed => _roomscaleAnimationForwardSpeed; public static float roomscaleAnimationSideSpeed => _roomscaleAnimationSideSpeed; public static Vector3 roomscaleMovement { get; private set; } public bool wasDodging { get; private set; } = false; public static GesturedLocomotionManager gesturedLocomotionManager { get; private set; } = null; private Transform dodgingRoom => ((Object)(object)_dodgingRoom == (Object)null) ? (_dodgingRoom = new GameObject().transform) : _dodgingRoom; public static Hand leftHand { get; private set; } public static Hand rightHand { get; private set; } public static Transform leftHandBone { get; private set; } public static Transform rightHandBone { get; private set; } public static Hand dominantHand => VHVRConfig.LeftHanded() ? leftHand : rightHand; public static bool ShouldPauseMovement => PlayerCustomizaton.IsBarberGuiVisible() || (Menu.IsVisible() && !VHVRConfig.AllowMovementWhenInMenu()); public static bool IsClickableGuiOpen => Hud.IsPieceSelectionVisible() || StoreGui.IsVisible() || InventoryGui.IsVisible() || Menu.IsVisible() || (Object.op_Implicit((Object)(object)TextViewer.instance) && TextViewer.instance.IsVisible()) || Minimap.IsOpen(); public static PhysicsEstimator leftHandPhysicsEstimator { get { PhysicsEstimator physicsEstimator = ((Component)leftHand).gameObject.GetComponent<PhysicsEstimator>(); if ((Object)(object)physicsEstimator == (Object)null && attachedToPlayer) { physicsEstimator = ((Component)leftHand).gameObject.AddComponent<PhysicsEstimator>(); physicsEstimator.UseVrHandControllerPhysics(leftHand); PhysicsEstimator physicsEstimator2 = physicsEstimator; Camera camera = CameraUtils.getCamera("VRCamera"); physicsEstimator2.refTransform = ((camera != null) ? ((Component)camera).transform.parent : null); } return physicsEstimator; } } public static PhysicsEstimator rightHandPhysicsEstimator { get { PhysicsEstimator physicsEstimator = ((Component)rightHand).gameObject.GetComponent<PhysicsEstimator>(); if ((Object)(object)physicsEstimator == (Object)null && attachedToPlayer) { physicsEstimator = ((Component)rightHand).gameObject.AddComponent<PhysicsEstimator>(); physicsEstimator.UseVrHandControllerPhysics(rightHand); PhysicsEstimator physicsEstimator2 = physicsEstimator; Camera camera = CameraUtils.getCamera("VRCamera"); physicsEstimator2.refTransform = ((camera != null) ? ((Component)camera).transform.parent : null); } return physicsEstimator; } } public static PhysicsEstimator headPhysicsEstimator { get { Camera camera = CameraUtils.getCamera("VRCamera"); if ((Object)(object)camera == (Object)null) { return null; } PhysicsEstimator physicsEstimator = ((Component)camera).GetComponent<PhysicsEstimator>(); if ((Object)(object)physicsEstimator == (Object)null && attachedToPlayer) { physicsEstimator = ((Component)camera).gameObject.AddComponent<PhysicsEstimator>(); physicsEstimator.refTransform = ((Component)camera).transform.parent; } return physicsEstimator; } } public static SteamVR_Input_Sources dominantHandInputSource => (SteamVR_Input_Sources)(VHVRConfig.LeftHanded() ? 1 : 2); public static SteamVR_Input_Sources nonDominantHandInputSource => (SteamVR_Input_Sources)((!VHVRConfig.LeftHanded()) ? 1 : 2); public static bool handsActive => handIsActive(leftHand, _leftPointer) && handIsActive(rightHand, _rightPointer); public static SteamVR_LaserPointer leftPointer => _leftPointer; public static SteamVR_LaserPointer rightPointer => _rightPointer; public static Vector3 dominantHandRayDirection { get { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) SteamVR_LaserPointer val = (VHVRConfig.LeftHanded() ? leftPointer : rightPointer); Vector3 val2 = val.rayDirection * Vector3.forward; return ((Vector3)(ref val2)).normalized; } } public static SteamVR_LaserPointer activePointer { get { if ((Object)(object)leftPointer != (Object)null && leftPointer.pointerIsActive()) { return leftPointer; } if ((Object)(object)rightPointer != (Object)null && rightPointer.pointerIsActive()) { return rightPointer; } return null; } } public static bool inFirstPerson => _headZoomLevel == HeadZoomLevel.FirstPerson && attachedToPlayer; public static bool isMoving { get { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Player.m_localPlayer != (Object)null && attachedToPlayer) { Vector3 val = ((Character)Player.m_localPlayer).GetVelocity(); if (Object.op_Implicit((Object)(object)((Character)Player.m_localPlayer).m_lastGroundBody)) { val -= ((Character)Player.m_localPlayer).m_lastGroundBody.velocity; } return ((Vector3)(ref val)).magnitude > 0.5f; } return false; } } public static bool inImmersiveDodge { get { if (!VHVRConfig.ImmersiveDodgeRoll() || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)vrPlayerInstance == (Object)null) { return false; } return ((Character)Player.m_localPlayer).InDodge() || vrPlayerInstance.wasDodging; } } public static GameObject instance => _instance; public static VRPlayer vrPlayerInstance => _vrPlayerInstance; public static bool headPositionInitialized { get { return _headPositionInitialized; } set { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) _headPositionInitialized = value; if (!_headPositionInitialized) { FIRST_PERSON_HEIGHT_OFFSET = 0f; FIRST_PERSON_OFFSET = Vector3.zero; } } } private void Awake() { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) _vrPlayerInstance = this; _prefab = VRAssetManager.GetAsset<GameObject>(PLAYER_PREFAB_NAME); _preferredHand = VHVRConfig.GetPreferredHand(); headPositionInitialized = false; FIRST_PERSON_OFFSET = Vector3.zero; THIRD_PERSON_CONFIG_OFFSET = VHVRConfig.GetThirdPersonHeadOffset(); ensurePlayerInstance(); ((Component)this).gameObject.AddComponent<VRControls>(); } private void Update() { if (ensurePlayerInstance()) { maybeUpdateHeadPosition(); attachVrPlayerToWorldObject(); enableCameras(); checkAndSetHandsAndPointers(); updateVrik(); maybeMoveVRPlayerDuringDodge(); UpdateAmplifyOcclusionStatus(); Pose.checkInteractions(); CheckSneakRoomscale(); MountedAttackUtils.CheckMountedMagicAndCrossbowAttack(); if (timerLeft > 0f) { timerLeft -= Time.deltaTime; leftHand.hapticAction.Execute(0f, 0.1f, 20f, 0.1f, (SteamVR_Input_Sources)1); } if (timerRight > 0f) { timerRight -= Time.deltaTime; rightHand.hapticAction.Execute(0f, 0.1f, 20f, 0.1f, (SteamVR_Input_Sources)2); } } } private void OnRenderObject() { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)leftHandBone) && Object.op_Implicit((Object)(object)_vrik?.references?.leftHand)) { leftHandBone.SetPositionAndRotation(_vrik.references.leftHand.position, _vrik.references.leftHand.rotation); } if (Object.op_Implicit((Object)(object)rightHandBone) && Object.op_Implicit((Object)(object)_vrik?.references?.rightHand)) { rightHandBone.SetPositionAndRotation(_vrik.references.rightHand.position, _vrik.references.rightHand.rotation); } } private void OnDestroy() { if ((Object)(object)_dodgingRoom != (Object)null) { Object.Destroy((Object)(object)((Component)_dodgingRoom).gameObject); } } private void FixedUpdate() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) if (ShouldPauseMovement) { if (vrikEnabled() && !pausedMovement) { VrikCreator.PauseLocalPlayerVrik(); pausedMovement = true; } } else { if (vrikEnabled() && pausedMovement) { Transform vrCameraRig = _vrCameraRig; vrCameraRig.localPosition -= Vector3.ProjectOnPlane(((Component)_vrCam).transform.localPosition - _lastCamPosition, Vector3.up); _lastCamPosition = ((Component)_vrCam).transform.localPosition; VrikCreator.UnpauseLocalPlayerVrik(); pausedMovement = false; } if (inFirstPerson) { if (VHVRConfig.CharaterMovesWithHeadset()) { DoRoomScaleMovement(Time.fixedDeltaTime); } gesturedLocomotionManager?.UpdateMovementFromGestures(Time.fixedDeltaTime); } else { roomscaleMovement = Vector3.zero; } } UpdateThirdPersonCamera(); } private void UpdateThirdPersonCamera() { if ((Object)(object)_thirdPersonCamera == (Object)null) { if (!VHVRConfig.UseThirdPersonCameraOnFlatscreen()) { return; } enableThirdPersonCamera(); if ((Object)(object)_thirdPersonCamera == (Object)null) { return; } } ((Component)_thirdPersonCamera).gameObject.SetActive(VHVRConfig.UseThirdPersonCameraOnFlatscreen()); } private static void UpdateTrackedPoseDriverPoseSource() { //IL_0040: Unknown result type (might be due to invalid IL or missing references) Transform hmdTransform = Player.instance.hmdTransform; TrackedPoseDriver component = ((Component)hmdTransform).gameObject.GetComponent<TrackedPoseDriver>(); if ((Object)(object)component == (Object)null) { LogUtils.LogWarning("Null TrackedPoseDriver on HMD transform."); return; } LogUtils.LogInfo("Setting TrackedPoseDriver.poseSource to Head."); component.SetPoseSource(component.deviceType, (TrackedPose)3); } private void maybeUpdateHeadPosition() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) if (VHVRConfig.AllowHeadRepositioning()) { if (Input.GetKeyDown(VHVRConfig.GetHeadForwardKey())) { updateHeadOffset(new Vector3(0f, 0f, 0.1f)); } if (Input.GetKeyDown(VHVRConfig.GetHeadBackwardKey())) { updateHeadOffset(new Vector3(0f, 0f, -0.1f)); } if (Input.GetKeyDown(VHVRConfig.GetHeadLeftKey())) { updateHeadOffset(new Vector3(-0.1f, 0f, 0f)); } if (Input.GetKeyDown(VHVRConfig.GetHeadRightKey())) { updateHeadOffset(new Vector3(0.1f, 0f, 0f)); } if (Input.GetKeyDown(VHVRConfig.GetHeadUpKey())) { updateHeadOffset(new Vector3(0f, 0.1f, 0f)); } if (Input.GetKeyDown(VHVRConfig.GetHeadDownKey())) { updateHeadOffset(new Vector3(0f, -0.1f, 0f)); } } } private void updateHeadOffset(Vector3 offset) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (attachedToPlayer) { if (inFirstPerson) { FIRST_PERSON_OFFSET += offset; return; } THIRD_PERSON_CONFIG_OFFSET += offset; VHVRConfig.UpdateThirdPersonHeadOffset(THIRD_PERSON_CONFIG_OFFSET); } } private void UpdateAmplifyOcclusionStatus() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_vrCam == (Object)null) && !((Object)(object)((Component)_vrCam).gameObject.GetComponent<AmplifyOcclusionEffect>() == (Object)null)) { AmplifyOcclusionEffect component = ((Component)_vrCam).gameObject.GetComponent<AmplifyOcclusionEffect>(); component.SampleCount = (SampleCountLevel)1; ((Behaviour)component).enabled = VHVRConfig.UseAmplifyOcclusion(); } } private void checkAndSetHandsAndPointers() { tryInitializeHands(); if ((Object)(object)leftHand != (Object)null) { ((Behaviour)leftHand).enabled = VHVRConfig.UseVrControls(); leftHand.SetVisibility(((Behaviour)leftHand).enabled && !vrikEnabled()); } if ((Object)(object)rightHand != (Object)null) { ((Behaviour)rightHand).enabled = VHVRConfig.UseVrControls(); rightHand.SetVisibility(((Behaviour)rightHand).enabled && !vrikEnabled()); } if (handIsActive(leftHand, _leftPointer) && handIsActive(rightHand, _rightPointer)) { if (_preferredHand == LEFT_HAND) { setPointerActive(_leftPointer, active: true); setPointerActive(_rightPointer, active: false); } else { setPointerActive(_rightPointer, active: true); setPointerActive(_leftPointer, active: false); } } else if (handIsActive(rightHand, _rightPointer)) { setPointerActive(_rightPointer, active: true); setPointerActive(_leftPointer, active: false); } else if (handIsActive(leftHand, _leftPointer)) { setPointerActive(_leftPointer, active: true); setPointerActive(_rightPointer, active: false); } else { setPointerActive(_leftPointer, active: false); setPointerActive(_rightPointer, active: false); } } private void tryInitializeHands() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)leftHand == (Object)null || (Object)(object)_leftPointer == (Object)null) { leftHand = getHand(LEFT_HAND, _instance); if ((Object)(object)leftHand != (Object)null) { (leftHandBone = new GameObject().transform).parent = ((Component)leftHand).transform; _leftPointer = ((Component)leftHand).GetComponent<SteamVR_LaserPointer>(); if ((Object)(object)_leftPointer != (Object)null) { _leftPointer.raycastLayerMask = LayerUtils.UI_PANEL_LAYER_MASK; } } } if (!((Object)(object)rightHand == (Object)null) && !((Object)(object)_rightPointer == (Object)null)) { return; } rightHand = getHand(RIGHT_HAND, _instance); if ((Object)(object)rightHand != (Object)null) { (rightHandBone = new GameObject().transform).parent = ((Component)rightHand).transform; _rightPointer = ((Component)rightHand).GetComponent<SteamVR_LaserPointer>(); if ((Object)(object)_rightPointer != (Object)null) { _rightPointer.raycastLayerMask = LayerUtils.UI_PANEL_LAYER_MASK; } } } private void setPointerActive(SteamVR_LaserPointer p, bool active) { if (!((Object)(object)p == (Object)null)) { p.setUsePointer(active && shouldLaserPointersBeActive()); p.setVisible(p.pointerIsActive() && Cursor.visible); } } private bool shouldLaserPointersBeActive() { bool flag = (Object)(object)getPlayerCharacter() != (Object)null && ((Character)getPlayerCharacter()).InPlaceMode(); return VHVRConfig.UseVrControls() && (Cursor.visible || flag); } private static bool handIsActive(Hand h, SteamVR_LaserPointer p) { if ((Object)(object)h == (Object)null || (Object)(object)p == (Object)null) { return false; } return ((Behaviour)h).enabled && h.isActive && h.isPoseValid; } private Hand getHand(string hand, GameObject playerInstance) { Hand[] componentsInChildren = playerInstance.GetComponentsInChildren<Hand>(); foreach (Hand val in componentsInChildren) { if (((Object)((Component)val).gameObject).name == hand) { return val; } } return null; } private bool ensurePlayerInstance() { if ((Object)(object)_instance == (Object)null) { if ((Object)(object)_prefab == (Object)null) { LogUtils.LogError("SteamVR Player Prefab is not loaded!"); return false; } _instance = Object.Instantiate<GameObject>(_prefab); if ((Object)(object)_instance != (Object)null) { DisableRigidBodies(_instance); UpdateTrackedPoseDriverPoseSource(); } } return (Object)(object)_instance != (Object)null; } private void enableCameras() { if ((Object)(object)_vrCam == (Object)null || !((Behaviour)_vrCam).enabled) { if ((Object)(object)_thirdPersonCamera != (Object)null) { Object.Destroy((Object)(object)_thirdPersonCamera); } enableVrCamera(); } else { _vrCam.nearClipPlane = VHVRConfig.GetNearClipPlane(); } if ((Object)(object)_handsCam == (Object)null || !((Behaviour)_handsCam).enabled) { enableHandsCamera(); } if ((Object)(object)_skyboxCam == (Object)null || !((Behaviour)_skyboxCam).enabled) { enableSkyboxCamera(); } } private void enableVrCamera() { if ((Object)(object)_instance == (Object)null) { LogUtils.LogError("Cannot enable VR Camera with null SteamVR Player instance."); return; } Camera camera = CameraUtils.getCamera("Main Camera"); if ((Object)(object)camera == (Object)null) { LogUtils.LogError("Main Camera is null."); return; } Camera camera2 = CameraUtils.getCamera("VRCamera"); CameraUtils.copyCamera(camera, camera2); maybeCopyPostProcessingEffects(camera2, camera); maybeAddAmplifyOcclusion(camera2); camera2.nearClipPlane = VHVRConfig.GetNearClipPlane(); camera2.cullingMask &= ~(1 << LayerUtils.getUiPanelLayer()); camera2.cullingMask &= ~(1 << LayerMask.NameToLayer("UI")); camera2.cullingMask &= ~(1 << LayerUtils.getHandsLayer()); camera2.cullingMask &= ~(1 << LayerUtils.getWorldspaceUiLayer()); camera2.cullingMask &= ~(1 << LayerUtils.CHARARCTER_TRIGGER); ((Behaviour)camera).enabled = false; AudioListener component = ((Component)camera).GetComponent<AudioListener>(); if ((Object)(object)component != (Object)null) { LogUtils.LogDebug("Destroying MainCamera AudioListener"); Object.DestroyImmediate((Object)(object)component); } _fadeManager = ((Component)camera2).gameObject.AddComponent<FadeToBlackManager>(); _instance.SetActive(true); ((Behaviour)camera2).enabled = true; _vrCam = camera2; _vrCameraRig = ((Component)camera2).transform.parent; gesturedLocomotionManager = new GesturedLocomotionManager(); _fadeManager.OnFadeToWorld += delegate { headPositionInitialized = false; vrPlayerInstance?.ResetRoomscaleCamera(); }; } private void enableHandsCamera() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown Camera camera = CameraUtils.getCamera("VRCamera"); if (!((Object)(object)camera == (Object)null) && !((Object)(object)((Component)camera).gameObject == (Object)null)) { LogUtils.LogDebug("Enabling Hands Camera"); GameObject val = new GameObject("VRHandsCamera"); Camera val2 = val.AddComponent<Camera>(); val2.CopyFrom(CameraUtils.getCamera("VRCamera")); val2.depth = 4f; val2.clearFlags = (CameraClearFlags)3; val2.cullingMask = LayerUtils.HANDS_LAYER_MASK; ((Component)val2).transform.SetParent(((Component)camera).transform); ((Behaviour)val2).enabled = true; _handsCam = val2; } } private void enableThirdPersonCamera() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) Camera camera = CameraUtils.getCamera("VRCamera"); if (!((Object)(object)camera == (Object)null) && !((Object)(object)((Component)camera).gameObject == (Object)null) && (!DisableFollowCameraOnDeathPatch.hasCharacterDied || attachedToPlayer)) { LogUtils.LogDebug("Enabling third person camera"); _thirdPersonCamera = new GameObject("FollowCamera").AddComponent<Camera>(); _thirdPersonCamera.CopyFrom(camera); _thirdPersonCamera.depth = 4f; Camera thirdPersonCamera = _thirdPersonCamera; thirdPersonCamera.cullingMask |= 1 << LayerUtils.CHARARCTER_TRIGGER; _thirdPersonCamera.cullingMask = -1; ((Component)_thirdPersonCamera).transform.position = ((Component)camera).transform.position; _thirdPersonCamera.stereoTargetEye = (StereoTargetEyeMask)0; ((Component)_thirdPersonCamera).gameObject.AddComponent<ThirdPersonCameraUpdater>(); ((Behaviour)_thirdPersonCamera).enabled = true; _thirdPersonCamera.ResetAspect(); _thirdPersonCamera.fieldOfView = 75f; } } private void enableSkyboxCamera() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Camera camera = CameraUtils.getCamera("SkyboxCamera"); if (!((Object)(object)camera == (Object)null) && !((Object)(object)((Component)camera).gameObject == (Object)null)) { Camera camera2 = CameraUtils.getCamera("VRCamera"); if (!((Object)(object)camera2 == (Object)null) && !((Object)(object)((Component)camera2).gameObject == (Object)null)) { GameObject val = new GameObject("VRSkyboxCamera"); Camera val2 = val.AddComponent<Camera>(); val2.CopyFrom(camera); val2.depth = -2f; ((Component)val2).transform.SetParent(((Component)camera2).transform); ((Behaviour)camera).enabled = false; ((Behaviour)val2).enabled = true; _skyboxCam = val2; } } } private void attachVrPlayerToWorldObject() { if (shouldAttachToPlayerCharacter()) { updateZoomLevel(); attachVrPlayerToPlayerCharacter(); } else { attachVrPlayerToMainCamera(); } } private void updateZoomLevel() { if (canAdjustCameraDistance()) { float axis = Input.GetAxis("Mouse ScrollWheel"); if (axis > 0f) { zoomCamera(zoomIn: true); } else if (axis < 0f) { zoomCamera(zoomIn: false); } } } private void zoomCamera(bool zoomIn) { switch (_headZoomLevel) { case HeadZoomLevel.FirstPerson: _headZoomLevel = ((!zoomIn) ? HeadZoomLevel.ThirdPerson0 : HeadZoomLevel.FirstPerson); break; case HeadZoomLevel.ThirdPerson0: _headZoomLevel = ((!zoomIn) ? HeadZoomLevel.ThirdPerson1 : HeadZoomLevel.FirstPerson); break; case HeadZoomLevel.ThirdPerson1: _headZoomLevel = (zoomIn ? HeadZoomLevel.ThirdPerson0 : HeadZoomLevel.ThirdPerson2); break; case HeadZoomLevel.ThirdPerson2: _headZoomLevel = (zoomIn ? HeadZoomLevel.ThirdPerson1 : HeadZoomLevel.ThirdPerson3); break; case HeadZoomLevel.ThirdPerson3: _headZoomLevel = (zoomIn ? HeadZoomLevel.ThirdPerson2 : HeadZoomLevel.ThirdPerson3); break; } } private static Vector3 getHeadOffset(HeadZoomLevel headZoomLevel) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) return (Vector3)(headZoomLevel switch { HeadZoomLevel.FirstPerson => FIRST_PERSON_OFFSET, HeadZoomLevel.ThirdPerson0 => THIRD_PERSON_0_OFFSET + THIRD_PERSON_CONFIG_OFFSET, HeadZoomLevel.ThirdPerson1 => THIRD_PERSON_1_OFFSET + THIRD_PERSON_CONFIG_OFFSET, HeadZoomLevel.ThirdPerson2 => THIRD_PERSON_2_OFFSET + THIRD_PERSON_CONFIG_OFFSET, HeadZoomLevel.ThirdPerson3 => THIRD_PERSON_3_OFFSET + THIRD_PERSON_CONFIG_OFFSET, _ => FIRST_PERSON_OFFSET, }); } private bool canAdjustCameraDistance() { return !IsClickableGuiOpen && (!Object.op_Implicit((Object)(object)Chat.instance) || !Chat.instance.HasFocus()) && !Console.IsVisible() && attachedToPlayer && !((Character)getPlayerCharacter()).InCutscene() && !((Character)getPlayerCharacter()).InPlaceMode(); } private bool shouldAttachToPlayerCharacter() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) int result; if ((Object)(object)getPlayerCharacter() != (Object)null) { Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name != START_SCENE && ensurePlayerInstance() && !((Character)getPlayerCharacter()).InCutscene() && !((Character)getPlayerCharacter()).IsDead() && !((Character)getPlayerCharacter()).InBed()) { result = ((!PlayerCustomizaton.IsBarberGuiVisible()) ? 1 : 0); goto IL_0062; } } result = 0; goto IL_0062; IL_0062: return (byte)result != 0; } private void attachVrPlayerToPlayerCharacter() { //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: 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) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0163: 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_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) Player playerCharacter = getPlayerCharacter(); if ((Object)(object)playerCharacter == (Object)null) { LogUtils.LogError("Player character is null. Cannot attach!"); return; } if (!ensurePlayerInstance()) { LogUtils.LogError("SteamVR Player instance is null. Cannot attach!"); return; } _instance.transform.SetParent(((Component)playerCharacter).transform, false); attachedToPlayer = true; maybeExitDodge(); maybeInitHeadPosition(playerCharacter); float num = (inFirstPerson ? FIRST_PERSON_HEIGHT_OFFSET : 0f); setHeadVisibility(!inFirstPerson); _instance.transform.localPosition = getDesiredLocalPosition(playerCharacter) + (num + getHeadHeightAdjust(playerCharacter)) * Vector3.up; if (_headZoomLevel != 0) { Transform transform = _instance.transform; transform.localPosition += getHeadOffset(_headZoomLevel) + Vector3.forward * 0.2f; setPlayerVisualsOffset(((Component)playerCharacter).transform, Vector3.zero); } else { Vector3 val = -getHeadOffset(_headZoomLevel); setPlayerVisualsOffset(offset: (!((Character)playerCharacter).IsSitting()) ? (val - Vector3.forward * 0.2f) : (val + Vector3.forward * 0.0625f), playerTransform: ((Component)playerCharacter).transform); } } private void setPlayerVisualsOffset(Transform playerTransform, Vector3 offset) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < playerTransform.childCount; i++) { Transform child = playerTransform.GetChild(i); if (!((Object)(object)child == (Object)(object)_instance.transform) && !(((Object)child).name == "EyePos")) { playerTransform.GetChild(i).localPosition = offset; } } Transform val = vrikRef?.solver?.spine?.pelvisTarget; if ((Object)(object)val != (Object)null && VHVRConfig.UseVrControls() && !pausedMovement) { val.localRotation = getPelvisRotationRelativeToPlayer(playerTransform); vrikRef.solver.spine.maintainPelvisPosition = ((!attachedToPlayer) ? 1 : 0); vrikRef.solver.spine.pelvisRotationWeight = (attachedToPlayer ? 1 : 0); } } private Quaternion getPelvisRotationRelativeToPlayer(Transform playerTransform) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) if (GesturedLocomotionManager.isInUse && Mathf.Abs(gesturedLocomotionManager.stickOutputY) > 0.25f) { return Quaternion.identity; } Vector3 val = playerTransform.InverseTransformDirection(rightHandBone.TransformPoint(-Vector3.up * 0.25f) - leftHandBone.TransformPoint(-Vector3.up * 0.25f)); return Quaternion.LookRotation(new Vector3(0f - val.z, 0f, val.x + (((Character)getPlayerCharacter()).IsAttached() ? 1f : 0.5f))); } private float getHeadHeightAdjust(Player player) { if (((Character)player).IsRiding() || MountedAttackUtils.IsRidingMount()) { return RIDE_HEIGHT_ADJUST; } if (MountedAttackUtils.IsSteering()) { return SIT_ATTACH_HEIGHT_ADJUST; } if (((Character)player).IsSitting()) { return ((Character)player).IsAttached() ? SIT_ATTACH_HEIGHT_ADJUST : SIT_HEIGHT_ADJUST; } if (((Character)player).IsCrouching() && Player_SetControls_SneakPatch.isJoystickSneaking) { return CROUCH_HEIGHT_ADJUST; } return VHVRConfig.PlayerHeightAdjust(); } private void updateVrik() { Player playerCharacter = getPlayerCharacter(); if (!((Object)(object)playerCharacter == (Object)null)) { maybeAddVrik(playerCharacter); if ((Object)(object)_vrik != (Object)null) { ((Behaviour)_vrik).enabled = VHVRConfig.UseVrControls() && inFirstPerson && !((Character)playerCharacter).InDodge() && !((Character)playerCharacter).IsStaggering() && !playerCharacter.IsSleeping() && validVrikAnimatorState(((Component)playerCharacter).GetComponentInChildren<Animator>()); LeftHandQuickMenu.instance.UpdateWristBar(); RightHandQuickMenu.instance.UpdateWristBar(); } } } private void maybeExitDodge() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) Player playerCharacter = getPlayerCharacter(); if ((Object)(object)playerCharacter != (Object)null && !((Character)playerCharacter).InDodge() && wasDodging) { if (attachedToPlayer && VHVRConfig.ImmersiveDodgeRoll()) { Quaternion localRotation = ((Component)_vrCam).transform.localRotation; float y = ((Quaternion)(ref localRotation)).eulerAngles.y; Vector3 lookDir = _instance.transform.rotation * Quaternion.Euler(0f, y, 0f) * Vector3.forward; _vrCameraRig.localPosition = roomLocalPositionBeforeDodge; _vrCameraRig.localRotation = Quaternion.identity; ((Character)playerCharacter).m_lookDir = lookDir; playerCharacter.FaceLookDirection(); _instance.transform.localRotation = Quaternion.Euler(0f, 0f - y, 0f); _vrCam.nearClipPlane = VHVRConfig.GetNearClipPlane(); Transform vrCameraRig = _vrCameraRig; vrCameraRig.position += Vector3.ProjectOnPlane(((Component)playerCharacter).transform.position - ((Component)_vrCam).transform.position, _vrCameraRig.up); _lastCamPosition = ((Component)_vrCam).transform.localPosition; roomscaleMovement = Vector3.zero; } wasDodging = false; } } private void maybeMoveVRPlayerDuringDodge() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: 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_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)getPlayerCharacter() == (Object)null) && ((Character)getPlayerCharacter()).InDodge()) { if (!wasDodging) { roomLocalPositionBeforeDodge = _vrCameraRig.localPosition; dodgingRoom.parent = getHeadBone(); dodgingRoom.SetPositionAndRotation(_vrCameraRig.position, _vrCameraRig.rotation); _vrCam.nearClipPlane = 0.3f; wasDodging = true; } else if (attachedToPlayer && VHVRConfig.ImmersiveDodgeRoll()) { float dodgeExitSmoothener = GetDodgeExitSmoothener(); ((Component)_vrCameraRig).transform.position = Vector3.Lerp(dodgingRoom.position, _instance.transform.TransformPoint(roomLocalPositionBeforeDodge), dodgeExitSmoothener); ((Component)_vrCameraRig).transform.rotation = Quaternion.Slerp(dodgingRoom.rotation, _instance.transform.rotation, dodgeExitSmoothener); } } } private float GetDodgeExitSmoothener() { float num = 0.3f; return (UpdateDodgeVr.currdodgetimer > num) ? 0f : ((num - UpdateDodgeVr.currdodgetimer) / num); } private bool validVrikAnimatorState(Animator animator) { if ((Object)(object)animator == (Object)null) { return false; } return !animator.GetBool("wakeup"); } private void maybeAddVrik(Player player) { if (VHVRConfig.UseVrControls() && !((Object)(object)((Component)player).gameObject.GetComponent<VRIK>() != (Object)null)) { Camera camera = CameraUtils.getCamera("VRCamera"); _vrik = VrikCreator.initialize(((Component)player).gameObject, ((Component)leftHand).transform, ((Component)rightHand).transform, ((Component)camera).transform); VRPlayerSync component = ((Component)player).gameObject.GetComponent<VRPlayerSync>(); component.camera = ((Component)camera).gameObject; component.leftHand = ((Component)_vrik.solver.leftArm.target.parent).gameObject; component.rightHand = ((Component)_vrik.solver.rightArm.target.parent).gameObject; VrikCreator.resetVrikHandTransform((Humanoid)(object)player); HandGesture handGesture = ((Component)_vrik.references.leftHand).gameObject.AddComponent<HandGesture>(); HandGesture handGesture2 = ((Component)_vrik.references.rightHand).gameObject.AddComponent<HandGesture>(); handGesture.sourceHand = leftHand; handGesture2.sourceHand = rightHand; StaticObjects.leftFist().setColliderParent(leftHandBone, handGesture, isRightHand: false); StaticObjects.rightFist().setColliderParent(rightHandBone, handGesture2, isRightHand: true); ((Component)Player.m_localPlayer).gameObject.AddComponent<FistBlock>(); Reining reining = ((Component)Player.m_localPlayer).gameObject.AddComponent<Reining>(); reining.leftHandGesture = handGesture; reining.rightHandGesture = handGesture2; StaticObjects.mouthCollider(((Component)camera).transform); StaticObjects.addQuickMenus(); LeftHandQuickMenu.instance.refreshItems(); RightHandQuickMenu.instance.refreshItems(); } } private bool vrikEnabled() { Player playerCharacter = getPlayerCharacter(); if ((Object)(object)playerCharacter == (Object)null) { return false; } VRIK component = ((Component)playerCharacter).gameObject.GetComponent<VRIK>(); if ((Object)(object)component != (Object)null && (Object)(object)component != (Object)null) { return ((Behaviour)component).enabled && !Game.IsPaused(); } return false; } private void maybeInitHeadPosition(Player playerCharacter) { //IL_002d: 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) //IL_0058: 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_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) if (!headPositionInitialized && inFirstPerson && !((Character)playerCharacter).InDodge()) { _instance.transform.localPosition = getDesiredLocalPosition(playerCharacter); Transform hmdTransform = Player.instance.hmdTransform; FIRST_PERSON_HEIGHT_OFFSET = Vector3.Dot(_instance.transform.position - hmdTransform.position, ((Component)playerCharacter).transform.up); if (_headZoomLevel != 0) { Transform transform = _instance.transform; transform.localPosition += getHeadOffset(_headZoomLevel); } else { setPlayerVisualsOffset(((Component)playerCharacter).transform, -getHeadOffset(_headZoomLevel)); } if (VHVRConfig.UseLookLocomotion()) { Transform transform2 = _instance.transform; Quaternion localRotation = hmdTransform.localRotation; transform2.localRotation = Quaternion.Euler(0f, 0f - ((Quaternion)(ref localRotation)).eulerAngles.y, 0f); } if (PlayerCustomizaton.IsBarberGuiVisible()) { Transform transform3 = _instance.transform; transform3.localRotation *= Quaternion.Euler(0f, 180f, 0f); } headPositionInitialized = true; referencePlayerHeight = Player.instance.eyeHeight; } } private static Vector3 getDesiredLocalPosition(Player playerCharacter) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)playerCharacter == (Object)null) { return Vector3.zero; } Vector3 result = ((Component)playerCharacter).transform.InverseTransformPoint(((Character)playerCharacter).GetEyePoint()); result.x = (result.z = 0f); return result; } private void attachVrPlayerToMainCamera() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: 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_00a5: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_instance == (Object)null) { LogUtils.LogError("SteamVR Player instance is null while attaching to main camera!"); return; } Camera camera = CameraUtils.getCamera("Main Camera"); if ((Object)(object)camera == (Object)null) { LogUtils.LogError("Main camera not found."); return; } setHeadVisibility(isVisible: true); _instance.transform.parent = ((Component)camera).gameObject.transform; Vector3 position = ((Component)camera).gameObject.transform.position; if (PlayerCustomizaton.IsBarberGuiVisible() && Object.op_Implicit((Object)(object)getPlayerCharacter())) { position.y = ((Component)getPlayerCharacter()).transform.position.y; } _instance.transform.position = position; _instance.transform.rotation = ((Component)camera).gameObject.transform.rotation; attachedToPlayer = false; headPositionInitialized = false; } private void setHeadVisibility(bool isVisible) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (!VHVRConfig.UseVrControls()) { Transform headBone = getHeadBone(); if ((Object)(object)headBone != (Object)null) { headBone.localScale = (isVisible ? new Vector3(1f, 1f, 1f) : new Vector3(0.001f, 0.001f, 0.001f)); } } } private Transform getHeadBone() { Player playerCharacter = getPlayerCharacter(); if ((Object)(object)playerCharacter == (Object)null) { return null; } Animator componentInChildren = ((Component)playerCharacter).GetComponentInChildren<Animator>(); if ((Object)(object)componentInChildren == (Object)null) { return null; } return componentInChildren.GetBoneTransform((HumanBodyBones)10); } private void maybeAddAmplifyOcclusion(Camera vrCamera) { if (!((Object)(object)vrCamera == (Object)null)) { AmplifyOcclusionEffect component = ((Component)vrCamera).gameObject.GetComponent<AmplifyOcclusionEffect>(); if (!((Object)(object)component != (Object)null)) { ((Component)vrCamera).gameObject.AddComponent<AmplifyOcclusionEffect>(); } } } private void maybeCopyPostProcessingEffects(Camera vrCamera, Camera mainCamera) { //IL_0184: 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) if ((Object)(object)vrCamera == (Object)null || (Object)(object)mainCamera == (Object)null || (Object)(object)((Component)vrCamera).gameObject.GetComponent<PostProcessingBehaviour>() != (Object)null) { return; } PostProcessingBehaviour val = null; bool flag = false; PostProcessingBehaviour[] array = Object.FindObjectsOfType<PostProcessingBehaviour>(); foreach (PostProcessingBehaviour val2 in array) { if (((Object)val2).name == "Main Camera") { flag = true; val = ((Component)vrCamera).gameObject.AddComponent<PostProcessingBehaviour>(); LogUtils.LogDebug("Copying Main Camera PostProcessingBehaviour"); PostProcessingProfile profile = Object.Instantiate<PostProcessingProfile>(val2.profile); val.profile = profile; val.jitteredMatrixFunc = val2.jitteredMatrixFunc; if (((Behaviour)val2).enabled) { ((Behaviour)val2).enabled = false; } } } if (flag) { DepthOfField component = ((Component)mainCamera).gameObject.GetComponent<DepthOfField>(); DepthOfField dest = ((Component)vrCamera).gameObject.AddComponent<DepthOfField>(); if ((Object)(object)component != (Object)null) { CopyClassFields(component, ref dest); } SunShafts dest2 = ((Component)vrCamera).gameObject.AddComponent<SunShafts>(); SunShafts component2 = ((Component)mainCamera).gameObject.GetComponent<SunShafts>(); if ((Object)(object)component2 != (Object)null) { CopyClassFields(component2, ref dest2); } CameraEffects val3 = ((Component)vrCamera).gameObject.AddComponent<CameraEffects>(); CameraEffects component3 = ((Component)mainCamera).gameObject.GetComponent<CameraEffects>(); if ((Object)(object)component3 != (Object)null) { val3.m_forceDof = component3.m_forceDof; val3.m_dofRayMask = component3.m_dofRayMask; val3.m_dofAutoFocus = component3.m_dofAutoFocus; val3.m_dofMinDistance = component3.m_dofMinDistance; val3.m_dofMaxDistance = component3.m_dofMaxDistance; } ((Component)vrCamera).gameObject.AddComponent<UnderwaterEffectsUpdater>().Init(vrCamera, val, val.profile); } } private void CopyClassFields<T>(T source, ref T dest) { FieldInfo[] fields = source.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { object value = fieldInfo.GetValue(source); fieldInfo.SetValue(dest, value); } } private Player getPlayerCharacter() { return Player.m_localPlayer; } private static void DisableRigidBodies(GameObject root) { Rigidbody[] componentsInChildren = root.GetComponentsInChildren<Rigidbody>(); foreach (Rigidbody val in componentsInChildren) { ((Component)val).gameObject.SetActive(false); } SphereCollider[] componentsInChildren2 = root.GetComponentsInChildren<SphereCollider>(); foreach (SphereCollider val2 in componentsInChildren2) { ((Component)val2).gameObject.SetActive(false); } } private void CheckSneakRoomscale() { if (!VHVRConfig.RoomScaleSneakEnabled()) { _isRoomscaleSneaking = false; return; } Player playerCharacter = getPlayerCharacter(); if ((Object)(object)playerCharacter == (Object)null) { _isRoomscaleSneaking = false; return; } float eyeHeight = Player.instance.eyeHeight; float num = referencePlayerHeight * VHVRConfig.RoomScaleSneakHeight(); if (eyeHeight < num && !((Character)playerCharacter).IsSitting()) { _isRoomscaleSneaking = true; } else if (eyeHeight > num + num * 0.05f) { _isRoomscaleSneaking = false; } } private void DoRoomScaleMovement(float deltaTime) { //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) //IL_0058: 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_026b: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017c: 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_018b: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) Player playerCharacter = getPlayerCharacter(); if ((Object)(object)_vrCam == (Object)null || (Object)(object)playerCharacter == (Object)null || (Object)(object)((Component)playerCharacter).gameObject == (Object)null || ((Character)playerCharacter).IsAttached()) { return; } Vector3 val = ((Component)_vrCam).transform.localPosition - _lastCamPosition; val.y = 0f; float num = 0.005f; switch (EquipScript.getRight()) { case EquipType.None: case EquipType.Hammer: case EquipType.Tankard: case EquipType.Claws: case EquipType.Knife: case EquipType.DualKnives: if (GesturedLocomotionManager.isInUse || SteamVR_Actions.valheim_Grab.GetState((SteamVR_Input_Sources)0)) { num = 1f; } break; } bool flag = ((Vector3)(ref val)).magnitude > num; if (flag) { float num2 = deltaTime * 4f; if (((Vector3)(ref val)).magnitude > num2) { val = ((Vector3)(ref val)).normalized * num2; } if (VHVRConfig.RoomscaleFadeToBlack() && !_fadeManager.IsFadingToBlack) { Vector3 val2 = ((Character)playerCharacter).m_body.position - _lastPlayerPosition; if (Object.op_Implicit((Object)(object)((Character)playerCharacter).m_lastAttachBody) && _lastPlayerAttachmentPosition != Vector3.zero) { val2 -= ((Character)playerCharacter).m_lastAttachBody.position - _lastPlayerAttachmentPosition; } val2.y = 0f; Vector3 val3 = roomscaleMovement; if (((Vector3)(ref val3)).magnitude * 0.6f > ((Vector3)(ref val2)).magnitude) { SteamVR_Fade.Start(Color.black, 0f, false); SteamVR_Fade.Start(Color.clear, 1.5f, false); } _lastPlayerPosition = ((Character)playerCharacter).m_body.position; _lastPlayerAttachmentPosition = (Object.op_Implicit((Object)(object)((Character)playerCharacter).m_lastAttachBody) ? ((Character)playerCharacter).m_lastAttachBody.position : Vector3.zero); } _lastCamPosition += val; Vector3 val4 = _instance.transform.TransformVector(val); val4.y = 0f; roomscaleMovement = val4; Transform vrCameraRig = _vrCameraRig; vrCameraRig.localPosition -= val; } else { roomscaleMovement = Vector3.zero; } _roomscaleAnimationForwardSpeed = Mathf.SmoothDamp(_roomscaleAnimationForwardSpeed, flag ? (val.z / Time.fixedDeltaTime) : 0f, ref _forwardSmoothVel, 0.3f, 99f); _roomscaleAnimationSideSpeed = Mathf.SmoothDamp(_roomscaleAnimationSideSpeed, flag ? (val.x / Time.fixedDeltaTime) : 0f, ref _sideSmoothVel, 0.3f, 99f); } public void ResetRoomscaleCamera() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_vrCameraRig == (Object)null)) { Vector3 localPosition = ((Component)_vrCam).transform.localPosition; localPosition.y = 0f; _vrCameraRig.localPosition = -localPosition; _lastCamPosition = ((Component)_vrCam).transform.localPosition; } } public void TriggerHandVibration(float time) { timerLeft = time; timerRight = time; } } } namespace ValheimVRMod.VRCore.UI { public class ConfigSettings { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__27_0; public static UnityAction <>9__27_1; public static UnityAction<string> <>9__37_0; internal void <setupOkAndBack>b__27_0() { doSave = true; Object.Destroy((Object)(object)settings); } internal void <setupOkAndBack>b__27_1() { doSave = false; Object.Destroy((Object)(object)settings); } internal void <createTransformButton>b__37_0(string param) { } } private const bool ENABLE_VHVR_SETTINGS_DIALOG = true; private const float MENU_ENTRY_HEIGHT = 40f; private const string MenuName = "VHVR"; private const int TabButtonWidth = 100; private static GameObject tabButtonPrefab; private static GameObject controlSettingsPrefab; private static GameObject togglePrefab; private static GameObject sliderPrefab; private static GameObject chooserPrefab; private static GameObject settingsPrefab; private static GameObject keyBindingPrefab; private static GameObject transformButtonPrefab; private static GameObject settings; private static Transform menuList; private static Transform menuParent; private static ConfigComponent tmpComfigComponent; private static bool enableTransformButtons; private static int tabCounter; public static bool doSave; public static GameObject toolTip; public static KeyboardMouseSettings keyboardMouseSettings; public static void instantiate(Transform mList, Transform mParent, GameObject sPrefab, bool enableTransformButtons) { menuList = ((Component)((Component)mList).transform.Find("MenuEntries")).transform; menuParent = mParent; settingsPrefab = sPrefab; createMenuEntry(); generatePrefabs(); ConfigSettings.enableTransformButtons = enableTransformButtons; } private static void createMenuEntry() { //IL_0036: 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_004c: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: 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_007f: Expected O, but got Unknown //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) int num = 0; for (int i = 0; i < menuList.childCount; i++) { Transform child = menuList.GetChild(i); if (((Object)child).name == "Settings") { bool flag = true; AddMenuEntry("VHVR", child, Vector2.zero, new UnityAction(createModSettings)); num++; AddMenuEntry("Screenshot", child, Vector2.up * 40f * (float)num, new UnityAction(CaptureScreenshot)); num++; } else if (num > 0) { RectTransform component = ((Component)menuList.GetChild(i)).GetComponent<RectTransform>(); component.anchoredPosition += Vector2.up * 40f * (float)num; } } } private static void AddMenuEntry(string text, Transform original, Vector2 offsetFromOriginal, UnityAction onClick) { //IL_0059: 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_005f: Unknown result type (might be due to invalid IL or missing references) Transform val = Object.Instantiate<Transform>(original, menuList); ((TMP_Text)((Component)val).GetComponentInChildren<TextMeshProUGUI>()).text = text; ((UnityEventBase)((Component)val).GetComponent<Button>().onClick).SetPersistentListenerState(0, (UnityEventCallState)0); ((UnityEventBase)((Component)val).GetComponent<Button>().onClick).RemoveAllListeners(); ((UnityEvent)((Component)val).GetComponent<Button>().onClick).AddListener(onClick); RectTransform component = ((Component)val).GetComponent<RectTransform>(); component.anchoredPosition += offsetFromOriginal; } private static void generatePrefabs() { Transform val = settingsPrefab.transform.Find("Panel").Find("TabButtons"); if ((Object)(object)tabButtonPrefab == (Object)null) { tabButtonPrefab = createTabButtonPrefab(((Component)val.GetChild(0)).gameObject); } Transform val2 = settingsPrefab.transform.Find("Panel").Find("TabContent"); controlSettingsPrefab = ((Component)val2.Find("KeyboardMouse")).gameObject; togglePrefab = ((Component)controlSettingsPrefab.GetComponentInChildren<Toggle>()).gameObject; if ((Object)(object)sliderPrefab == (Object)null) { sliderPrefa
plugins/Valheim_Data/Managed/amplify_occlusion.dll
Decompiled 5 months agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using AmplifyOcclusion; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.XR; using Valve.VR; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] [ExecuteInEditMode] [AddComponentMenu("Image Effects/Amplify Occlusion")] [ImageEffectAllowedInSceneView] [RequireComponent(typeof(Camera))] public class AmplifyOcclusionEffect : MonoBehaviour { public enum ApplicationMethod { PostEffect, Deferred, Debug } public enum PerPixelNormalSource { None, Camera, GBuffer, GBufferOctaEncoded } private struct CmdBuffer { public CommandBuffer cmdBuffer; public CameraEvent cmdBufferEvent; public string cmdBufferName; } private static int m_nextID; private int m_myID; private string m_myIDstring; private float m_oneOverDepthScale = 1.5266243E-05f; [Header("Ambient Occlusion")] [Tooltip("How to inject the occlusion: Post Effect = Overlay, Deferred = Deferred Injection, Debug - Vizualize.")] public ApplicationMethod ApplyMethod; [Tooltip("Number of samples per pass.")] public SampleCountLevel SampleCount = SampleCountLevel.High; [Tooltip("Source of per-pixel normals: None = All, Camera = Forward, GBuffer = Deferred.")] public PerPixelNormalSource PerPixelNormals = PerPixelNormalSource.Camera; [Tooltip("Final applied intensity of the occlusion effect.")] [Range(0f, 1f)] public float Intensity = 1f; [Tooltip("Color tint for occlusion.")] public Color Tint = Color.black; [Tooltip("Radius spread of the occlusion.")] public float Radius = 2f; [Tooltip("Power exponent attenuation of the occlusion.")] [Range(0f, 16f)] public float PowerExponent = 1.8f; [Tooltip("Controls the initial occlusion contribution offset.")] [Range(0f, 0.99f)] public float Bias = 0.05f; [Tooltip("Controls the thickness occlusion contribution.")] [Range(0f, 1f)] public float Thickness = 1f; [Tooltip("Compute the Occlusion and Blur at half of the resolution.")] public bool Downsample = true; [Tooltip("Cache optimization for best performance / quality tradeoff.")] public bool CacheAware = true; [Header("Distance Fade")] [Tooltip("Control parameters at faraway.")] public bool FadeEnabled; [Tooltip("Distance in Unity unities that start to fade.")] public float FadeStart = 100f; [Tooltip("Length distance to performe the transition.")] public float FadeLength = 50f; [Tooltip("Final Intensity parameter.")] [Range(0f, 1f)] public float FadeToIntensity; public Color FadeToTint = Color.black; [Tooltip("Final Radius parameter.")] public float FadeToRadius = 2f; [Tooltip("Final PowerExponent parameter.")] [Range(0f, 16f)] public float FadeToPowerExponent = 1f; [Tooltip("Final Thickness parameter.")] [Range(0f, 1f)] public float FadeToThickness = 1f; [Header("Bilateral Blur")] public bool BlurEnabled = true; [Tooltip("Radius in screen pixels.")] [Range(1f, 4f)] public int BlurRadius = 3; [Tooltip("Number of times that the Blur will repeat.")] [Range(1f, 4f)] public int BlurPasses = 1; [Tooltip("Sharpness of blur edge-detection: 0 = Softer Edges, 20 = Sharper Edges.")] [Range(0f, 20f)] public float BlurSharpness = 15f; [Header("Temporal Filter")] [Tooltip("Accumulates the effect over the time.")] public bool FilterEnabled = true; public bool FilterDownsample = true; [Tooltip("Controls the accumulation decayment: 0 = More flicker with less ghosting, 1 = Less flicker with more ghosting.")] [Range(0f, 1f)] public float FilterBlending = 0.8f; [Tooltip("Controls the discard sensitivity based on the motion of the scene and objects.")] [Range(0f, 1f)] public float FilterResponse = 0.5f; private bool m_HDR = true; private bool m_MSAA = true; private PerPixelNormalSource m_prevPerPixelNormals; private ApplicationMethod m_prevApplyMethod; private bool m_prevDeferredReflections; private SampleCountLevel m_prevSampleCount; private bool m_prevDownsample; private bool m_prevCacheAware; private bool m_prevBlurEnabled; private int m_prevBlurRadius; private int m_prevBlurPasses; private bool m_prevFilterEnabled = true; private bool m_prevFilterDownsample = true; private bool m_prevHDR = true; private bool m_prevMSAA = true; private Camera m_targetCamera; private RenderTargetIdentifier[] applyDebugTargetsTemporal = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[2]; private RenderTargetIdentifier[] applyDeferredTargets_Log_Temporal = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[3]; private RenderTargetIdentifier[] applyDeferredTargetsTemporal = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[3]; private RenderTargetIdentifier[] applyOcclusionTemporal = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[2]; private RenderTargetIdentifier[] applyPostEffectTargetsTemporal = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[2]; private bool useMRTBlendingFallback; private bool checkedforMRTBlendingFallback; private CmdBuffer m_commandBuffer_Parameters; private CmdBuffer m_commandBuffer_Occlusion; private CmdBuffer m_commandBuffer_Apply; private static Mesh m_quadMesh; private static Material m_occlusionMat; private static Material m_blurMat; private static Material m_applyOcclusionMat; private RenderTextureFormat m_occlusionRTFormat = (RenderTextureFormat)13; private RenderTextureFormat m_accumTemporalRTFormat; private RenderTextureFormat m_temporaryEmissionRTFormat = (RenderTextureFormat)8; private RenderTextureFormat m_motionIntensityRTFormat = (RenderTextureFormat)16; private bool m_paramsChanged = true; private bool m_clearHistory = true; private RenderTexture m_occlusionDepthRT; private RenderTexture[] m_temporalAccumRT; private RenderTexture m_depthMipmap; private uint m_sampleStep; private uint m_curTemporalIdx; private uint m_prevTemporalIdx; private string[] m_tmpMipString; private int m_numberMips; private readonly RenderTargetIdentifier[] m_applyDeferredTargets = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[2] { RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)10), RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2) }; private readonly RenderTargetIdentifier[] m_applyDeferredTargets_Log = (RenderTargetIdentifier[])(object)new RenderTargetIdentifier[2] { RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)10), RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)13) }; private TargetDesc m_target; private AmplifyOcclusionViewProjMatrix m_viewProjMatrix = new AmplifyOcclusionViewProjMatrix(); private bool UsingTemporalFilter { get { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 if (m_sampleStep != 0 && FilterEnabled) { return (int)m_targetCamera.cameraType != 2; } return false; } } private bool UsingMotionVectors { get { if (UsingTemporalFilter) { return ApplyMethod != ApplicationMethod.Deferred; } return false; } } private bool UsingFilterDownsample { get { if (Downsample && FilterDownsample) { return UsingTemporalFilter; } return false; } } private void createCommandBuffer(ref CmdBuffer aCmdBuffer, string aCmdBufferName, CameraEvent aCameraEvent) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (aCmdBuffer.cmdBuffer != null) { cleanupCommandBuffer(ref aCmdBuffer); } aCmdBuffer.cmdBufferName = aCmdBufferName; aCmdBuffer.cmdBuffer = new CommandBuffer(); aCmdBuffer.cmdBuffer.name = aCmdBufferName; aCmdBuffer.cmdBufferEvent = aCameraEvent; m_targetCamera.AddCommandBuffer(aCameraEvent, aCmdBuffer.cmdBuffer); } private void cleanupCommandBuffer(ref CmdBuffer aCmdBuffer) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) CommandBuffer[] commandBuffers = m_targetCamera.GetCommandBuffers(aCmdBuffer.cmdBufferEvent); for (int i = 0; i < commandBuffers.Length; i++) { if (commandBuffers[i].name == aCmdBuffer.cmdBufferName) { m_targetCamera.RemoveCommandBuffer(aCmdBuffer.cmdBufferEvent, commandBuffers[i]); } } aCmdBuffer.cmdBufferName = null; aCmdBuffer.cmdBufferEvent = (CameraEvent)0; aCmdBuffer.cmdBuffer = null; } private void createQuadMesh() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_quadMesh == (Object)null) { m_quadMesh = new Mesh(); m_quadMesh.vertices = (Vector3[])(object)new Vector3[4] { new Vector3(0f, 0f, 0f), new Vector3(0f, 1f, 0f), new Vector3(1f, 1f, 0f), new Vector3(1f, 0f, 0f) }; m_quadMesh.uv = (Vector2[])(object)new Vector2[4] { new Vector2(0f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f), new Vector2(1f, 0f) }; m_quadMesh.triangles = new int[6] { 0, 1, 2, 0, 2, 3 }; m_quadMesh.normals = (Vector3[])(object)new Vector3[0]; m_quadMesh.tangents = (Vector4[])(object)new Vector4[0]; m_quadMesh.colors32 = (Color32[])(object)new Color32[0]; m_quadMesh.colors = (Color[])(object)new Color[0]; } } private void PerformBlit(CommandBuffer cb, Material mat, int pass) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) cb.DrawMesh(m_quadMesh, Matrix4x4.identity, mat, 0, pass); } private void checkMaterials(bool aThroughErrorMsg) { if ((Object)(object)m_occlusionMat == (Object)null) { m_occlusionMat = AmplifyOcclusionCommon.CreateMaterialWithShaderName("Hidden/Amplify Occlusion/Occlusion", aThroughErrorMsg); } if ((Object)(object)m_blurMat == (Object)null) { m_blurMat = AmplifyOcclusionCommon.CreateMaterialWithShaderName("Hidden/Amplify Occlusion/Blur", aThroughErrorMsg); } if ((Object)(object)m_applyOcclusionMat == (Object)null) { m_applyOcclusionMat = AmplifyOcclusionCommon.CreateMaterialWithShaderName("Hidden/Amplify Occlusion/Apply", aThroughErrorMsg); } if ((Object)(object)m_applyOcclusionMat != (Object)null && !checkedforMRTBlendingFallback) { checkedforMRTBlendingFallback = true; useMRTBlendingFallback = m_applyOcclusionMat.GetTag("MRTBlending", false).ToUpper() != "TRUE"; } } private bool checkRenderTextureFormats() { //IL_0013: 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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (SystemInfo.SupportsRenderTextureFormat((RenderTextureFormat)0) && SystemInfo.SupportsRenderTextureFormat((RenderTextureFormat)2)) { m_occlusionRTFormat = (RenderTextureFormat)13; if (!SystemInfo.SupportsRenderTextureFormat(m_occlusionRTFormat)) { m_occlusionRTFormat = (RenderTextureFormat)12; if (!SystemInfo.SupportsRenderTextureFormat(m_occlusionRTFormat)) { m_occlusionRTFormat = (RenderTextureFormat)2; } } return true; } return false; } private void OnEnable() { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Invalid comparison between Unknown and I4 //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Invalid comparison between Unknown and I4 m_myID = m_nextID; m_myIDstring = m_myID.ToString(); m_nextID++; if (!checkRenderTextureFormats()) { Debug.LogError((object)"[AmplifyOcclusion] Target platform does not meet the minimum requirements for this effect to work properly."); ((Behaviour)this).enabled = false; return; } if (CacheAware) { if (!SystemInfo.SupportsRenderTextureFormat((RenderTextureFormat)14)) { CacheAware = false; Debug.LogWarning((object)"[AmplifyOcclusion] System does not support RFloat RenderTextureFormat. CacheAware will be disabled."); } else if ((int)SystemInfo.copyTextureSupport == 0) { CacheAware = false; Debug.LogWarning((object)"[AmplifyOcclusion] System does not support CopyTexture. CacheAware will be disabled."); } else if ((int)SystemInfo.graphicsDeviceType == 8 || (int)SystemInfo.graphicsDeviceType == 11) { CacheAware = false; Debug.LogWarningFormat("[AmplifyOcclusion] CacheAware is not supported on {0} devices. CacheAware will be disabled.", new object[1] { SystemInfo.graphicsDeviceType }); } } checkMaterials(aThroughErrorMsg: false); createQuadMesh(); if (GraphicsSettings.HasShaderDefine(Graphics.activeTier, (BuiltinShaderDefine)17)) { m_oneOverDepthScale = 6.106497E-05f; } } private void Reset() { if (m_commandBuffer_Parameters.cmdBuffer != null) { cleanupCommandBuffer(ref m_commandBuffer_Parameters); } if (m_commandBuffer_Occlusion.cmdBuffer != null) { cleanupCommandBuffer(ref m_commandBuffer_Occlusion); } if (m_commandBuffer_Apply.cmdBuffer != null) { cleanupCommandBuffer(ref m_commandBuffer_Apply); } AmplifyOcclusionCommon.SafeReleaseRT(ref m_occlusionDepthRT); AmplifyOcclusionCommon.SafeReleaseRT(ref m_depthMipmap); releaseTemporalRT(); m_tmpMipString = null; } private void OnDisable() { Reset(); } private void releaseTemporalRT() { if (m_temporalAccumRT != null) { for (int i = 0; i < m_temporalAccumRT.Length; i++) { AmplifyOcclusionCommon.SafeReleaseRT(ref m_temporalAccumRT[i]); } } m_temporalAccumRT = null; } private void ClearHistory(CommandBuffer cb) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) m_clearHistory = false; if (m_temporalAccumRT != null && (Object)(object)m_occlusionDepthRT != (Object)null) { for (int i = 0; i < m_temporalAccumRT.Length; i++) { cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)m_temporalAccumRT[i])); PerformBlit(cb, m_occlusionMat, 34); } } } private void checkParamsChanged() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) bool allowHDR = m_targetCamera.allowHDR; bool flag = m_targetCamera.allowMSAA && (int)m_targetCamera.actualRenderingPath != 2 && (int)m_targetCamera.actualRenderingPath != 3 && QualitySettings.antiAliasing >= 1; int antiAliasing = ((!flag) ? 1 : QualitySettings.antiAliasing); if ((Object)(object)m_occlusionDepthRT != (Object)null && (((Texture)m_occlusionDepthRT).width != m_target.width || ((Texture)m_occlusionDepthRT).height != m_target.height || m_prevMSAA != flag || !m_occlusionDepthRT.IsCreated() || m_prevFilterEnabled != FilterEnabled || m_prevFilterDownsample != UsingFilterDownsample || (m_temporalAccumRT != null && (!m_temporalAccumRT[0].IsCreated() || !m_temporalAccumRT[1].IsCreated())))) { AmplifyOcclusionCommon.SafeReleaseRT(ref m_occlusionDepthRT); AmplifyOcclusionCommon.SafeReleaseRT(ref m_depthMipmap); releaseTemporalRT(); m_paramsChanged = true; } if (m_temporalAccumRT != null) { if (AmplifyOcclusionCommon.IsStereoMultiPassEnabled(m_targetCamera)) { if (m_temporalAccumRT.Length != 4) { m_temporalAccumRT = null; } } else if (m_temporalAccumRT.Length != 2) { m_temporalAccumRT = null; } } if ((Object)(object)m_occlusionDepthRT == (Object)null) { m_occlusionDepthRT = AmplifyOcclusionCommon.SafeAllocateRT("_AO_OcclusionDepthTexture", m_target.width, m_target.height, m_occlusionRTFormat, (RenderTextureReadWrite)1, (FilterMode)1); } if (m_temporalAccumRT == null && FilterEnabled) { if (AmplifyOcclusionCommon.IsStereoMultiPassEnabled(m_targetCamera)) { m_temporalAccumRT = (RenderTexture[])(object)new RenderTexture[4]; } else { m_temporalAccumRT = (RenderTexture[])(object)new RenderTexture[2]; } for (int i = 0; i < m_temporalAccumRT.Length; i++) { m_temporalAccumRT[i] = AmplifyOcclusionCommon.SafeAllocateRT("_AO_TemporalAccum_" + i, m_target.width, m_target.height, m_accumTemporalRTFormat, (RenderTextureReadWrite)1, (FilterMode)1, antiAliasing); } m_clearHistory = true; } if (CacheAware && (Object)(object)m_depthMipmap == (Object)null) { m_depthMipmap = AmplifyOcclusionCommon.SafeAllocateRT("_AO_DepthMipmap", m_target.fullWidth >> 1, m_target.fullHeight >> 1, (RenderTextureFormat)14, (RenderTextureReadWrite)1, (FilterMode)0, 1, aUseMipMap: true); int num = Mathf.Min(m_target.fullWidth, m_target.fullHeight); m_numberMips = (int)(Mathf.Log((float)num, 2f) + 1f) - 1; m_tmpMipString = null; m_tmpMipString = new string[m_numberMips]; for (int j = 0; j < m_numberMips; j++) { m_tmpMipString[j] = "_AO_TmpMip_" + j; } } else if (!CacheAware && (Object)(object)m_depthMipmap != (Object)null) { AmplifyOcclusionCommon.SafeReleaseRT(ref m_depthMipmap); m_tmpMipString = null; } if (m_prevSampleCount != SampleCount || m_prevDownsample != Downsample || m_prevCacheAware != CacheAware || m_prevBlurEnabled != BlurEnabled || ((m_prevBlurPasses != BlurPasses || m_prevBlurRadius != BlurRadius) && BlurEnabled) || m_prevFilterEnabled != FilterEnabled || m_prevFilterDownsample != UsingFilterDownsample || m_prevHDR != allowHDR || m_prevMSAA != flag) { m_clearHistory |= m_prevHDR != allowHDR; m_clearHistory |= m_prevMSAA != flag; m_HDR = allowHDR; m_MSAA = flag; m_paramsChanged = true; } } private void updateParams() { m_prevSampleCount = SampleCount; m_prevDownsample = Downsample; m_prevCacheAware = CacheAware; m_prevBlurEnabled = BlurEnabled; m_prevBlurPasses = BlurPasses; m_prevBlurRadius = BlurRadius; m_prevFilterEnabled = FilterEnabled; m_prevFilterDownsample = UsingFilterDownsample; m_prevHDR = m_HDR; m_prevMSAA = m_MSAA; m_paramsChanged = false; } private void Update() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Invalid comparison between Unknown and I4 //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: 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_0079: Invalid comparison between Unknown and I4 //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Invalid comparison between Unknown and I4 //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_targetCamera != (Object)null) { if ((int)m_targetCamera.actualRenderingPath != 3) { if (PerPixelNormals != 0 && PerPixelNormals != PerPixelNormalSource.Camera) { m_paramsChanged = true; PerPixelNormals = PerPixelNormalSource.Camera; if ((int)m_targetCamera.cameraType != 2) { Debug.LogWarning((object)"[AmplifyOcclusion] GBuffer Normals only available in Camera Deferred Shading mode. Switched to Camera source."); } } if (ApplyMethod == ApplicationMethod.Deferred) { m_paramsChanged = true; ApplyMethod = ApplicationMethod.PostEffect; if ((int)m_targetCamera.cameraType != 2) { Debug.LogWarning((object)"[AmplifyOcclusion] Deferred Method requires a Deferred Shading path. Switching to Post Effect Method."); } } } else if (PerPixelNormals == PerPixelNormalSource.Camera) { m_paramsChanged = true; PerPixelNormals = PerPixelNormalSource.GBuffer; if ((int)m_targetCamera.cameraType != 2) { Debug.LogWarning((object)"[AmplifyOcclusion] Camera Normals not supported for Deferred Method. Switching to GBuffer Normals."); } } if ((m_targetCamera.depthTextureMode & 1) == 0) { Camera targetCamera = m_targetCamera; targetCamera.depthTextureMode = (DepthTextureMode)(targetCamera.depthTextureMode | 1); } if (PerPixelNormals == PerPixelNormalSource.Camera && (m_targetCamera.depthTextureMode & 2) == 0) { Camera targetCamera2 = m_targetCamera; targetCamera2.depthTextureMode = (DepthTextureMode)(targetCamera2.depthTextureMode | 2); } if (UsingMotionVectors && (m_targetCamera.depthTextureMode & 4) == 0) { Camera targetCamera3 = m_targetCamera; targetCamera3.depthTextureMode = (DepthTextureMode)(targetCamera3.depthTextureMode | 4); } } else { m_targetCamera = ((Component)this).GetComponent<Camera>(); } } private void OnPreRender() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 //IL_0073: 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_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) checkMaterials(aThroughErrorMsg: true); if ((Object)(object)m_targetCamera != (Object)null) { bool flag = (int)GraphicsSettings.GetShaderMode((BuiltinShaderType)1) > 0; if (m_prevPerPixelNormals != PerPixelNormals || m_prevApplyMethod != ApplyMethod || m_prevDeferredReflections != flag || m_commandBuffer_Parameters.cmdBuffer == null || m_commandBuffer_Occlusion.cmdBuffer == null || m_commandBuffer_Apply.cmdBuffer == null) { CameraEvent aCameraEvent = (CameraEvent)12; if (ApplyMethod == ApplicationMethod.Deferred) { aCameraEvent = (CameraEvent)(flag ? 21 : 6); } createCommandBuffer(ref m_commandBuffer_Parameters, "AmplifyOcclusion_Parameters_" + m_myIDstring, aCameraEvent); createCommandBuffer(ref m_commandBuffer_Occlusion, "AmplifyOcclusion_Compute_" + m_myIDstring, aCameraEvent); createCommandBuffer(ref m_commandBuffer_Apply, "AmplifyOcclusion_Apply_" + m_myIDstring, aCameraEvent); m_prevPerPixelNormals = PerPixelNormals; m_prevApplyMethod = ApplyMethod; m_prevDeferredReflections = flag; m_paramsChanged = true; } if (m_commandBuffer_Parameters.cmdBuffer != null && m_commandBuffer_Occlusion.cmdBuffer != null && m_commandBuffer_Apply.cmdBuffer != null) { if (AmplifyOcclusionCommon.IsStereoMultiPassEnabled(m_targetCamera)) { uint num = (m_sampleStep >> 1) & 1u; uint num2 = m_sampleStep & 1u; m_curTemporalIdx = num2 * 2 + num; m_prevTemporalIdx = num2 * 2 + (1 - num); } else { m_prevTemporalIdx = 1 - (m_curTemporalIdx = m_sampleStep & 1u); } m_commandBuffer_Parameters.cmdBuffer.Clear(); UpdateGlobalShaderConstants(m_commandBuffer_Parameters.cmdBuffer); UpdateGlobalShaderConstants_Matrices(m_commandBuffer_Parameters.cmdBuffer); UpdateGlobalShaderConstants_AmbientOcclusion(m_commandBuffer_Parameters.cmdBuffer); checkParamsChanged(); if (m_paramsChanged) { m_commandBuffer_Occlusion.cmdBuffer.Clear(); commandBuffer_FillComputeOcclusion(m_commandBuffer_Occlusion.cmdBuffer); } m_commandBuffer_Apply.cmdBuffer.Clear(); if (ApplyMethod == ApplicationMethod.Debug) { commandBuffer_FillApplyDebug(m_commandBuffer_Apply.cmdBuffer); } else if (ApplyMethod == ApplicationMethod.PostEffect) { commandBuffer_FillApplyPostEffect(m_commandBuffer_Apply.cmdBuffer); } else { bool logTarget = !m_HDR; commandBuffer_FillApplyDeferred(m_commandBuffer_Apply.cmdBuffer, logTarget); } updateParams(); m_sampleStep++; } } else { m_targetCamera = ((Component)this).GetComponent<Camera>(); Update(); } } private void OnPostRender() { if ((Object)(object)m_occlusionDepthRT != (Object)null) { m_occlusionDepthRT.MarkRestoreExpected(); } if (m_temporalAccumRT != null) { RenderTexture[] temporalAccumRT = m_temporalAccumRT; for (int i = 0; i < temporalAccumRT.Length; i++) { temporalAccumRT[i].MarkRestoreExpected(); } } } private void commandBuffer_FillComputeOcclusion(CommandBuffer cb) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) cb.BeginSample("AO 1 - ComputeOcclusion"); if (PerPixelNormals == PerPixelNormalSource.GBuffer || PerPixelNormals == PerPixelNormalSource.GBufferOctaEncoded) { cb.SetGlobalTexture(PropertyID._AO_GBufferNormals, RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)12)); } Vector4 val = default(Vector4); ((Vector4)(ref val))..ctor(1f / (float)m_target.fullWidth, 1f / (float)m_target.fullHeight, (float)m_target.fullWidth, (float)m_target.fullHeight); int num = (int)((int)SampleCount * AmplifyOcclusionCommon.PerPixelNormalSourceCount + PerPixelNormals); if (CacheAware) { num += 16; int num2 = 0; for (int i = 0; i < m_numberMips; i++) { int width = m_target.fullWidth >> i + 1; int height = m_target.fullHeight >> i + 1; int num3 = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, m_tmpMipString[i], width, height, (RenderTextureFormat)14, (RenderTextureReadWrite)1, (FilterMode)1); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num3)); PerformBlit(cb, m_occlusionMat, (i == 0) ? 36 : 35); cb.CopyTexture(RenderTargetIdentifier.op_Implicit(num3), 0, 0, RenderTargetIdentifier.op_Implicit((Texture)(object)m_depthMipmap), 0, i); if (num2 != 0) { AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num2); } num2 = num3; cb.SetGlobalTexture(PropertyID._AO_CurrDepthSource, RenderTargetIdentifier.op_Implicit(num3)); } AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num2); cb.SetGlobalTexture(PropertyID._AO_SourceDepthMipmap, RenderTargetIdentifier.op_Implicit((Texture)(object)m_depthMipmap)); } if (Downsample && !UsingFilterDownsample) { int num4 = m_target.fullWidth / 2; int num5 = m_target.fullHeight / 2; int num6 = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_SmallOcclusionTexture", num4, num5, m_occlusionRTFormat, (RenderTextureReadWrite)1, (FilterMode)1); cb.SetGlobalVector(PropertyID._AO_Source_TexelSize, val); cb.SetGlobalVector(PropertyID._AO_Target_TexelSize, new Vector4(1f / ((float)m_target.fullWidth / 2f), 1f / ((float)m_target.fullHeight / 2f), (float)m_target.fullWidth / 2f, (float)m_target.fullHeight / 2f)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num6)); PerformBlit(cb, m_occlusionMat, num); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 1 - ComputeOcclusion"); if (BlurEnabled) { commandBuffer_Blur(cb, RenderTargetIdentifier.op_Implicit(num6), num4, num5); } cb.BeginSample("AO 2b - Combine"); cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit(num6)); cb.SetGlobalVector(PropertyID._AO_Target_TexelSize, val); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); PerformBlit(cb, m_occlusionMat, 32); AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num6); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 2b - Combine"); } else { cb.SetGlobalVector(PropertyID._AO_Source_TexelSize, val); if (UsingFilterDownsample) { cb.SetGlobalVector(PropertyID._AO_Target_TexelSize, new Vector4(1f / ((float)m_target.fullWidth / 2f), 1f / ((float)m_target.fullHeight / 2f), (float)m_target.fullWidth / 2f, (float)m_target.fullHeight / 2f)); } else { cb.SetGlobalVector(PropertyID._AO_Target_TexelSize, new Vector4(1f / (float)m_target.width, 1f / (float)m_target.height, (float)m_target.width, (float)m_target.height)); } cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); PerformBlit(cb, m_occlusionMat, num); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 1 - ComputeOcclusion"); if (BlurEnabled) { commandBuffer_Blur(cb, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT), m_target.width, m_target.height); } } } private int commandBuffer_NeighborMotionIntensity(CommandBuffer cb, int aSourceWidth, int aSourceHeight) { //IL_000d: 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) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) int num = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_IntensityTmp", aSourceWidth / 4, aSourceHeight / 4, m_motionIntensityRTFormat, (RenderTextureReadWrite)1, (FilterMode)1); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num)); cb.SetGlobalVector("_AO_Target_TexelSize", new Vector4(1f / ((float)aSourceWidth / 4f), 1f / ((float)aSourceHeight / 4f), (float)aSourceWidth / 4f, (float)aSourceHeight / 4f)); PerformBlit(cb, m_occlusionMat, 33); int num2 = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_BlurIntensityTmp", aSourceWidth / 4, aSourceHeight / 4, m_motionIntensityRTFormat, (RenderTextureReadWrite)1, (FilterMode)1); cb.SetGlobalTexture(PropertyID._AO_CurrMotionIntensity, RenderTargetIdentifier.op_Implicit(num)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num2)); PerformBlit(cb, m_blurMat, 8); cb.SetGlobalTexture(PropertyID._AO_CurrMotionIntensity, RenderTargetIdentifier.op_Implicit(num2)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num)); PerformBlit(cb, m_blurMat, 9); AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num2); cb.SetGlobalTexture(PropertyID._AO_CurrMotionIntensity, RenderTargetIdentifier.op_Implicit(num)); return num; } private void commandBuffer_Blur(CommandBuffer cb, RenderTargetIdentifier aSourceRT, int aSourceWidth, int aSourceHeight) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) cb.BeginSample("AO 2 - Blur"); int num = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_BlurTmp", aSourceWidth, aSourceHeight, m_occlusionRTFormat, (RenderTextureReadWrite)1, (FilterMode)1); for (int i = 0; i < BlurPasses; i++) { cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, aSourceRT); int pass = (BlurRadius - 1) * 2; cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit(num)); PerformBlit(cb, m_blurMat, pass); cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit(num)); int pass2 = 1 + (BlurRadius - 1) * 2; cb.SetRenderTarget(aSourceRT); PerformBlit(cb, m_blurMat, pass2); } AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 2 - Blur"); } private int getTemporalPass() { if (!UsingMotionVectors || m_sampleStep <= 1) { return 0; } return 1; } private void commandBuffer_TemporalFilter(CommandBuffer cb) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (m_clearHistory) { ClearHistory(cb); } float num = Mathf.Lerp(0.01f, 0.99f, FilterBlending); cb.SetGlobalFloat(PropertyID._AO_TemporalCurveAdj, num); cb.SetGlobalFloat(PropertyID._AO_TemporalMotionSensibility, FilterResponse * FilterResponse + 0.01f); cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); cb.SetGlobalTexture(PropertyID._AO_TemporalAccumm, RenderTargetIdentifier.op_Implicit((Texture)(object)m_temporalAccumRT[m_prevTemporalIdx])); } private void commandBuffer_FillApplyDeferred(CommandBuffer cb, bool logTarget) { //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) //IL_0489: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Unknown result type (might be due to invalid IL or missing references) //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03cf: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) cb.BeginSample("AO 3 - ApplyDeferred"); if (!logTarget) { if (UsingTemporalFilter) { commandBuffer_TemporalFilter(cb); int id = 0; if (UsingMotionVectors) { id = commandBuffer_NeighborMotionIntensity(cb, m_target.fullWidth, m_target.fullHeight); } if (!UsingFilterDownsample) { int num = 0; if (useMRTBlendingFallback) { num = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_ApplyOcclusionTexture", m_target.fullWidth, m_target.fullHeight, (RenderTextureFormat)0, (RenderTextureReadWrite)0, (FilterMode)0); applyOcclusionTemporal[0] = RenderTargetIdentifier.op_Implicit(num); applyOcclusionTemporal[1] = new RenderTargetIdentifier((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(applyOcclusionTemporal, applyOcclusionTemporal[0]); PerformBlit(cb, m_applyOcclusionMat, 10 + getTemporalPass()); } else { applyDeferredTargetsTemporal[0] = m_applyDeferredTargets[0]; applyDeferredTargetsTemporal[1] = m_applyDeferredTargets[1]; applyDeferredTargetsTemporal[2] = new RenderTargetIdentifier((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(applyDeferredTargetsTemporal, applyDeferredTargetsTemporal[0]); PerformBlit(cb, m_applyOcclusionMat, 4 + getTemporalPass()); } if (useMRTBlendingFallback) { cb.SetGlobalTexture("_AO_ApplyOcclusionTexture", RenderTargetIdentifier.op_Implicit(num)); applyOcclusionTemporal[0] = m_applyDeferredTargets[0]; applyOcclusionTemporal[1] = m_applyDeferredTargets[1]; cb.SetRenderTarget(applyOcclusionTemporal, applyOcclusionTemporal[0]); PerformBlit(cb, m_applyOcclusionMat, 13); AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num); } } else { RenderTargetIdentifier val = default(RenderTargetIdentifier); ((RenderTargetIdentifier)(ref val))..ctor((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(val); PerformBlit(cb, m_occlusionMat, 37 + getTemporalPass()); cb.SetGlobalTexture(PropertyID._AO_TemporalAccumm, val); cb.SetRenderTarget(m_applyDeferredTargets, m_applyDeferredTargets[0]); PerformBlit(cb, m_applyOcclusionMat, 16); } if (UsingMotionVectors) { AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, id); } } else { cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); cb.SetRenderTarget(m_applyDeferredTargets, m_applyDeferredTargets[0]); PerformBlit(cb, m_applyOcclusionMat, 3); } } else { int num2 = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_tmpAlbedo", m_target.fullWidth, m_target.fullHeight, (RenderTextureFormat)0, (RenderTextureReadWrite)0, (FilterMode)0); int num3 = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_tmpEmission", m_target.fullWidth, m_target.fullHeight, m_temporaryEmissionRTFormat, (RenderTextureReadWrite)0, (FilterMode)0); cb.Blit(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)10), RenderTargetIdentifier.op_Implicit(num2)); cb.Blit(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)13), RenderTargetIdentifier.op_Implicit(num3)); cb.SetGlobalTexture(PropertyID._AO_GBufferAlbedo, RenderTargetIdentifier.op_Implicit(num2)); cb.SetGlobalTexture(PropertyID._AO_GBufferEmission, RenderTargetIdentifier.op_Implicit(num3)); if (UsingTemporalFilter) { commandBuffer_TemporalFilter(cb); int id2 = 0; if (UsingMotionVectors) { id2 = commandBuffer_NeighborMotionIntensity(cb, m_target.fullWidth, m_target.fullHeight); } if (!UsingFilterDownsample) { applyDeferredTargets_Log_Temporal[0] = m_applyDeferredTargets_Log[0]; applyDeferredTargets_Log_Temporal[1] = m_applyDeferredTargets_Log[1]; applyDeferredTargets_Log_Temporal[2] = new RenderTargetIdentifier((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(applyDeferredTargets_Log_Temporal, applyDeferredTargets_Log_Temporal[0]); PerformBlit(cb, m_applyOcclusionMat, 7 + getTemporalPass()); } else { RenderTargetIdentifier val2 = default(RenderTargetIdentifier); ((RenderTargetIdentifier)(ref val2))..ctor((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(val2); PerformBlit(cb, m_occlusionMat, 37 + getTemporalPass()); cb.SetGlobalTexture(PropertyID._AO_TemporalAccumm, val2); cb.SetRenderTarget(m_applyDeferredTargets_Log, m_applyDeferredTargets_Log[0]); PerformBlit(cb, m_applyOcclusionMat, 17); } if (UsingMotionVectors) { AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, id2); } } else { cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); cb.SetRenderTarget(m_applyDeferredTargets_Log, m_applyDeferredTargets_Log[0]); PerformBlit(cb, m_applyOcclusionMat, 6); } AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num2); AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num3); } cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 3 - ApplyDeferred"); } private void commandBuffer_FillApplyPostEffect(CommandBuffer cb) { //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0165: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) cb.BeginSample("AO 3 - ApplyPostEffect"); if (UsingTemporalFilter) { commandBuffer_TemporalFilter(cb); int id = 0; if (UsingMotionVectors) { id = commandBuffer_NeighborMotionIntensity(cb, m_target.fullWidth, m_target.fullHeight); } if (!UsingFilterDownsample) { int num = 0; if (useMRTBlendingFallback) { num = AmplifyOcclusionCommon.SafeAllocateTemporaryRT(cb, "_AO_ApplyOcclusionTexture", m_target.fullWidth, m_target.fullHeight, (RenderTextureFormat)0, (RenderTextureReadWrite)0, (FilterMode)0); applyPostEffectTargetsTemporal[0] = RenderTargetIdentifier.op_Implicit(num); } else { applyPostEffectTargetsTemporal[0] = RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2); } applyPostEffectTargetsTemporal[1] = new RenderTargetIdentifier((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(applyPostEffectTargetsTemporal, applyPostEffectTargetsTemporal[0]); PerformBlit(cb, m_applyOcclusionMat, 10 + getTemporalPass()); if (useMRTBlendingFallback) { cb.SetGlobalTexture("_AO_ApplyOcclusionTexture", RenderTargetIdentifier.op_Implicit(num)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2)); PerformBlit(cb, m_applyOcclusionMat, 12); AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, num); } } else { RenderTargetIdentifier val = default(RenderTargetIdentifier); ((RenderTargetIdentifier)(ref val))..ctor((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(val); PerformBlit(cb, m_occlusionMat, 37 + getTemporalPass()); cb.SetGlobalTexture(PropertyID._AO_TemporalAccumm, val); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2)); PerformBlit(cb, m_applyOcclusionMat, 15); } if (UsingMotionVectors) { AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, id); } } else { cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2)); PerformBlit(cb, m_applyOcclusionMat, 9); } cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 3 - ApplyPostEffect"); } private void commandBuffer_FillApplyDebug(CommandBuffer cb) { //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) cb.BeginSample("AO 3 - ApplyDebug"); if (UsingTemporalFilter) { commandBuffer_TemporalFilter(cb); int id = 0; if (UsingMotionVectors) { id = commandBuffer_NeighborMotionIntensity(cb, m_target.fullWidth, m_target.fullHeight); } if (!UsingFilterDownsample) { applyDebugTargetsTemporal[0] = RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2); applyDebugTargetsTemporal[1] = new RenderTargetIdentifier((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(applyDebugTargetsTemporal, applyDebugTargetsTemporal[0]); PerformBlit(cb, m_applyOcclusionMat, 1 + getTemporalPass()); } else { RenderTargetIdentifier val = default(RenderTargetIdentifier); ((RenderTargetIdentifier)(ref val))..ctor((Texture)(object)m_temporalAccumRT[m_curTemporalIdx]); cb.SetRenderTarget(val); PerformBlit(cb, m_occlusionMat, 37 + getTemporalPass()); cb.SetGlobalTexture(PropertyID._AO_TemporalAccumm, val); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2)); PerformBlit(cb, m_applyOcclusionMat, 14); } if (UsingMotionVectors) { AmplifyOcclusionCommon.SafeReleaseTemporaryRT(cb, id); } } else { cb.SetGlobalTexture(PropertyID._AO_CurrOcclusionDepth, RenderTargetIdentifier.op_Implicit((Texture)(object)m_occlusionDepthRT)); cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((BuiltinRenderTextureType)2)); PerformBlit(cb, m_applyOcclusionMat, 0); } cb.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)null)); cb.EndSample("AO 3 - ApplyDebug"); } private void UpdateGlobalShaderConstants(CommandBuffer cb) { AmplifyOcclusionCommon.UpdateGlobalShaderConstants(cb, ref m_target, m_targetCamera, Downsample, UsingFilterDownsample); } private void UpdateGlobalShaderConstants_AmbientOcclusion(CommandBuffer cb) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) cb.SetGlobalFloat(PropertyID._AO_Radius, Radius); cb.SetGlobalFloat(PropertyID._AO_PowExponent, PowerExponent); cb.SetGlobalFloat(PropertyID._AO_Bias, Bias * Bias); cb.SetGlobalColor(PropertyID._AO_Levels, new Color(Tint.r, Tint.g, Tint.b, Intensity)); float num = 1f - Thickness; cb.SetGlobalFloat(PropertyID._AO_ThicknessDecay, (1f - num * num) * 0.98f); float num2 = m_targetCamera.farClipPlane * m_oneOverDepthScale; cb.SetGlobalFloat(PropertyID._AO_BufDepthToLinearEye, num2); if (BlurEnabled) { float num3 = BlurSharpness * 100f * num2; cb.SetGlobalFloat(PropertyID._AO_BlurSharpness, num3); } if (FadeEnabled) { FadeStart = Mathf.Max(0f, FadeStart); FadeLength = Mathf.Max(0.01f, FadeLength); float num4 = 1f / FadeLength; cb.SetGlobalVector(PropertyID._AO_FadeParams, Vector4.op_Implicit(new Vector2(FadeStart, num4))); float num5 = 1f - FadeToThickness; cb.SetGlobalVector(PropertyID._AO_FadeValues, new Vector4(FadeToIntensity, FadeToRadius, FadeToPowerExponent, (1f - num5 * num5) * 0.98f)); cb.SetGlobalColor(PropertyID._AO_FadeToTint, new Color(FadeToTint.r, FadeToTint.g, FadeToTint.b, 0f)); } else { cb.SetGlobalVector(PropertyID._AO_FadeParams, Vector4.op_Implicit(new Vector2(0f, 0f))); } if (UsingTemporalFilter) { AmplifyOcclusionCommon.CommandBuffer_TemporalFilterDirectionsOffsets(cb, m_sampleStep); return; } cb.SetGlobalFloat(PropertyID._AO_TemporalDirections, 0f); cb.SetGlobalFloat(PropertyID._AO_TemporalOffsets, 0f); } private void UpdateGlobalShaderConstants_Matrices(CommandBuffer cb) { m_viewProjMatrix.UpdateGlobalShaderConstants_Matrices(cb, m_targetCamera, UsingTemporalFilter); } } namespace AmplifyOcclusion; public static class AmplifyOcclusionCommon { public static readonly int PerPixelNormalSourceCount = 4; public static readonly float[] m_temporalRotations = new float[6] { 60f, 300f, 180f, 240f, 120f, 0f }; public static readonly float[] m_spatialOffsets = new float[4] { 0f, 0.5f, 0.25f, 0.75f }; public static void CommandBuffer_TemporalFilterDirectionsOffsets(CommandBuffer cb, uint aSampleStep) { float num = m_temporalRotations[aSampleStep % 6]; float num2 = m_spatialOffsets[aSampleStep / 6 % 4]; cb.SetGlobalFloat(PropertyID._AO_TemporalDirections, num / 360f); cb.SetGlobalFloat(PropertyID._AO_TemporalOffsets, num2); } public static Material CreateMaterialWithShaderName(string aShaderName, bool aThroughErrorMsg) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown Shader shader = ShaderLoader.GetShader(aShaderName); if ((Object)(object)shader == (Object)null) { if (aThroughErrorMsg) { Debug.LogErrorFormat("[AmplifyOcclusion] Cannot find shader: \"{0}\" Please contact [email protected]", new object[1] { aShaderName }); } return null; } return new Material(shader) { hideFlags = (HideFlags)52 }; } public static int SafeAllocateTemporaryRT(CommandBuffer cb, string propertyName, int width, int height, RenderTextureFormat format = 7, RenderTextureReadWrite readWrite = 0, FilterMode filterMode = 0) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) int num = Shader.PropertyToID(propertyName); cb.GetTemporaryRT(num, width, height, 0, filterMode, format, readWrite); return num; } public static void SafeReleaseTemporaryRT(CommandBuffer cb, int id) { cb.ReleaseTemporaryRT(id); } public static RenderTexture SafeAllocateRT(string name, int width, int height, RenderTextureFormat format, RenderTextureReadWrite readWrite, FilterMode filterMode = 0, int antiAliasing = 1, bool aUseMipMap = false) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown width = Mathf.Clamp(width, 1, 65536); height = Mathf.Clamp(height, 1, 65536); RenderTexture val = new RenderTexture(width, height, 0, format, readWrite) { hideFlags = (HideFlags)52, name = name, filterMode = filterMode, wrapMode = (TextureWrapMode)1, antiAliasing = Mathf.Max(antiAliasing, 1), useMipMap = aUseMipMap }; val.Create(); return val; } public static void SafeReleaseRT(ref RenderTexture rt) { if ((Object)(object)rt != (Object)null) { RenderTexture.active = null; rt.Release(); Object.DestroyImmediate((Object)(object)rt); rt = null; } } public static bool IsStereoSinglePassEnabled(Camera aCamera) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 if (aCamera.stereoEnabled) { RenderTextureDescriptor eyeTextureDesc = XRSettings.eyeTextureDesc; return (int)((RenderTextureDescriptor)(ref eyeTextureDesc)).vrUsage == 2; } return false; } public static bool IsStereoMultiPassEnabled(Camera aCamera) { return true; } public static void UpdateGlobalShaderConstants(CommandBuffer cb, ref TargetDesc aTarget, Camera aCamera, bool isDownsample, bool isFilterDownsample) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) if (XRSettings.enabled) { RenderTextureDescriptor eyeTextureDesc = XRSettings.eyeTextureDesc; aTarget.fullWidth = (int)((float)((RenderTextureDescriptor)(ref eyeTextureDesc)).width * XRSettings.eyeTextureResolutionScale); eyeTextureDesc = XRSettings.eyeTextureDesc; aTarget.fullHeight = (int)((float)((RenderTextureDescriptor)(ref eyeTextureDesc)).height * XRSettings.eyeTextureResolutionScale); } else { aTarget.fullWidth = aCamera.pixelWidth; aTarget.fullHeight = aCamera.pixelHeight; } if (isFilterDownsample) { aTarget.width = aTarget.fullWidth / 2; aTarget.height = aTarget.fullHeight / 2; } else { aTarget.width = aTarget.fullWidth; aTarget.height = aTarget.fullHeight; } aTarget.oneOverWidth = 1f / (float)aTarget.width; aTarget.oneOverHeight = 1f / (float)aTarget.height; float num = aCamera.fieldOfView * (MathF.PI / 180f); float num2 = 1f / Mathf.Tan(num * 0.5f); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor(num2 * ((float)aTarget.height / (float)aTarget.width), num2); Vector2 val2 = default(Vector2); ((Vector2)(ref val2))..ctor(1f / val.x, 1f / val.y); cb.SetGlobalVector(PropertyID._AO_UVToView, new Vector4(2f * val2.x, 2f * val2.y, -1f * val2.x, -1f * val2.y)); float num3 = ((!aCamera.orthographic) ? ((float)aTarget.fullHeight / (Mathf.Tan(num * 0.5f) * 2f)) : ((float)aTarget.fullHeight / aCamera.orthographicSize)); num3 = ((!isDownsample && !isFilterDownsample) ? (num3 * 0.5f) : (num3 * 0.5f * 0.5f)); cb.SetGlobalFloat(PropertyID._AO_HalfProjScale, num3); } } public class AmplifyOcclusionViewProjMatrix { private Matrix4x4 m_prevViewProjMatrixLeft = Matrix4x4.identity; private Matrix4x4 m_prevInvViewProjMatrixLeft = Matrix4x4.identity; private Matrix4x4 m_prevViewProjMatrixRight = Matrix4x4.identity; private Matrix4x4 m_prevInvViewProjMatrixRight = Matrix4x4.identity; public void UpdateGlobalShaderConstants_Matrices(CommandBuffer cb, Camera aCamera, bool isUsingTemporalFilter) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0123: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) if (AmplifyOcclusionCommon.IsStereoSinglePassEnabled(aCamera)) { Matrix4x4 stereoViewMatrix = aCamera.GetStereoViewMatrix((StereoscopicEye)0); Matrix4x4 stereoViewMatrix2 = aCamera.GetStereoViewMatrix((StereoscopicEye)1); cb.SetGlobalMatrix(PropertyID._AO_CameraViewLeft, stereoViewMatrix); cb.SetGlobalMatrix(PropertyID._AO_CameraViewRight, stereoViewMatrix2); Matrix4x4 stereoProjectionMatrix = aCamera.GetStereoProjectionMatrix((StereoscopicEye)0); Matrix4x4 stereoProjectionMatrix2 = aCamera.GetStereoProjectionMatrix((StereoscopicEye)1); Matrix4x4 gPUProjectionMatrix = GL.GetGPUProjectionMatrix(stereoProjectionMatrix, false); Matrix4x4 gPUProjectionMatrix2 = GL.GetGPUProjectionMatrix(stereoProjectionMatrix2, false); cb.SetGlobalMatrix(PropertyID._AO_ProjMatrixLeft, gPUProjectionMatrix); cb.SetGlobalMatrix(PropertyID._AO_ProjMatrixRight, gPUProjectionMatrix2); if (isUsingTemporalFilter) { Matrix4x4 val = gPUProjectionMatrix * stereoViewMatrix; Matrix4x4 val2 = gPUProjectionMatrix2 * stereoViewMatrix2; Matrix4x4 val3 = Matrix4x4.Inverse(val); Matrix4x4 val4 = Matrix4x4.Inverse(val2); cb.SetGlobalMatrix(PropertyID._AO_InvViewProjMatrixLeft, val3); cb.SetGlobalMatrix(PropertyID._AO_PrevViewProjMatrixLeft, m_prevViewProjMatrixLeft); cb.SetGlobalMatrix(PropertyID._AO_PrevInvViewProjMatrixLeft, m_prevInvViewProjMatrixLeft); cb.SetGlobalMatrix(PropertyID._AO_InvViewProjMatrixRight, val4); cb.SetGlobalMatrix(PropertyID._AO_PrevViewProjMatrixRight, m_prevViewProjMatrixRight); cb.SetGlobalMatrix(PropertyID._AO_PrevInvViewProjMatrixRight, m_prevInvViewProjMatrixRight); m_prevViewProjMatrixLeft = val; m_prevInvViewProjMatrixLeft = val3; m_prevViewProjMatrixRight = val2; m_prevInvViewProjMatrixRight = val4; } } else { Matrix4x4 worldToCameraMatrix = aCamera.worldToCameraMatrix; cb.SetGlobalMatrix(PropertyID._AO_CameraViewLeft, worldToCameraMatrix); if (isUsingTemporalFilter) { Matrix4x4 val5 = GL.GetGPUProjectionMatrix(aCamera.projectionMatrix, false) * worldToCameraMatrix; Matrix4x4 val6 = Matrix4x4.Inverse(val5); cb.SetGlobalMatrix(PropertyID._AO_InvViewProjMatrixLeft, val6); cb.SetGlobalMatrix(PropertyID._AO_PrevViewProjMatrixLeft, m_prevViewProjMatrixLeft); cb.SetGlobalMatrix(PropertyID._AO_PrevInvViewProjMatrixLeft, m_prevInvViewProjMatrixLeft); m_prevViewProjMatrixLeft = val5; m_prevInvViewProjMatrixLeft = val6; } } } } public enum SampleCountLevel { Low, Medium, High, VeryHigh } public struct TargetDesc { public int fullWidth; public int fullHeight; public int width; public int height; public float oneOverWidth; public float oneOverHeight; } public static class ShaderPass { public const int OcclusionLow_None_UseDynamicDepthMips = 16; public const int CombineDownsampledOcclusionDepth = 32; public const int NeighborMotionIntensity = 33; public const int ClearTemporal = 34; public const int ScaleDownCloserDepthEven = 35; public const int ScaleDownCloserDepthEven_CameraDepthTexture = 36; public const int Temporal = 37; public const int BlurHorizontal1 = 0; public const int BlurVertical1 = 1; public const int BlurHorizontal2 = 2; public const int BlurVertical2 = 3; public const int BlurHorizontal3 = 4; public const int BlurVertical3 = 5; public const int BlurHorizontal4 = 6; public const int BlurVertical4 = 7; public const int BlurHorizontalIntensity = 8; public const int BlurVerticalIntensity = 9; public const int ApplyDebug = 0; public const int ApplyDebugTemporal = 1; public const int ApplyDeferred = 3; public const int ApplyDeferredTemporal = 4; public const int ApplyDeferredLog = 6; public const int ApplyDeferredLogTemporal = 7; public const int ApplyPostEffect = 9; public const int ApplyPostEffectTemporal = 10; public const int ApplyPostEffectTemporalMultiply = 12; public const int ApplyDeferredTemporalMultiply = 13; public const int ApplyDebugCombineFromTemporal = 14; public const int ApplyCombineFromTemporal = 15; public const int ApplyDeferredCombineFromTemporal = 16; public const int ApplyDeferredLogCombineFromTemporal = 17; public const int OcclusionLow_None = 0; public const int OcclusionLow_Camera = 1; public const int OcclusionLow_GBuffer = 2; public const int OcclusionLow_GBufferOctaEncoded = 3; } public static class PropertyID { public static readonly int _MainTex = Shader.PropertyToID("_MainTex"); public static readonly int _AO_Radius = Shader.PropertyToID("_AO_Radius"); public static readonly int _AO_PowExponent = Shader.PropertyToID("_AO_PowExponent"); public static readonly int _AO_Bias = Shader.PropertyToID("_AO_Bias"); public static readonly int _AO_Levels = Shader.PropertyToID("_AO_Levels"); public static readonly int _AO_ThicknessDecay = Shader.PropertyToID("_AO_ThicknessDecay"); public static readonly int _AO_BlurSharpness = Shader.PropertyToID("_AO_BlurSharpness"); public static readonly int _AO_BufDepthToLinearEye = Shader.PropertyToID("_AO_BufDepthToLinearEye"); public static readonly int _AO_CameraViewLeft = Shader.PropertyToID("_AO_CameraViewLeft"); public static readonly int _AO_CameraViewRight = Shader.PropertyToID("_AO_CameraViewRight"); public static readonly int _AO_ProjMatrixLeft = Shader.PropertyToID("_AO_ProjMatrixLeft"); public static readonly int _AO_ProjMatrixRight = Shader.PropertyToID("_AO_ProjMatrixRight"); public static readonly int _AO_InvViewProjMatrixLeft = Shader.PropertyToID("_AO_InvViewProjMatrixLeft"); public static readonly int _AO_PrevViewProjMatrixLeft = Shader.PropertyToID("_AO_PrevViewProjMatrixLeft"); public static readonly int _AO_PrevInvViewProjMatrixLeft = Shader.PropertyToID("_AO_PrevInvViewProjMatrixLeft"); public static readonly int _AO_InvViewProjMatrixRight = Shader.PropertyToID("_AO_InvViewProjMatrixRight"); public static readonly int _AO_PrevViewProjMatrixRight = Shader.PropertyToID("_AO_PrevViewProjMatrixRight"); public static readonly int _AO_PrevInvViewProjMatrixRight = Shader.PropertyToID("_AO_PrevInvViewProjMatrixRight"); public static readonly int _AO_GBufferNormals = Shader.PropertyToID("_AO_GBufferNormals"); public static readonly int _AO_Target_TexelSize = Shader.PropertyToID("_AO_Target_TexelSize"); public static readonly int _AO_TemporalCurveAdj = Shader.PropertyToID("_AO_TemporalCurveAdj"); public static readonly int _AO_TemporalMotionSensibility = Shader.PropertyToID("_AO_TemporalMotionSensibility"); public static readonly int _AO_CurrOcclusionDepth = Shader.PropertyToID("_AO_CurrOcclusionDepth"); public static readonly int _AO_CurrOcclusionDepth_TexelSize = Shader.PropertyToID("_AO_CurrOcclusionDepth_TexelSize"); public static readonly int _AO_TemporalAccumm = Shader.PropertyToID("_AO_TemporalAccumm"); public static readonly int _AO_TemporalDirections = Shader.PropertyToID("_AO_TemporalDirections"); public static readonly int _AO_TemporalOffsets = Shader.PropertyToID("_AO_TemporalOffsets"); public static readonly int _AO_GBufferAlbedo = Shader.PropertyToID("_AO_GBufferAlbedo"); public static readonly int _AO_GBufferEmission = Shader.PropertyToID("_AO_GBufferEmission"); public static readonly int _AO_UVToView = Shader.PropertyToID("_AO_UVToView"); public static readonly int _AO_HalfProjScale = Shader.PropertyToID("_AO_HalfProjScale"); public static readonly int _AO_FadeParams = Shader.PropertyToID("_AO_FadeParams"); public static readonly int _AO_FadeValues = Shader.PropertyToID("_AO_FadeValues"); public static readonly int _AO_FadeToTint = Shader.PropertyToID("_AO_FadeToTint"); public static readonly int _AO_CurrMotionIntensity = Shader.PropertyToID("_AO_CurrMotionIntensity"); public static readonly int _AO_CurrDepthSource_TexelSize = Shader.PropertyToID("_AO_CurrDepthSource_TexelSize"); public static readonly int _AO_CurrDepthSource = Shader.PropertyToID("_AO_CurrDepthSource"); public static readonly int _AO_CurrMotionIntensity_TexelSize = Shader.PropertyToID("_AO_CurrMotionIntensity_TexelSize"); public static readonly int _AO_SourceDepthMipmap = Shader.PropertyToID("_AO_SourceDepthMipmap"); public static readonly int _AO_Source_TexelSize = Shader.PropertyToID("_AO_Source_TexelSize"); } [Serializable] public class VersionInfo { public const byte Major = 2; public const byte Minor = 0; public const byte Release = 8; public const byte Revision = 0; [SerializeField] private int m_major; [SerializeField] private int m_minor; [SerializeField] private int m_release; public static int FullNumber => 208; public int Number => m_major * 100 + m_minor * 10 + m_release; public static string StaticToString() { return $"{(byte)2}.{(byte)0}.{(byte)8}" ?? ""; } public override string ToString() { return $"{m_major}.{m_minor}.{m_release}" ?? ""; } private VersionInfo() { m_major = 2; m_minor = 0; m_release = 8; } private VersionInfo(byte major, byte minor, byte release) { m_major = major; m_minor = minor; m_release = release; } public static VersionInfo Current() { return new VersionInfo(2, 0, 8); } public static bool Matches(VersionInfo version) { if (2 == version.m_major && version.m_minor == 0) { return 8 == version.m_release; } return false; } }
plugins/Valheim_Data/Managed/Bhaptics.Tact.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Threading; using System.Timers; using CustomWebSocketSharp; using CustomWebSocketSharp.Net; using CustomWebSocketSharp.Net.WebSockets; using CustomWebSocketSharp.Server; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Bhaptics.Tact")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Bhaptics.Tact")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("f6971bb6-19f6-4d65-855d-fafa09351643")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyVersion("1.0.0.0")] namespace CustomWebSocketSharp { public enum ByteOrder { Little, Big } public class CloseEventArgs : EventArgs { private bool _clean; private PayloadData _payloadData; internal PayloadData PayloadData => _payloadData; public ushort Code => _payloadData.Code; public string Reason => _payloadData.Reason ?? string.Empty; public bool WasClean { get { return _clean; } internal set { _clean = value; } } internal CloseEventArgs() { _payloadData = PayloadData.Empty; } internal CloseEventArgs(ushort code) : this(code, null) { } internal CloseEventArgs(CloseStatusCode code) : this((ushort)code, null) { } internal CloseEventArgs(PayloadData payloadData) { _payloadData = payloadData; } internal CloseEventArgs(ushort code, string reason) { _payloadData = new PayloadData(code, reason); } internal CloseEventArgs(CloseStatusCode code, string reason) : this((ushort)code, reason) { } } public enum CloseStatusCode : ushort { Normal = 1000, Away = 1001, ProtocolError = 1002, UnsupportedData = 1003, Undefined = 1004, NoStatus = 1005, Abnormal = 1006, InvalidData = 1007, PolicyViolation = 1008, TooBig = 1009, MandatoryExtension = 1010, ServerError = 1011, TlsHandshakeFailure = 1015 } public enum CompressionMethod : byte { None, Deflate } public class ErrorEventArgs : EventArgs { private Exception _exception; private string _message; public Exception Exception => _exception; public string Message => _message; internal ErrorEventArgs(string message) : this(message, null) { } internal ErrorEventArgs(string message, Exception exception) { _message = message; _exception = exception; } } public static class Ext { private static readonly byte[] _last = new byte[1]; private static readonly int _retry = 5; private const string _tspecials = "()<>@,;:\\\"/[]?={} \t"; private static byte[] compress(this byte[] data) { if (data.Length == 0) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.compressToArray(); } private static MemoryStream compress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0L) { return memoryStream; } stream.Position = 0L; using DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, leaveOpen: true); CopyTo(stream, deflateStream, 1024); deflateStream.Close(); memoryStream.Write(_last, 0, 1); memoryStream.Position = 0L; return memoryStream; } private static byte[] compressToArray(this Stream stream) { using MemoryStream memoryStream = stream.compress(); memoryStream.Close(); return memoryStream.ToArray(); } private static byte[] decompress(this byte[] data) { if (data.LongLength == 0L) { return data; } using MemoryStream stream = new MemoryStream(data); return stream.decompressToArray(); } private static MemoryStream decompress(this Stream stream) { MemoryStream memoryStream = new MemoryStream(); if (stream.Length == 0L) { return memoryStream; } stream.Position = 0L; using DeflateStream source = new DeflateStream(stream, CompressionMode.Decompress, leaveOpen: true); CopyTo(source, memoryStream, 1024); memoryStream.Position = 0L; return memoryStream; } private static byte[] decompressToArray(this Stream stream) { using MemoryStream memoryStream = stream.decompress(); memoryStream.Close(); return memoryStream.ToArray(); } private static void times(this ulong n, Action action) { for (ulong num = 0uL; num < n; num++) { action(); } } internal static byte[] Append(this ushort code, string reason) { byte[] array = code.InternalToByteArray(ByteOrder.Big); if (reason != null && reason.Length > 0) { List<byte> list = new List<byte>(array); list.AddRange(Encoding.UTF8.GetBytes(reason)); array = list.ToArray(); } return array; } internal static string CheckIfAvailable(this ServerState state, bool ready, bool start, bool shutting) { if ((ready || (state != 0 && state != ServerState.Stop)) && (start || state != ServerState.Start) && (shutting || state != ServerState.ShuttingDown)) { return null; } return "This operation isn't available in: " + state.ToString().ToLower(); } internal static string CheckIfAvailable(this WebSocketState state, bool connecting, bool open, bool closing, bool closed) { if ((connecting || state != 0) && (open || state != WebSocketState.Open) && (closing || state != WebSocketState.Closing) && (closed || state != WebSocketState.Closed)) { return null; } return "This operation isn't available in: " + state.ToString().ToLower(); } internal static string CheckIfValidProtocols(this string[] protocols) { if (!protocols.Contains((string protocol) => protocol == null || protocol.Length == 0 || !protocol.IsToken())) { if (!protocols.ContainsTwice()) { return null; } return "Contains a value twice."; } return "Contains an invalid value."; } internal static string CheckIfValidServicePath(this string path) { if (path != null && path.Length != 0) { if (path[0] == '/') { if (path.IndexOfAny(new char[2] { '?', '#' }) <= -1) { return null; } return "'path' includes either or both query and fragment components."; } return "'path' isn't an absolute path."; } return "'path' is null or empty."; } internal static string CheckIfValidSessionID(this string id) { if (id != null && id.Length != 0) { return null; } return "'id' is null or empty."; } internal static string CheckIfValidWaitTime(this TimeSpan time) { if (!(time <= TimeSpan.Zero)) { return null; } return "A wait time is zero or less."; } internal static bool CheckWaitTime(this TimeSpan time, out string message) { message = null; if (time <= TimeSpan.Zero) { message = "A wait time is zero or less."; return false; } return true; } internal static void Close(this CustomWebSocketSharp.Net.HttpListenerResponse response, CustomWebSocketSharp.Net.HttpStatusCode code) { response.StatusCode = (int)code; response.OutputStream.Close(); } internal static void CloseWithAuthChallenge(this CustomWebSocketSharp.Net.HttpListenerResponse response, string challenge) { response.Headers.InternalSet("WWW-Authenticate", challenge, response: true); response.Close(CustomWebSocketSharp.Net.HttpStatusCode.Unauthorized); } internal static byte[] Compress(this byte[] data, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return data; } return data.compress(); } internal static Stream Compress(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream; } return stream.compress(); } internal static byte[] CompressToArray(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream.ToByteArray(); } return stream.compressToArray(); } internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition) { foreach (T item in source) { if (condition(item)) { return true; } } return false; } internal static bool ContainsTwice(this string[] values) { int len = values.Length; Func<int, bool> contains = null; contains = delegate(int idx) { if (idx < len - 1) { for (int i = idx + 1; i < len; i++) { if (values[i] == values[idx]) { return true; } } return contains(++idx); } return false; }; return contains(0); } internal static T[] Copy<T>(this T[] source, int length) { T[] array = new T[length]; Array.Copy(source, 0, array, 0, length); return array; } internal static T[] Copy<T>(this T[] source, long length) { T[] array = new T[length]; Array.Copy(source, 0L, array, 0L, length); return array; } internal static void CopyTo(this Stream source, Stream destination, int bufferLength) { byte[] buffer = new byte[bufferLength]; int num = 0; while ((num = source.Read(buffer, 0, bufferLength)) > 0) { destination.Write(buffer, 0, num); } } internal static void CopyToAsync(this Stream source, Stream destination, int bufferLength, Action completed, Action<Exception> error) { byte[] buff = new byte[bufferLength]; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = source.EndRead(ar); if (num <= 0) { if (completed != null) { completed(); } } else { destination.Write(buff, 0, num); source.BeginRead(buff, 0, bufferLength, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { source.BeginRead(buff, 0, bufferLength, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static byte[] Decompress(this byte[] data, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return data; } return data.decompress(); } internal static Stream Decompress(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream; } return stream.decompress(); } internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method) { if (method != CompressionMethod.Deflate) { return stream.ToByteArray(); } return stream.decompressToArray(); } internal static bool EqualsWith(this int value, char c, Action<int> action) { action(value); return value == c; } internal static string GetAbsolutePath(this Uri uri) { if (uri.IsAbsoluteUri) { return uri.AbsolutePath; } string originalString = uri.OriginalString; if (originalString[0] != '/') { return null; } int num = originalString.IndexOfAny(new char[2] { '?', '#' }); if (num <= 0) { return originalString; } return originalString.Substring(0, num); } internal static string GetMessage(this CloseStatusCode code) { return code switch { CloseStatusCode.TlsHandshakeFailure => "An error has occurred during a TLS handshake.", CloseStatusCode.ServerError => "WebSocket server got an internal error.", CloseStatusCode.MandatoryExtension => "WebSocket client didn't receive expected extension(s).", CloseStatusCode.TooBig => "A too big message has been received.", CloseStatusCode.PolicyViolation => "A policy violation has occurred.", CloseStatusCode.InvalidData => "Invalid data has been received.", CloseStatusCode.Abnormal => "An exception has occurred.", CloseStatusCode.UnsupportedData => "Unsupported data has been received.", CloseStatusCode.ProtocolError => "A WebSocket protocol error has occurred.", _ => string.Empty, }; } internal static string GetName(this string nameAndValue, char separator) { int num = nameAndValue.IndexOf(separator); if (num <= 0) { return null; } return nameAndValue.Substring(0, num).Trim(); } internal static string GetValue(this string nameAndValue, char separator) { int num = nameAndValue.IndexOf(separator); if (num <= -1 || num >= nameAndValue.Length - 1) { return null; } return nameAndValue.Substring(num + 1).Trim(); } internal static string GetValue(this string nameAndValue, char separator, bool unquote) { int num = nameAndValue.IndexOf(separator); if (num < 0 || num == nameAndValue.Length - 1) { return null; } string text = nameAndValue.Substring(num + 1).Trim(); if (!unquote) { return text; } return text.Unquote(); } internal static TcpListenerWebSocketContext GetWebSocketContext(this TcpClient tcpClient, string protocol, bool secure, ServerSslConfiguration sslConfig, Logger logger) { return new TcpListenerWebSocketContext(tcpClient, protocol, secure, sslConfig, logger); } internal static byte[] InternalToByteArray(this ushort value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static byte[] InternalToByteArray(this ulong value, ByteOrder order) { byte[] bytes = BitConverter.GetBytes(value); if (!order.IsHostOrder()) { Array.Reverse((Array)bytes); } return bytes; } internal static bool IsCompressionExtension(this string value, CompressionMethod method) { return value.StartsWith(method.ToExtensionString()); } internal static bool IsControl(this byte opcode) { if (opcode > 7) { return opcode < 16; } return false; } internal static bool IsControl(this Opcode opcode) { return (int)opcode >= 8; } internal static bool IsData(this byte opcode) { if (opcode != 1) { return opcode == 2; } return true; } internal static bool IsData(this Opcode opcode) { if (opcode != Opcode.Text) { return opcode == Opcode.Binary; } return true; } internal static bool IsPortNumber(this int value) { if (value > 0) { return value < 65536; } return false; } internal static bool IsReserved(this ushort code) { if (code != 1004 && code != 1005 && code != 1006) { return code == 1015; } return true; } internal static bool IsReserved(this CloseStatusCode code) { if (code != CloseStatusCode.Undefined && code != CloseStatusCode.NoStatus && code != CloseStatusCode.Abnormal) { return code == CloseStatusCode.TlsHandshakeFailure; } return true; } internal static bool IsSupported(this byte opcode) { return Enum.IsDefined(typeof(Opcode), opcode); } internal static bool IsText(this string value) { int length = value.Length; for (int i = 0; i < length; i++) { char c = value[i]; if (c < ' ' && !Contains("\r\n\t", c)) { return false; } switch (c) { case '\u007f': return false; case '\n': if (++i < length) { c = value[i]; if (!Contains(" \t", c)) { return false; } } break; } } return true; } internal static bool IsToken(this string value) { foreach (char c in value) { if (c < ' ' || c >= '\u007f' || Contains("()<>@,;:\\\"/[]?={} \t", c)) { return false; } } return true; } internal static string Quote(this string value) { return string.Format("\"{0}\"", value.Replace("\"", "\\\"")); } internal static byte[] ReadBytes(this Stream stream, int length) { byte[] array = new byte[length]; int num = 0; try { int num2 = 0; while (length > 0) { num2 = stream.Read(array, num, length); if (num2 != 0) { num += num2; length -= num2; continue; } break; } } catch { } return array.SubArray(0, num); } internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength) { using MemoryStream memoryStream = new MemoryStream(); try { byte[] buffer = new byte[bufferLength]; int num = 0; while (length > 0) { if (length < bufferLength) { bufferLength = (int)length; } num = stream.Read(buffer, 0, bufferLength); if (num != 0) { memoryStream.Write(buffer, 0, num); length -= num; continue; } break; } } catch { } memoryStream.Close(); return memoryStream.ToArray(); } internal static void ReadBytesAsync(this Stream stream, int length, Action<byte[]> completed, Action<Exception> error) { byte[] buff = new byte[length]; int offset = 0; int retry = 0; AsyncCallback callback = null; callback = delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num == 0 && retry < _retry) { retry++; stream.BeginRead(buff, offset, length, callback, null); } else if (num == 0 || num == length) { if (completed != null) { completed(buff.SubArray(0, offset + num)); } } else { retry = 0; offset += num; length -= num; stream.BeginRead(buff, offset, length, callback, null); } } catch (Exception obj2) { if (error != null) { error(obj2); } } }; try { stream.BeginRead(buff, offset, length, callback, null); } catch (Exception obj) { if (error != null) { error(obj); } } } internal static void ReadBytesAsync(this Stream stream, long length, int bufferLength, Action<byte[]> completed, Action<Exception> error) { MemoryStream dest = new MemoryStream(); byte[] buff = new byte[bufferLength]; int retry = 0; Action<long> read = null; read = delegate(long len) { if (len < bufferLength) { bufferLength = (int)len; } stream.BeginRead(buff, 0, bufferLength, delegate(IAsyncResult ar) { try { int num = stream.EndRead(ar); if (num > 0) { dest.Write(buff, 0, num); } if (num == 0 && retry < _retry) { int num2 = retry; retry = num2 + 1; read(len); } else if (num == 0 || num == len) { if (completed != null) { dest.Close(); completed(dest.ToArray()); } dest.Dispose(); } else { retry = 0; read(len - num); } } catch (Exception obj2) { dest.Dispose(); if (error != null) { error(obj2); } } }, null); }; try { read(length); } catch (Exception obj) { dest.Dispose(); if (error != null) { error(obj); } } } internal static string RemovePrefix(this string value, params string[] prefixes) { int num = 0; foreach (string text in prefixes) { if (value.StartsWith(text)) { num = text.Length; break; } } if (num <= 0) { return value; } return value.Substring(num); } internal static T[] Reverse<T>(this T[] array) { int num = array.Length; T[] array2 = new T[num]; int num2 = num - 1; for (int i = 0; i <= num2; i++) { array2[i] = array[num2 - i]; } return array2; } internal static IEnumerable<string> SplitHeaderValue(this string value, params char[] separators) { int len = value.Length; string seps = new string(separators); StringBuilder buff = new StringBuilder(32); bool escaped = false; bool quoted = false; for (int i = 0; i < len; i++) { char c = value[i]; switch (c) { case '"': if (escaped) { escaped = !escaped; } else { quoted = !quoted; } break; case '\\': if (i < len - 1 && value[i + 1] == '"') { escaped = true; } break; default: if (Contains(seps, c) && !quoted) { yield return buff.ToString(); buff.Length = 0; continue; } break; } buff.Append(c); } if (buff.Length > 0) { yield return buff.ToString(); } } internal static byte[] ToByteArray(this Stream stream) { using MemoryStream memoryStream = new MemoryStream(); stream.Position = 0L; CopyTo(stream, memoryStream, 1024); memoryStream.Close(); return memoryStream.ToArray(); } internal static CompressionMethod ToCompressionMethod(this string value) { foreach (CompressionMethod value2 in Enum.GetValues(typeof(CompressionMethod))) { if (value2.ToExtensionString() == value) { return value2; } } return CompressionMethod.None; } internal static string ToExtensionString(this CompressionMethod method, params string[] parameters) { if (method == CompressionMethod.None) { return string.Empty; } string text = $"permessage-{method.ToString().ToLower()}"; if (parameters == null || parameters.Length == 0) { return text; } return string.Format("{0}; {1}", text, parameters.ToString("; ")); } internal static IPAddress ToIPAddress(this string value) { if (value == null || value.Length == 0) { return null; } if (IPAddress.TryParse(value, out IPAddress address)) { return address; } try { return Dns.GetHostAddresses(value)[0]; } catch { return null; } } internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) { return new List<TSource>(source); } internal static ushort ToUInt16(this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt16(source.ToHostOrder(sourceOrder), 0); } internal static ulong ToUInt64(this byte[] source, ByteOrder sourceOrder) { return BitConverter.ToUInt64(source.ToHostOrder(sourceOrder), 0); } internal static string TrimSlashFromEnd(this string value) { string text = value.TrimEnd(new char[1] { '/' }); if (text.Length <= 0) { return "/"; } return text; } internal static bool TryCreateWebSocketUri(this string uriString, out Uri result, out string message) { result = null; message = null; Uri uri = uriString.ToUri(); if (uri == null) { message = "An invalid URI string."; return false; } if (!uri.IsAbsoluteUri) { message = "A relative URI."; return false; } string scheme = uri.Scheme; if (!(scheme == "ws") && !(scheme == "wss")) { message = "The scheme part is not 'ws' or 'wss'."; return false; } int port = uri.Port; if (port == 0) { message = "The port part is zero."; return false; } if (uri.Fragment.Length > 0) { message = "It includes the fragment component."; return false; } result = ((port != -1) ? uri : new Uri(string.Format("{0}://{1}:{2}{3}", scheme, uri.Host, (scheme == "ws") ? 80 : 443, uri.PathAndQuery))); return true; } internal static bool TryGetUTF8DecodedString(this byte[] bytes, out string s) { s = null; try { s = Encoding.UTF8.GetString(bytes); } catch { return false; } return true; } internal static bool TryGetUTF8EncodedBytes(this string s, out byte[] bytes) { bytes = null; try { bytes = Encoding.UTF8.GetBytes(s); } catch { return false; } return true; } internal static bool TryOpenRead(this FileInfo fileInfo, out FileStream fileStream) { fileStream = null; try { fileStream = fileInfo.OpenRead(); } catch { return false; } return true; } internal static string Unquote(this string value) { int num = value.IndexOf('"'); if (num < 0) { return value; } int num2 = value.LastIndexOf('"') - num - 1; if (num2 >= 0) { if (num2 != 0) { return value.Substring(num + 1, num2).Replace("\\\"", "\""); } return string.Empty; } return value; } internal static string UTF8Decode(this byte[] bytes) { try { return Encoding.UTF8.GetString(bytes); } catch { return null; } } internal static byte[] UTF8Encode(this string s) { return Encoding.UTF8.GetBytes(s); } internal static void WriteBytes(this Stream stream, byte[] bytes, int bufferLength) { using MemoryStream source = new MemoryStream(bytes); CopyTo(source, stream, bufferLength); } internal static void WriteBytesAsync(this Stream stream, byte[] bytes, int bufferLength, Action completed, Action<Exception> error) { MemoryStream input = new MemoryStream(bytes); input.CopyToAsync(stream, bufferLength, delegate { if (completed != null) { completed(); } input.Dispose(); }, delegate(Exception ex) { input.Dispose(); if (error != null) { error(ex); } }); } public static bool Contains(this string value, params char[] chars) { if (chars != null && chars.Length != 0) { if (value != null && value.Length != 0) { return value.IndexOfAny(chars) > -1; } return false; } return true; } public static bool Contains(this NameValueCollection collection, string name) { if (collection == null || collection.Count <= 0) { return false; } return collection[name] != null; } public static bool Contains(this NameValueCollection collection, string name, string value) { if (collection == null || collection.Count == 0) { return false; } string text = collection[name]; if (text == null) { return false; } string[] array = text.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { if (array[i].Trim().Equals(value, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } public static void Emit(this EventHandler eventHandler, object sender, EventArgs e) { eventHandler?.Invoke(sender, e); } public static void Emit<TEventArgs>(this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e) where TEventArgs : EventArgs { eventHandler?.Invoke(sender, e); } public static CustomWebSocketSharp.Net.CookieCollection GetCookies(this NameValueCollection headers, bool response) { string name = (response ? "Set-Cookie" : "Cookie"); if (headers == null || !headers.Contains(name)) { return new CustomWebSocketSharp.Net.CookieCollection(); } return CustomWebSocketSharp.Net.CookieCollection.Parse(headers[name], response); } public static string GetDescription(this CustomWebSocketSharp.Net.HttpStatusCode code) { return ((int)code).GetStatusDescription(); } public static string GetStatusDescription(this int code) { return code switch { 100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 307 => "Temporary Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-Uri Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "Http Version Not Supported", 507 => "Insufficient Storage", _ => string.Empty, }; } public static bool IsCloseStatusCode(this ushort value) { if (value > 999) { return value < 5000; } return false; } public static bool IsEnclosedIn(this string value, char c) { if (value != null && value.Length > 1 && value[0] == c) { return value[value.Length - 1] == c; } return false; } public static bool IsHostOrder(this ByteOrder order) { return BitConverter.IsLittleEndian == (order == ByteOrder.Little); } public static bool IsLocal(this IPAddress address) { if (address == null) { return false; } if (address.Equals(IPAddress.Any)) { return true; } if (address.Equals(IPAddress.Loopback)) { return true; } if (Socket.OSSupportsIPv6) { if (address.Equals(IPAddress.IPv6Any)) { return true; } if (address.Equals(IPAddress.IPv6Loopback)) { return true; } } IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress obj in hostAddresses) { if (address.Equals(obj)) { return true; } } return false; } public static bool IsNullOrEmpty(this string value) { if (value != null) { return value.Length == 0; } return true; } public static bool IsPredefinedScheme(this string value) { if (value == null || value.Length < 2) { return false; } switch (value[0]) { case 'h': if (!(value == "http")) { return value == "https"; } return true; case 'w': if (!(value == "ws")) { return value == "wss"; } return true; case 'f': if (!(value == "file")) { return value == "ftp"; } return true; case 'g': return value == "gopher"; case 'm': return value == "mailto"; case 'n': { char c = value[1]; if (c != 'e') { return value == "nntp"; } if (!(value == "news") && !(value == "net.pipe")) { return value == "net.tcp"; } return true; } default: return false; } } public static bool IsUpgradeTo(this CustomWebSocketSharp.Net.HttpListenerRequest request, string protocol) { if (request == null) { throw new ArgumentNullException("request"); } if (protocol == null) { throw new ArgumentNullException("protocol"); } if (protocol.Length == 0) { throw new ArgumentException("An empty string.", "protocol"); } if (request.Headers.Contains("Upgrade", protocol)) { return request.Headers.Contains("Connection", "Upgrade"); } return false; } public static bool MaybeUri(this string value) { if (value == null || value.Length == 0) { return false; } int num = value.IndexOf(':'); if (num == -1) { return false; } if (num >= 10) { return false; } return value.Substring(0, num).IsPredefinedScheme(); } public static T[] SubArray<T>(this T[] array, int startIndex, int length) { int num; if (array == null || (num = array.Length) == 0) { return new T[0]; } if (startIndex < 0 || length <= 0 || startIndex + length > num) { return new T[0]; } if (startIndex == 0 && length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0, length); return array2; } public static T[] SubArray<T>(this T[] array, long startIndex, long length) { long num; if (array == null || (num = array.LongLength) == 0L) { return new T[0]; } if (startIndex < 0 || length <= 0 || startIndex + length > num) { return new T[0]; } if (startIndex == 0L && length == num) { return array; } T[] array2 = new T[length]; Array.Copy(array, startIndex, array2, 0L, length); return array2; } public static void Times(this int n, Action action) { if (n > 0 && action != null) { ((ulong)n).times(action); } } public static void Times(this long n, Action action) { if (n > 0 && action != null) { ((ulong)n).times(action); } } public static void Times(this uint n, Action action) { if (n != 0 && action != null) { times(n, action); } } public static void Times(this ulong n, Action action) { if (n != 0 && action != null) { n.times(action); } } public static void Times(this int n, Action<int> action) { if (n > 0 && action != null) { for (int i = 0; i < n; i++) { action(i); } } } public static void Times(this long n, Action<long> action) { if (n > 0 && action != null) { for (long num = 0L; num < n; num++) { action(num); } } } public static void Times(this uint n, Action<uint> action) { if (n != 0 && action != null) { for (uint num = 0u; num < n; num++) { action(num); } } } public static void Times(this ulong n, Action<ulong> action) { if (n != 0 && action != null) { for (ulong num = 0uL; num < n; num++) { action(num); } } } public static T To<T>(this byte[] source, ByteOrder sourceOrder) where T : struct { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length == 0) { return default(T); } Type typeFromHandle = typeof(T); byte[] value = source.ToHostOrder(sourceOrder); if ((object)typeFromHandle != typeof(bool)) { if ((object)typeFromHandle != typeof(char)) { if ((object)typeFromHandle != typeof(double)) { if ((object)typeFromHandle != typeof(short)) { if ((object)typeFromHandle != typeof(int)) { if ((object)typeFromHandle != typeof(long)) { if ((object)typeFromHandle != typeof(float)) { if ((object)typeFromHandle != typeof(ushort)) { if ((object)typeFromHandle != typeof(uint)) { if ((object)typeFromHandle != typeof(ulong)) { return default(T); } return (T)(object)BitConverter.ToUInt64(value, 0); } return (T)(object)BitConverter.ToUInt32(value, 0); } return (T)(object)BitConverter.ToUInt16(value, 0); } return (T)(object)BitConverter.ToSingle(value, 0); } return (T)(object)BitConverter.ToInt64(value, 0); } return (T)(object)BitConverter.ToInt32(value, 0); } return (T)(object)BitConverter.ToInt16(value, 0); } return (T)(object)BitConverter.ToDouble(value, 0); } return (T)(object)BitConverter.ToChar(value, 0); } return (T)(object)BitConverter.ToBoolean(value, 0); } public static byte[] ToByteArray<T>(this T value, ByteOrder order) where T : struct { Type typeFromHandle = typeof(T); byte[] array = (((object)typeFromHandle == typeof(bool)) ? BitConverter.GetBytes((bool)(object)value) : (((object)typeFromHandle != typeof(byte)) ? (((object)typeFromHandle == typeof(char)) ? BitConverter.GetBytes((char)(object)value) : (((object)typeFromHandle == typeof(double)) ? BitConverter.GetBytes((double)(object)value) : (((object)typeFromHandle == typeof(short)) ? BitConverter.GetBytes((short)(object)value) : (((object)typeFromHandle == typeof(int)) ? BitConverter.GetBytes((int)(object)value) : (((object)typeFromHandle == typeof(long)) ? BitConverter.GetBytes((long)(object)value) : (((object)typeFromHandle == typeof(float)) ? BitConverter.GetBytes((float)(object)value) : (((object)typeFromHandle == typeof(ushort)) ? BitConverter.GetBytes((ushort)(object)value) : (((object)typeFromHandle == typeof(uint)) ? BitConverter.GetBytes((uint)(object)value) : (((object)typeFromHandle == typeof(ulong)) ? BitConverter.GetBytes((ulong)(object)value) : WebSocket.EmptyBytes))))))))) : new byte[1] { (byte)(object)value })); if (array.Length > 1 && !order.IsHostOrder()) { Array.Reverse((Array)array); } return array; } public static byte[] ToHostOrder(this byte[] source, ByteOrder sourceOrder) { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length <= 1 || sourceOrder.IsHostOrder()) { return source; } return source.Reverse(); } public static string ToString<T>(this T[] array, string separator) { if (array == null) { throw new ArgumentNullException("array"); } int num = array.Length; if (num == 0) { return string.Empty; } if (separator == null) { separator = string.Empty; } StringBuilder buff = new StringBuilder(64); (num - 1).Times(delegate(int i) { buff.AppendFormat("{0}{1}", array[i].ToString(), separator); }); buff.Append(array[num - 1].ToString()); return buff.ToString(); } public static Uri ToUri(this string value) { Uri.TryCreate(value, value.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out Uri result); return result; } public static string UrlDecode(this string value) { if (value == null || value.Length <= 0) { return value; } return HttpUtility.UrlDecode(value); } public static string UrlEncode(this string value) { if (value == null || value.Length <= 0) { return value; } return HttpUtility.UrlEncode(value); } public static void WriteContent(this CustomWebSocketSharp.Net.HttpListenerResponse response, byte[] content) { if (response == null) { throw new ArgumentNullException("response"); } if (content == null) { throw new ArgumentNullException("content"); } long num = content.LongLength; if (num == 0L) { response.Close(); return; } response.ContentLength64 = num; Stream outputStream = response.OutputStream; if (num <= int.MaxValue) { outputStream.Write(content, 0, (int)num); } else { outputStream.WriteBytes(content, 1024); } outputStream.Close(); } } internal enum Fin : byte { More, Final } internal abstract class HttpBase { private NameValueCollection _headers; private const int _headersMaxLength = 8192; private Version _version; internal byte[] EntityBodyData; protected const string CrLf = "\r\n"; public string EntityBody { get { if (EntityBodyData == null || EntityBodyData.LongLength == 0L) { return string.Empty; } Encoding encoding = null; string text = _headers["Content-Type"]; if (text != null && text.Length > 0) { encoding = HttpUtility.GetEncoding(text); } return (encoding ?? Encoding.UTF8).GetString(EntityBodyData); } } public NameValueCollection Headers => _headers; public Version ProtocolVersion => _version; protected HttpBase(Version version, NameValueCollection headers) { _version = version; _headers = headers; } private static byte[] readEntityBody(Stream stream, string length) { if (!long.TryParse(length, out var result)) { throw new ArgumentException("Cannot be parsed.", "length"); } if (result < 0) { throw new ArgumentOutOfRangeException("length", "Less than zero."); } if (result <= 1024) { if (result <= 0) { return null; } return stream.ReadBytes((int)result); } return stream.ReadBytes(result, 1024); } private static string[] readHeaders(Stream stream, int maxLength) { List<byte> buff = new List<byte>(); int cnt = 0; Action<int> action = delegate(int i) { if (i == -1) { throw new EndOfStreamException("The header cannot be read from the data source."); } buff.Add((byte)i); cnt++; }; bool flag = false; while (cnt < maxLength) { if (stream.ReadByte().EqualsWith('\r', action) && stream.ReadByte().EqualsWith('\n', action) && stream.ReadByte().EqualsWith('\r', action) && stream.ReadByte().EqualsWith('\n', action)) { flag = true; break; } } if (!flag) { throw new WebSocketException("The length of header part is greater than the max length."); } return Encoding.UTF8.GetString(buff.ToArray()).Replace("\r\n ", " ").Replace("\r\n\t", " ") .Split(new string[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); } protected static T Read<T>(Stream stream, Func<string[], T> parser, int millisecondsTimeout) where T : HttpBase { bool timeout = false; System.Threading.Timer timer = new System.Threading.Timer(delegate { timeout = true; stream.Close(); }, null, millisecondsTimeout, -1); T val = null; Exception ex = null; try { val = parser(readHeaders(stream, 8192)); string text = val.Headers["Content-Length"]; if (text != null && text.Length > 0) { val.EntityBodyData = readEntityBody(stream, text); } } catch (Exception ex2) { ex = ex2; } finally { timer.Change(-1, -1); timer.Dispose(); } string text2 = (timeout ? "A timeout has occurred while reading an HTTP request/response." : ((ex != null) ? "An exception has occurred while reading an HTTP request/response." : null)); if (text2 != null) { throw new WebSocketException(text2, ex); } return val; } public byte[] ToByteArray() { return Encoding.UTF8.GetBytes(ToString()); } } internal class HttpRequest : HttpBase { private string _method; private string _uri; private bool _websocketRequest; private bool _websocketRequestSet; public AuthenticationResponse AuthenticationResponse { get { string text = base.Headers["Authorization"]; if (text == null || text.Length <= 0) { return null; } return AuthenticationResponse.Parse(text); } } public CustomWebSocketSharp.Net.CookieCollection Cookies => base.Headers.GetCookies(response: false); public string HttpMethod => _method; public bool IsWebSocketRequest { get { if (!_websocketRequestSet) { NameValueCollection headers = base.Headers; _websocketRequest = _method == "GET" && base.ProtocolVersion > CustomWebSocketSharp.Net.HttpVersion.Version10 && headers.Contains("Upgrade", "websocket") && headers.Contains("Connection", "Upgrade"); _websocketRequestSet = true; } return _websocketRequest; } } public string RequestUri => _uri; private HttpRequest(string method, string uri, Version version, NameValueCollection headers) : base(version, headers) { _method = method; _uri = uri; } internal HttpRequest(string method, string uri) : this(method, uri, CustomWebSocketSharp.Net.HttpVersion.Version11, new NameValueCollection()) { base.Headers["User-Agent"] = "websocket-sharp/1.0"; } internal static HttpRequest CreateConnectRequest(Uri uri) { string dnsSafeHost = uri.DnsSafeHost; int port = uri.Port; string text = $"{dnsSafeHost}:{port}"; HttpRequest httpRequest = new HttpRequest("CONNECT", text); httpRequest.Headers["Host"] = ((port == 80) ? dnsSafeHost : text); return httpRequest; } internal static HttpRequest CreateWebSocketRequest(Uri uri) { HttpRequest httpRequest = new HttpRequest("GET", uri.PathAndQuery); NameValueCollection headers = httpRequest.Headers; int port = uri.Port; string scheme = uri.Scheme; headers["Host"] = (((port == 80 && scheme == "ws") || (port == 443 && scheme == "wss")) ? uri.DnsSafeHost : uri.Authority); headers["Upgrade"] = "websocket"; headers["Connection"] = "Upgrade"; return httpRequest; } internal HttpResponse GetResponse(Stream stream, int millisecondsTimeout) { byte[] array = ToByteArray(); stream.Write(array, 0, array.Length); return HttpBase.Read(stream, HttpResponse.Parse, millisecondsTimeout); } internal static HttpRequest Parse(string[] headerParts) { string[] array = headerParts[0].Split(new char[1] { ' ' }, 3); if (array.Length != 3) { throw new ArgumentException("Invalid request line: " + headerParts[0]); } CustomWebSocketSharp.Net.WebHeaderCollection webHeaderCollection = new CustomWebSocketSharp.Net.WebHeaderCollection(); for (int i = 1; i < headerParts.Length; i++) { webHeaderCollection.InternalSet(headerParts[i], response: false); } return new HttpRequest(array[0], array[1], new Version(array[2].Substring(5)), webHeaderCollection); } internal static HttpRequest Read(Stream stream, int millisecondsTimeout) { return HttpBase.Read(stream, Parse, millisecondsTimeout); } public void SetCookies(CustomWebSocketSharp.Net.CookieCollection cookies) { if (cookies == null || cookies.Count == 0) { return; } StringBuilder stringBuilder = new StringBuilder(64); foreach (CustomWebSocketSharp.Net.Cookie item in cookies.Sorted) { if (!item.Expired) { stringBuilder.AppendFormat("{0}; ", item.ToString()); } } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; base.Headers["Cookie"] = stringBuilder.ToString(); } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(64); stringBuilder.AppendFormat("{0} {1} HTTP/{2}{3}", _method, _uri, base.ProtocolVersion, "\r\n"); NameValueCollection headers = base.Headers; string[] allKeys = headers.AllKeys; foreach (string text in allKeys) { stringBuilder.AppendFormat("{0}: {1}{2}", text, headers[text], "\r\n"); } stringBuilder.Append("\r\n"); string entityBody = base.EntityBody; if (entityBody.Length > 0) { stringBuilder.Append(entityBody); } return stringBuilder.ToString(); } } internal class HttpResponse : HttpBase { private string _code; private string _reason; public CustomWebSocketSharp.Net.CookieCollection Cookies => base.Headers.GetCookies(response: true); public bool HasConnectionClose => base.Headers.Contains("Connection", "close"); public bool IsProxyAuthenticationRequired => _code == "407"; public bool IsRedirect { get { if (!(_code == "301")) { return _code == "302"; } return true; } } public bool IsUnauthorized => _code == "401"; public bool IsWebSocketResponse { get { NameValueCollection headers = base.Headers; if (base.ProtocolVersion > CustomWebSocketSharp.Net.HttpVersion.Version10 && _code == "101" && headers.Contains("Upgrade", "websocket")) { return headers.Contains("Connection", "Upgrade"); } return false; } } public string Reason => _reason; public string StatusCode => _code; private HttpResponse(string code, string reason, Version version, NameValueCollection headers) : base(version, headers) { _code = code; _reason = reason; } internal HttpResponse(CustomWebSocketSharp.Net.HttpStatusCode code) : this(code, code.GetDescription()) { } internal HttpResponse(CustomWebSocketSharp.Net.HttpStatusCode code, string reason) : this(((int)code).ToString(), reason, CustomWebSocketSharp.Net.HttpVersion.Version11, new NameValueCollection()) { base.Headers["Server"] = "websocket-sharp/1.0"; } internal static HttpResponse CreateCloseResponse(CustomWebSocketSharp.Net.HttpStatusCode code) { HttpResponse httpResponse = new HttpResponse(code); httpResponse.Headers["Connection"] = "close"; return httpResponse; } internal static HttpResponse CreateUnauthorizedResponse(string challenge) { HttpResponse httpResponse = new HttpResponse(CustomWebSocketSharp.Net.HttpStatusCode.Unauthorized); httpResponse.Headers["WWW-Authenticate"] = challenge; return httpResponse; } internal static HttpResponse CreateWebSocketResponse() { HttpResponse httpResponse = new HttpResponse(CustomWebSocketSharp.Net.HttpStatusCode.SwitchingProtocols); NameValueCollection headers = httpResponse.Headers; headers["Upgrade"] = "websocket"; headers["Connection"] = "Upgrade"; return httpResponse; } internal static HttpResponse Parse(string[] headerParts) { string[] array = headerParts[0].Split(new char[1] { ' ' }, 3); if (array.Length != 3) { throw new ArgumentException("Invalid status line: " + headerParts[0]); } CustomWebSocketSharp.Net.WebHeaderCollection webHeaderCollection = new CustomWebSocketSharp.Net.WebHeaderCollection(); for (int i = 1; i < headerParts.Length; i++) { webHeaderCollection.InternalSet(headerParts[i], response: true); } return new HttpResponse(array[1], array[2], new Version(array[0].Substring(5)), webHeaderCollection); } internal static HttpResponse Read(Stream stream, int millisecondsTimeout) { return HttpBase.Read(stream, Parse, millisecondsTimeout); } public void SetCookies(CustomWebSocketSharp.Net.CookieCollection cookies) { if (cookies == null || cookies.Count == 0) { return; } NameValueCollection headers = base.Headers; foreach (CustomWebSocketSharp.Net.Cookie item in cookies.Sorted) { headers.Add("Set-Cookie", item.ToResponseString()); } } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(64); stringBuilder.AppendFormat("HTTP/{0} {1} {2}{3}", base.ProtocolVersion, _code, _reason, "\r\n"); NameValueCollection headers = base.Headers; string[] allKeys = headers.AllKeys; foreach (string text in allKeys) { stringBuilder.AppendFormat("{0}: {1}{2}", text, headers[text], "\r\n"); } stringBuilder.Append("\r\n"); string entityBody = base.EntityBody; if (entityBody.Length > 0) { stringBuilder.Append(entityBody); } return stringBuilder.ToString(); } } public class LogData { private StackFrame _caller; private DateTime _date; private LogLevel _level; private string _message; public StackFrame Caller => _caller; public DateTime Date => _date; public LogLevel Level => _level; public string Message => _message; internal LogData(LogLevel level, StackFrame caller, string message) { _level = level; _caller = caller; _message = message ?? string.Empty; _date = DateTime.Now; } public override string ToString() { string text = $"{_date}|{_level,-5}|"; MethodBase method = _caller.GetMethod(); Type declaringType = method.DeclaringType; string arg = $"{text}{declaringType.Name}.{method.Name}|"; string[] array = _message.Replace("\r\n", "\n").TrimEnd(new char[1] { '\n' }).Split(new char[1] { '\n' }); if (array.Length <= 1) { return $"{arg}{_message}"; } StringBuilder stringBuilder = new StringBuilder($"{arg}{array[0]}\n", 64); string format = $"{{0,{text.Length}}}{{1}}\n"; for (int i = 1; i < array.Length; i++) { stringBuilder.AppendFormat(format, "", array[i]); } stringBuilder.Length--; return stringBuilder.ToString(); } } public class Logger { private volatile string _file; private volatile LogLevel _level; private Action<LogData, string> _output; private object _sync; public string File { get { return _file; } set { lock (_sync) { _file = value; Warn($"The current path to the log file has been changed to {_file}."); } } } public LogLevel Level { get { return _level; } set { lock (_sync) { _level = value; Warn($"The current logging level has been changed to {_level}."); } } } public Action<LogData, string> Output { get { return _output; } set { lock (_sync) { _output = value ?? new Action<LogData, string>(defaultOutput); Warn("The current output action has been changed."); } } } public Logger() : this(LogLevel.Error, null, null) { } public Logger(LogLevel level) : this(level, null, null) { } public Logger(LogLevel level, string file, Action<LogData, string> output) { _level = level; _file = file; _output = output ?? new Action<LogData, string>(defaultOutput); _sync = new object(); } private static void defaultOutput(LogData data, string path) { string value = data.ToString(); Console.WriteLine(value); if (path != null && path.Length > 0) { writeToFile(value, path); } } private void output(string message, LogLevel level) { lock (_sync) { if (_level > level) { return; } LogData logData = null; try { logData = new LogData(level, new StackFrame(2, needFileInfo: true), message); _output(logData, _file); } catch (Exception ex) { logData = new LogData(LogLevel.Fatal, new StackFrame(0, needFileInfo: true), ex.Message); Console.WriteLine(logData.ToString()); } } } private static void writeToFile(string value, string path) { using StreamWriter writer = new StreamWriter(path, append: true); using TextWriter textWriter = TextWriter.Synchronized(writer); textWriter.WriteLine(value); } public void Debug(string message) { if (_level <= LogLevel.Debug) { output(message, LogLevel.Debug); } } public void Error(string message) { if (_level <= LogLevel.Error) { output(message, LogLevel.Error); } } public void Fatal(string message) { output(message, LogLevel.Fatal); } public void Info(string message) { if (_level <= LogLevel.Info) { output(message, LogLevel.Info); } } public void Trace(string message) { if (_level <= LogLevel.Trace) { output(message, LogLevel.Trace); } } public void Warn(string message) { if (_level <= LogLevel.Warn) { output(message, LogLevel.Warn); } } } public enum LogLevel { Trace, Debug, Info, Warn, Error, Fatal } internal enum Mask : byte { Off, On } public class MessageEventArgs : EventArgs { private string _data; private bool _dataSet; private Opcode _opcode; private byte[] _rawData; internal Opcode Opcode => _opcode; public string Data { get { setData(); return _data; } } public bool IsBinary => _opcode == Opcode.Binary; public bool IsPing => _opcode == Opcode.Ping; public bool IsText => _opcode == Opcode.Text; public byte[] RawData { get { setData(); return _rawData; } } internal MessageEventArgs(WebSocketFrame frame) { _opcode = frame.Opcode; _rawData = frame.PayloadData.ApplicationData; } internal MessageEventArgs(Opcode opcode, byte[] rawData) { if ((ulong)rawData.LongLength > PayloadData.MaxLength) { throw new WebSocketException(CloseStatusCode.TooBig); } _opcode = opcode; _rawData = rawData; } private void setData() { if (!_dataSet) { if (_opcode == Opcode.Binary) { _dataSet = true; return; } _data = _rawData.UTF8Decode(); _dataSet = true; } } } internal enum Opcode : byte { Cont = 0, Text = 1, Binary = 2, Close = 8, Ping = 9, Pong = 10 } internal class PayloadData : IEnumerable<byte>, IEnumerable { private ushort _code; private bool _codeSet; private byte[] _data; private long _extDataLength; private long _length; private string _reason; private bool _reasonSet; public static readonly PayloadData Empty; public static readonly ulong MaxLength; internal ushort Code { get { if (!_codeSet) { _code = (ushort)((_length > 1) ? _data.SubArray(0, 2).ToUInt16(ByteOrder.Big) : 1005); _codeSet = true; } return _code; } } internal long ExtensionDataLength { get { return _extDataLength; } set { _extDataLength = value; } } internal bool HasReservedCode { get { if (_length > 1) { return Code.IsReserved(); } return false; } } internal string Reason { get { if (!_reasonSet) { _reason = ((_length > 2) ? _data.SubArray(2L, _length - 2).UTF8Decode() : string.Empty); _reasonSet = true; } return _reason; } } public byte[] ApplicationData { get { if (_extDataLength <= 0) { return _data; } return _data.SubArray(_extDataLength, _length - _extDataLength); } } public byte[] ExtensionData { get { if (_extDataLength <= 0) { return WebSocket.EmptyBytes; } return _data.SubArray(0L, _extDataLength); } } public ulong Length => (ulong)_length; static PayloadData() { Empty = new PayloadData(); MaxLength = 9223372036854775807uL; } internal PayloadData() { _code = 1005; _reason = string.Empty; _data = WebSocket.EmptyBytes; _codeSet = true; _reasonSet = true; } internal PayloadData(byte[] data) : this(data, data.LongLength) { } internal PayloadData(byte[] data, long length) { _data = data; _length = length; } internal PayloadData(ushort code, string reason) { _code = code; _reason = reason ?? string.Empty; _data = code.Append(reason); _length = _data.LongLength; _codeSet = true; _reasonSet = true; } internal void Mask(byte[] key) { for (long num = 0L; num < _length; num++) { _data[num] ^= key[num % 4]; } } public IEnumerator<byte> GetEnumerator() { byte[] data = _data; for (int i = 0; i < data.Length; i++) { yield return data[i]; } } public byte[] ToArray() { return _data; } public override string ToString() { return BitConverter.ToString(_data); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal enum Rsv : byte { Off, On } public class WebSocket : IDisposable { private AuthenticationChallenge _authChallenge; private string _base64Key; private bool _client; private Action _closeContext; private CompressionMethod _compression; private WebSocketContext _context; private CustomWebSocketSharp.Net.CookieCollection _cookies; private CustomWebSocketSharp.Net.NetworkCredential _credentials; private bool _emitOnPing; private bool _enableRedirection; private string _extensions; private bool _extensionsRequested; private object _forMessageEventQueue; private object _forPing; private object _forSend; private object _forState; private MemoryStream _fragmentsBuffer; private bool _fragmentsCompressed; private Opcode _fragmentsOpcode; private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private Func<WebSocketContext, string> _handshakeRequestChecker; private bool _ignoreExtensions; private bool _inContinuation; private volatile bool _inMessage; private volatile Logger _logger; private static readonly int _maxRetryCountForConnect; private Action<MessageEventArgs> _message; private Queue<MessageEventArgs> _messageEventQueue; private uint _nonceCount; private string _origin; private ManualResetEvent _pongReceived; private bool _preAuth; private string _protocol; private string[] _protocols; private bool _protocolsRequested; private CustomWebSocketSharp.Net.NetworkCredential _proxyCredentials; private Uri _proxyUri; private volatile WebSocketState _readyState; private ManualResetEvent _receivingExited; private int _retryCountForConnect; private bool _secure; private ClientSslConfiguration _sslConfig; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private const string _version = "13"; private TimeSpan _waitTime; internal static readonly byte[] EmptyBytes; internal static readonly int FragmentLength; internal static readonly RandomNumberGenerator RandomNumber; internal CustomWebSocketSharp.Net.CookieCollection CookieCollection => _cookies; internal Func<WebSocketContext, string> CustomHandshakeRequestChecker { get { return _handshakeRequestChecker; } set { _handshakeRequestChecker = value; } } internal bool HasMessage { get { lock (_forMessageEventQueue) { return _messageEventQueue.Count > 0; } } } internal bool IgnoreExtensions { get { return _ignoreExtensions; } set { _ignoreExtensions = value; } } internal bool IsConnected { get { if (_readyState != WebSocketState.Open) { return _readyState == WebSocketState.Closing; } return true; } } public CompressionMethod Compression { get { return _compression; } set { if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in setting the compression.", null); return; } lock (_forState) { if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out text)) { _logger.Error(text); error("An error has occurred in setting the compression.", null); } else { _compression = value; } } } } public IEnumerable<CustomWebSocketSharp.Net.Cookie> Cookies { get { lock (_cookies.SyncRoot) { foreach (CustomWebSocketSharp.Net.Cookie cookie in _cookies) { yield return cookie; } } } } public CustomWebSocketSharp.Net.NetworkCredential Credentials => _credentials; public bool EmitOnPing { get { return _emitOnPing; } set { _emitOnPing = value; } } public bool EnableRedirection { get { return _enableRedirection; } set { lock (_forState) { if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in setting the enable redirection.", null); } else { _enableRedirection = value; } } } } public string Extensions => _extensions ?? string.Empty; public bool IsAlive => ping(EmptyBytes); public bool IsSecure => _secure; public Logger Log { get { return _logger; } internal set { _logger = value; } } public string Origin { get { return _origin; } set { lock (_forState) { Uri result; if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in setting the origin.", null); } else if (value.IsNullOrEmpty()) { _origin = value; } else if (!Uri.TryCreate(value, UriKind.Absolute, out result) || result.Segments.Length > 1) { _logger.Error("The syntax of an origin must be '<scheme>://<host>[:<port>]'."); error("An error has occurred in setting the origin.", null); } else { _origin = value.TrimEnd(new char[1] { '/' }); } } } } public string Protocol { get { return _protocol ?? string.Empty; } internal set { _protocol = value; } } public WebSocketState ReadyState => _readyState; public ClientSslConfiguration SslConfiguration { get { if (!_client) { return null; } return _sslConfig ?? (_sslConfig = new ClientSslConfiguration(_uri.DnsSafeHost)); } set { lock (_forState) { if (!checkIfAvailable(client: true, server: false, connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in setting the ssl configuration.", null); } else { _sslConfig = value; } } } } public Uri Url { get { if (!_client) { return _context.RequestUri; } return _uri; } } public TimeSpan WaitTime { get { return _waitTime; } set { lock (_forState) { if (!checkIfAvailable(client: true, server: true, connecting: true, open: false, closing: false, closed: true, out var text) || !value.CheckWaitTime(out text)) { _logger.Error(text); error("An error has occurred in setting the wait time.", null); } else { _waitTime = value; } } } } public event EventHandler<CloseEventArgs> OnClose; public event EventHandler<ErrorEventArgs> OnError; public event EventHandler<MessageEventArgs> OnMessage; public event EventHandler OnOpen; static WebSocket() { _maxRetryCountForConnect = 10; EmptyBytes = new byte[0]; FragmentLength = 1016; RandomNumber = new RNGCryptoServiceProvider(); } internal WebSocket(HttpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } internal WebSocket(TcpListenerWebSocketContext context, string protocol) { _context = context; _protocol = protocol; _closeContext = context.Close; _logger = context.Log; _message = messages; _secure = context.IsSecureConnection; _stream = context.Stream; _waitTime = TimeSpan.FromSeconds(1.0); init(); } public WebSocket(string url, params string[] protocols) { if (url == null) { throw new ArgumentNullException("url"); } if (url.Length == 0) { throw new ArgumentException("An empty string.", "url"); } if (!url.TryCreateWebSocketUri(out _uri, out var text)) { throw new ArgumentException(text, "url"); } if (protocols != null && protocols.Length != 0) { text = protocols.CheckIfValidProtocols(); if (text != null) { throw new ArgumentException(text, "protocols"); } _protocols = protocols; } _base64Key = CreateBase64Key(); _client = true; _logger = new Logger(); _message = messagec; _secure = _uri.Scheme == "wss"; _waitTime = TimeSpan.FromSeconds(5.0); init(); } private bool accept() { lock (_forState) { if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: false, out var text)) { _logger.Error(text); error("An error has occurred in accepting.", null); return false; } try { if (!acceptHandshake()) { return false; } _readyState = WebSocketState.Open; } catch (Exception ex) { _logger.Fatal(ex.ToString()); fatal("An exception has occurred while accepting.", ex); return false; } return true; } } private bool acceptHandshake() { _logger.Debug($"A request from {_context.UserEndPoint}:\n{_context}"); if (!checkHandshakeRequest(_context, out var text)) { sendHttpResponse(createHandshakeFailureResponse(CustomWebSocketSharp.Net.HttpStatusCode.BadRequest)); _logger.Fatal(text); fatal("An error has occurred while accepting.", CloseStatusCode.ProtocolError); return false; } if (!customCheckHandshakeRequest(_context, out text)) { sendHttpResponse(createHandshakeFailureResponse(CustomWebSocketSharp.Net.HttpStatusCode.BadRequest)); _logger.Fatal(text); fatal("An error has occurred while accepting.", CloseStatusCode.PolicyViolation); return false; } _base64Key = _context.Headers["Sec-WebSocket-Key"]; if (_protocol != null) { processSecWebSocketProtocolHeader(_context.SecWebSocketProtocols); } if (!_ignoreExtensions) { processSecWebSocketExtensionsClientHeader(_context.Headers["Sec-WebSocket-Extensions"]); } return sendHttpResponse(createHandshakeResponse()); } private bool checkHandshakeRequest(WebSocketContext context, out string message) { message = null; if (context.RequestUri == null) { message = "Specifies an invalid Request-URI."; return false; } if (!context.IsWebSocketRequest) { message = "Not a WebSocket handshake request."; return false; } NameValueCollection headers = context.Headers; if (!validateSecWebSocketKeyHeader(headers["Sec-WebSocket-Key"])) { message = "Includes no Sec-WebSocket-Key header, or it has an invalid value."; return false; } if (!validateSecWebSocketVersionClientHeader(headers["Sec-WebSocket-Version"])) { message = "Includes no Sec-WebSocket-Version header, or it has an invalid value."; return false; } if (!validateSecWebSocketProtocolClientHeader(headers["Sec-WebSocket-Protocol"])) { message = "Includes an invalid Sec-WebSocket-Protocol header."; return false; } if (!_ignoreExtensions && !validateSecWebSocketExtensionsClientHeader(headers["Sec-WebSocket-Extensions"])) { message = "Includes an invalid Sec-WebSocket-Extensions header."; return false; } return true; } private bool checkHandshakeResponse(HttpResponse response, out string message) { message = null; if (response.IsRedirect) { message = "Indicates the redirection."; return false; } if (response.IsUnauthorized) { message = "Requires the authentication."; return false; } if (!response.IsWebSocketResponse) { message = "Not a WebSocket handshake response."; return false; } NameValueCollection headers = response.Headers; if (!validateSecWebSocketAcceptHeader(headers["Sec-WebSocket-Accept"])) { message = "Includes no Sec-WebSocket-Accept header, or it has an invalid value."; return false; } if (!validateSecWebSocketProtocolServerHeader(headers["Sec-WebSocket-Protocol"])) { message = "Includes no Sec-WebSocket-Protocol header, or it has an invalid value."; return false; } if (!validateSecWebSocketExtensionsServerHeader(headers["Sec-WebSocket-Extensions"])) { message = "Includes an invalid Sec-WebSocket-Extensions header."; return false; } if (!validateSecWebSocketVersionServerHeader(headers["Sec-WebSocket-Version"])) { message = "Includes an invalid Sec-WebSocket-Version header."; return false; } return true; } private bool checkIfAvailable(bool connecting, bool open, bool closing, bool closed, out string message) { message = null; if (!connecting && _readyState == WebSocketState.Connecting) { message = "This operation is not available in: connecting"; return false; } if (!open && _readyState == WebSocketState.Open) { message = "This operation is not available in: open"; return false; } if (!closing && _readyState == WebSocketState.Closing) { message = "This operation is not available in: closing"; return false; } if (!closed && _readyState == WebSocketState.Closed) { message = "This operation is not available in: closed"; return false; } return true; } private bool checkIfAvailable(bool client, bool server, bool connecting, bool open, bool closing, bool closed, out string message) { message = null; if (!client && _client) { message = "This operation is not available in: client"; return false; } if (!server && !_client) { message = "This operation is not available in: server"; return false; } return checkIfAvailable(connecting, open, closing, closed, out message); } private static bool checkParametersForSetCredentials(string username, string password, out string message) { message = null; if (username.IsNullOrEmpty()) { return true; } if (Ext.Contains(username, ':') || !username.IsText()) { message = "'username' contains an invalid character."; return false; } if (password.IsNullOrEmpty()) { return true; } if (!password.IsText()) { message = "'password' contains an invalid character."; return false; } return true; } private static bool checkParametersForSetProxy(string url, string username, string password, out string message) { message = null; if (url.IsNullOrEmpty()) { return true; } if (!Uri.TryCreate(url, UriKind.Absolute, out Uri result) || result.Scheme != "http" || result.Segments.Length > 1) { message = "'url' is an invalid URL."; return false; } if (username.IsNullOrEmpty()) { return true; } if (Ext.Contains(username, ':') || !username.IsText()) { message = "'username' contains an invalid character."; return false; } if (password.IsNullOrEmpty()) { return true; } if (!password.IsText()) { message = "'password' contains an invalid character."; return false; } return true; } private bool checkReceivedFrame(WebSocketFrame frame, out string message) { message = null; bool isMasked = frame.IsMasked; if (_client && isMasked) { message = "A frame from the server is masked."; return false; } if (!_client && !isMasked) { message = "A frame from a client is not masked."; return false; } if (_inContinuation && frame.IsData) { message = "A data frame has been received while receiving continuation frames."; return false; } if (frame.IsCompressed && _compression == CompressionMethod.None) { message = "A compressed frame has been received without any agreement for it."; return false; } if (frame.Rsv2 == Rsv.On) { message = "The RSV2 of a frame is non-zero without any negotiation for it."; return false; } if (frame.Rsv3 == Rsv.On) { message = "The RSV3 of a frame is non-zero without any negotiation for it."; return false; } return true; } private void close(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { close(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); close(new PayloadData(code, reason), receive, receive, received: false); } private void close(PayloadData payloadData, bool send, bool receive, bool received) { lock (_forState) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } send = send && _readyState == WebSocketState.Open; receive = send && receive; _readyState = WebSocketState.Closing; } _logger.Trace("Begin closing the connection."); bool wasClean = closeHandshake(payloadData, send, receive, received); releaseResources(); _logger.Trace("End closing the connection."); _readyState = WebSocketState.Closed; CloseEventArgs closeEventArgs = new CloseEventArgs(payloadData); closeEventArgs.WasClean = wasClean; try { this.OnClose.Emit(this, closeEventArgs); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the OnClose event.", ex); } } private void closeAsync(ushort code, string reason) { if (_readyState == WebSocketState.Closing) { _logger.Info("The closing is already in progress."); return; } if (_readyState == WebSocketState.Closed) { _logger.Info("The connection has already been closed."); return; } if (code == 1005) { closeAsync(PayloadData.Empty, send: true, receive: true, received: false); return; } bool receive = !code.IsReserved(); closeAsync(new PayloadData(code, reason), receive, receive, received: false); } private void closeAsync(PayloadData payloadData, bool send, bool receive, bool received) { Action<PayloadData, bool, bool, bool> closer = close; closer.BeginInvoke(payloadData, send, receive, received, delegate(IAsyncResult ar) { closer.EndInvoke(ar); }, null); } private bool closeHandshake(byte[] frameAsBytes, bool receive, bool received) { bool flag = frameAsBytes != null && sendBytes(frameAsBytes); if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool closeHandshake(PayloadData payloadData, bool send, bool receive, bool received) { bool flag = false; if (send) { WebSocketFrame webSocketFrame = WebSocketFrame.CreateCloseFrame(payloadData, _client); flag = sendBytes(webSocketFrame.ToArray()); if (_client) { webSocketFrame.Unmask(); } } if (!received && flag && receive && _receivingExited != null) { received = _receivingExited.WaitOne(_waitTime); } bool flag2 = flag && received; _logger.Debug($"Was clean?: {flag2}\n sent: {flag}\n received: {received}"); return flag2; } private bool connect() { lock (_forState) { if (!checkIfAvailable(connecting: true, open: false, closing: false, closed: true, out var text)) { _logger.Error(text); error("An error has occurred in connecting.", null); return false; } if (_retryCountForConnect > _maxRetryCountForConnect) { _retryCountForConnect = 0; _logger.Fatal("A series of reconnecting has failed."); return false; } _readyState = WebSocketState.Connecting; try { doHandshake(); } catch (Exception ex) { _retryCountForConnect++; _logger.Fatal(ex.ToString()); fatal("An exception has occurred while connecting.", ex); return false; } _retryCountForConnect = 1; _readyState = WebSocketState.Open; return true; } } private string createExtensions() { StringBuilder stringBuilder = new StringBuilder(80); if (_compression != 0) { string arg = _compression.ToExtensionString("server_no_context_takeover", "client_no_context_takeover"); stringBuilder.AppendFormat("{0}, ", arg); } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; return stringBuilder.ToString(); } return null; } private HttpResponse createHandshakeFailureResponse(CustomWebSocketSharp.Net.HttpStatusCode code) { HttpResponse httpResponse = HttpResponse.CreateCloseResponse(code); httpResponse.Headers["Sec-WebSocket-Version"] = "13"; return httpResponse; } private HttpRequest createHandshakeRequest() { HttpRequest httpRequest = HttpRequest.CreateWebSocketRequest(_uri); NameValueCollection headers = httpRequest.Headers; if (!_origin.IsNullOrEmpty()) { headers["Origin"] = _origin; } headers["Sec-WebSocket-Key"] = _base64Key; _protocolsRequested = _protocols != null; if (_protocolsRequested) { headers["Sec-WebSocket-Protocol"] = _protocols.ToString(", "); } _extensionsRequested = _compression != CompressionMethod.None; if (_extensionsRequested) { headers["Sec-WebSocket-Extensions"] = createExtensions(); } headers["Sec-WebSocket-Version"] = "13"; AuthenticationResponse authenticationResponse = null; if (_authChallenge != null && _credentials != null) { authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; } else if (_preAuth) { authenticationResponse = new AuthenticationResponse(_credentials); } if (authenticationResponse != null) { headers["Authorization"] = authenticationResponse.ToString(); } if (_cookies.Count > 0) { httpRequest.SetCookies(_cookies); } return httpRequest; } private HttpResponse createHandshakeResponse() { HttpResponse httpResponse = HttpResponse.CreateWebSocketResponse(); NameValueCollection headers = httpResponse.Headers; headers["Sec-WebSocket-Accept"] = CreateResponseKey(_base64Key); if (_protocol != null) { headers["Sec-WebSocket-Protocol"] = _protocol; } if (_extensions != null) { headers["Sec-WebSocket-Extensions"] = _extensions; } if (_cookies.Count > 0) { httpResponse.SetCookies(_cookies); } return httpResponse; } private bool customCheckHandshakeRequest(WebSocketContext context, out string message) { message = null; if (_handshakeRequestChecker != null) { return (message = _handshakeRequestChecker(context)) == null; } return true; } private MessageEventArgs dequeueFromMessageEventQueue() { lock (_forMessageEventQueue) { return (_messageEventQueue.Count > 0) ? _messageEventQueue.Dequeue() : null; } } private void doHandshake() { setClientStream(); HttpResponse httpResponse = sendHandshakeRequest(); if (!checkHandshakeResponse(httpResponse, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } if (_protocolsRequested) { _protocol = httpResponse.Headers["Sec-WebSocket-Protocol"]; } if (_extensionsRequested) { processSecWebSocketExtensionsServerHeader(httpResponse.Headers["Sec-WebSocket-Extensions"]); } processCookies(httpResponse.Cookies); } private void enqueueToMessageEventQueue(MessageEventArgs e) { lock (_forMessageEventQueue) { _messageEventQueue.Enqueue(e); } } private void error(string message, Exception exception) { try { this.OnError.Emit(this, new ErrorEventArgs(message, exception)); } catch (Exception ex) { _logger.Error(ex.ToString()); } } private void fatal(string message, Exception exception) { CloseStatusCode code = ((exception is WebSocketException) ? ((WebSocketException)exception).Code : CloseStatusCode.Abnormal); fatal(message, (ushort)code); } private void fatal(string message, ushort code) { PayloadData payloadData = new PayloadData(code, message); close(payloadData, !code.IsReserved(), receive: false, received: false); } private void fatal(string message, CloseStatusCode code) { fatal(message, (ushort)code); } private void init() { _compression = CompressionMethod.None; _cookies = new CustomWebSocketSharp.Net.CookieCollection(); _forPing = new object(); _forSend = new object(); _forState = new object(); _messageEventQueue = new Queue<MessageEventArgs>(); _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot; _readyState = WebSocketState.Connecting; } private void message() { MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_inMessage || _messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { return; } _inMessage = true; obj = _messageEventQueue.Dequeue(); } _message(obj); } private void messagec(MessageEventArgs e) { while (true) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; break; } e = _messageEventQueue.Dequeue(); } } } private void messages(MessageEventArgs e) { try { this.OnMessage.Emit(this, e); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during an OnMessage event.", ex); } lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } e = _messageEventQueue.Dequeue(); } ThreadPool.QueueUserWorkItem(delegate { messages(e); }); } private void open() { _inMessage = true; startReceiving(); try { this.OnOpen.Emit(this, EventArgs.Empty); } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the OnOpen event.", ex); } MessageEventArgs obj = null; lock (_forMessageEventQueue) { if (_messageEventQueue.Count == 0 || _readyState != WebSocketState.Open) { _inMessage = false; return; } obj = _messageEventQueue.Dequeue(); } _message.BeginInvoke(obj, delegate(IAsyncResult ar) { _message.EndInvoke(ar); }, null); } private bool ping(byte[] data) { if (_readyState != WebSocketState.Open) { return false; } ManualResetEvent pongReceived = _pongReceived; if (pongReceived == null) { return false; } lock (_forPing) { try { pongReceived.Reset(); if (!send(Fin.Final, Opcode.Ping, data, compressed: false)) { return false; } return pongReceived.WaitOne(_waitTime); } catch (ObjectDisposedException) { return false; } } } private bool processCloseFrame(WebSocketFrame frame) { PayloadData payloadData = frame.PayloadData; close(payloadData, !payloadData.HasReservedCode, receive: false, received: true); return false; } private void processCookies(CustomWebSocketSharp.Net.CookieCollection cookies) { if (cookies.Count != 0) { _cookies.SetOrRemove(cookies); } } private bool processDataFrame(WebSocketFrame frame) { enqueueToMessageEventQueue(frame.IsCompressed ? new MessageEventArgs(frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression)) : new MessageEventArgs(frame)); return true; } private bool processFragmentFrame(WebSocketFrame frame) { if (!_inContinuation) { if (frame.IsContinuation) { return true; } _fragmentsOpcode = frame.Opcode; _fragmentsCompressed = frame.IsCompressed; _fragmentsBuffer = new MemoryStream(); _inContinuation = true; } _fragmentsBuffer.WriteBytes(frame.PayloadData.ApplicationData, 1024); if (frame.IsFinal) { using (_fragmentsBuffer) { byte[] rawData = (_fragmentsCompressed ? _fragmentsBuffer.DecompressToArray(_compression) : _fragmentsBuffer.ToArray()); enqueueToMessageEventQueue(new MessageEventArgs(_fragmentsOpcode, rawData)); } _fragmentsBuffer = null; _inContinuation = false; } return true; } private bool processPingFrame(WebSocketFrame frame) { WebSocketFrame webSocketFrame = WebSocketFrame.CreatePongFrame(frame.PayloadData, _client); lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The state of the connection has been changed."); return true; } if (!sendBytes(webSocketFrame.ToArray())) { return false; } } _logger.Trace("A pong has been sent to respond to this ping."); if (_emitOnPing) { if (_client) { webSocketFrame.Unmask(); } enqueueToMessageEventQueue(new MessageEventArgs(frame)); } return true; } private bool processPongFrame(WebSocketFrame frame) { try { _pongReceived.Set(); } catch (NullReferenceException) { return false; } catch (ObjectDisposedException) { return false; } _logger.Trace("It has been signaled that a pong was received."); return true; } private bool processReceivedFrame(WebSocketFrame frame) { if (!checkReceivedFrame(frame, out var text)) { throw new WebSocketException(CloseStatusCode.ProtocolError, text); } frame.Unmask(); if (!frame.IsFragment) { if (!frame.IsData) { if (!frame.IsPing) { if (!frame.IsPong) { if (!frame.IsClose) { return processUnsupportedFrame(frame); } return processCloseFrame(frame); } return processPongFrame(frame); } return processPingFrame(frame); } return processDataFrame(frame); } return processFragmentFrame(frame); } private void processSecWebSocketExtensionsClientHeader(string value) { if (value == null) { return; } StringBuilder stringBuilder = new StringBuilder(80); bool flag = false; foreach (string item in value.SplitHeaderValue(',')) { string value2 = item.Trim(); if (!flag && value2.IsCompressionExtension(CompressionMethod.Deflate)) { _compression = CompressionMethod.Deflate; stringBuilder.AppendFormat("{0}, ", _compression.ToExtensionString("client_no_context_takeover", "server_no_context_takeover")); flag = true; } } int length = stringBuilder.Length; if (length > 2) { stringBuilder.Length = length - 2; _extensions = stringBuilder.ToString(); } } private void processSecWebSocketExtensionsServerHeader(string value) { if (value == null) { _compression = CompressionMethod.None; } else { _extensions = value; } } private void processSecWebSocketProtocolHeader(IEnumerable<string> values) { if (!values.Contains((string p) => p == _protocol)) { _protocol = null; } } private bool processUnsupportedFrame(WebSocketFrame frame) { _logger.Fatal("An unsupported frame:" + frame.PrintToString(dumped: false)); fatal("There is no way to handle it.", CloseStatusCode.PolicyViolation); return false; } private void releaseClientResources() { if (_stream != null) { _stream.Dispose(); _stream = null; } if (_tcpClient != null) { _tcpClient.Close(); _tcpClient = null; } } private void releaseCommonResources() { if (_fragmentsBuffer != null) { _fragmentsBuffer.Dispose(); _fragmentsBuffer = null; _inContinuation = false; } if (_pongReceived != null) { _pongReceived.Close(); _pongReceived = null; } if (_receivingExited != null) { _receivingExited.Close(); _receivingExited = null; } } private void releaseResources() { if (_client) { releaseClientResources(); } else { releaseServerResources(); } releaseCommonResources(); } private void releaseServerResources() { if (_closeContext != null) { _closeContext(); _closeContext = null; _stream = null; _context = null; } } private bool send(Opcode opcode, Stream stream) { lock (_forSend) { Stream stream2 = stream; bool flag = false; bool flag2 = false; try { if (_compression != 0) { stream = stream.Compress(_compression); flag = true; } flag2 = send(opcode, stream, flag); if (!flag2) { error("A send has been interrupted.", null); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during a send.", ex); } finally { if (flag) { stream.Dispose(); } stream2.Dispose(); } return flag2; } } private bool send(Opcode opcode, Stream stream, bool compressed) { long length = stream.Length; if (length == 0L) { return send(Fin.Final, opcode, EmptyBytes, compressed: false); } long num = length / FragmentLength; int num2 = (int)(length % FragmentLength); byte[] array = null; switch (num) { case 0L: array = new byte[num2]; if (stream.Read(array, 0, num2) == num2) { return send(Fin.Final, opcode, array, compressed); } return false; case 1L: if (num2 == 0) { array = new byte[FragmentLength]; if (stream.Read(array, 0, FragmentLength) == FragmentLength) { return send(Fin.Final, opcode, array, compressed); } return false; } break; } array = new byte[FragmentLength]; if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, opcode, array, compressed)) { return false; } long num3 = ((num2 == 0) ? (num - 2) : (num - 1)); for (long num4 = 0L; num4 < num3; num4++) { if (stream.Read(array, 0, FragmentLength) != FragmentLength || !send(Fin.More, Opcode.Cont, array, compressed: false)) { return false; } } if (num2 == 0) { num2 = FragmentLength; } else { array = new byte[num2]; } if (stream.Read(array, 0, num2) == num2) { return send(Fin.Final, Opcode.Cont, array, compressed: false); } return false; } private bool send(Fin fin, Opcode opcode, byte[] data, bool compressed) { lock (_forState) { if (_readyState != WebSocketState.Open) { _logger.Error("The state of the connection has been changed."); return false; } WebSocketFrame webSocketFrame = new WebSocketFrame(fin, opcode, data, compressed, _client); return sendBytes(webSocketFrame.ToArray()); } } private void sendAsync(Opcode opcode, Stream stream, Action<bool> completed) { Func<Opcode, Stream, bool> sender = send; sender.BeginInvoke(opcode, stream, delegate(IAsyncResult ar) { try { bool obj = sender.EndInvoke(ar); if (completed != null) { completed(obj); } } catch (Exception ex) { _logger.Error(ex.ToString()); error("An error has occurred during the callback for an async send.", ex); } }, null); } private bool sendBytes(byte[] bytes) { try { _stream.Write(bytes, 0, bytes.Length); return true; } catch (Exception ex) { _logger.Error(ex.ToString()); return false; } } private HttpResponse sendHandshakeRequest() { HttpRequest httpRequest = createHandshakeRequest(); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsUnauthorized) { string text = httpResponse.Headers["WWW-Authenticate"]; _logger.Warn($"Received an authentication requirement for '{text}'."); if (text.IsNullOrEmpty()) { _logger.Error("No authentication challenge is specified."); return httpResponse; } _authChallenge = AuthenticationChallenge.Parse(text); if (_authChallenge == null) { _logger.Error("An invalid authentication challenge is specified."); return httpResponse; } if (_credentials != null && (!_preAuth || _authChallenge.Scheme == CustomWebSocketSharp.Net.AuthenticationSchemes.Digest)) { if (httpResponse.HasConnectionClose) { releaseClientResources(); setClientStream(); } AuthenticationResponse authenticationResponse = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authenticationResponse.NonceCount; httpRequest.Headers["Authorization"] = authenticationResponse.ToString(); httpResponse = sendHttpRequest(httpRequest, 15000); } } if (httpResponse.IsRedirect) { string text2 = httpResponse.Headers["Location"]; _logger.Warn($"Received a redirection to '{text2}'."); if (_enableRedirection) { if (text2.IsNullOrEmpty()) { _logger.Error("No url to redirect is located."); return httpResponse; } if (!text2.TryCreateWebSocketUri(out var result, out var text3)) { _logger.Error("An invalid url to redirect is located: " + text3); return httpResponse; } releaseClientResources(); _uri = result; _secure = result.Scheme == "wss"; setClientStream(); return sendHandshakeRequest(); } } return httpResponse; } private HttpResponse sendHttpRequest(HttpRequest request, int millisecondsTimeout) { _logger.Debug("A request to the server:\n" + request.ToString()); HttpResponse response = request.GetResponse(_stream, millisecondsTimeout); _logger.Debug("A response to this request:\n" + response.ToString()); return response; } private bool sendHttpResponse(HttpResponse response) { _logger.Debug("A response to this request:\n" + response.ToString()); return sendBytes(response.ToByteArray()); } private void sendProxyConnectRequest() { HttpRequest httpRequest = HttpRequest.CreateConnectRequest(_uri); HttpResponse httpResponse = sendHttpRequest(httpRequest, 90000); if (httpResponse.IsProxyAuthenticationRequired) { string text = httpResponse.Headers["Proxy-Authenticate"]; _logger.Warn($"Received a proxy authentication requirement for '{text}'."); if (text.IsNullOrEmpty()) { throw new WebSocketException("No proxy authentication challenge is specified."); } AuthenticationChallenge authenticationChallenge = AuthenticationChallenge.Parse(text); if (authenticationChallenge == null) { throw new WebSocketException("An invalid proxy authentication challenge is specified."); } if (_proxyCredentials != null) { if (httpResponse.HasConnectionClose) { releaseClientResources(); _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); } AuthenticationResponse authenticationResponse = new AuthenticationResponse(authenticationChallenge, _proxyCredentials, 0u); httpRequest.Headers["Proxy-Authorization"] = authenticationResponse.ToString(); httpResponse = sendHttpRequest(httpRequest, 15000); } if (httpResponse.IsProxyAuthenticationRequired) { throw new WebSocketException("A proxy authentication is required."); } } if (httpResponse.StatusCode[0] != '2') { throw new WebSocketException("The proxy has failed a connection to the requested host and port."); } } private void setClientStream() { if (_proxyUri != null) { _tcpClient = new TcpClient(_proxyUri.DnsSafeHost, _proxyUri.Port); _stream = _tcpClient.GetStream(); sendProxyConnectRequest(); } else { _tcpClient = new TcpClient(_uri.DnsSafeHost, _uri.Port); _stream = _tcpClient.GetStream(); } if (_secure) { ClientSslConfiguration sslConfiguration = SslConfiguration; string targetHost = sslConfiguration.TargetHost; if (targetHost != _uri.DnsSafeHost) { throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, "An invalid host name is specified."); } try { SslStream sslStream = new SslStream(_stream, leaveInnerStreamOpen: false, sslConfiguration.ServerCertificateValidationCallback, sslConfiguration.ClientCertificateSelectionCallback); sslStream.AuthenticateAsClient(targetHost, sslConfiguration.ClientCertificates, sslConfiguration.EnabledSslProtocols, sslConfiguration.CheckCertificateRevocation); _stream = sslStream; } catch (Exception innerException) { throw new WebSocketException(CloseStatusCode.TlsHandshakeFailure, innerException); } } } private void startReceiving() { if (_messageEventQueue.Count > 0) { _messageEventQueue.Clear(); } _pongReceived = new ManualResetEvent(initialState: false); _receivingExited = new ManualResetEvent(initialState: false); Action receive = null; receive = delegate { WebSocketFrame.ReadFrameAsync(_stream, unmask: false, delegate(WebSocketFrame frame) { if (!processReceivedFrame(frame) || _readyState == WebSocketState.Closed) { _receivingExited?.Set(); } else { receive(); if (!_inMessage && HasMessage && _readyState == WebSocketState.Open) { message(); } } }, delegate(Exception ex) { _logger.Fatal(ex.ToString()); fatal("An exception has occurred while receiving.", ex); }); }; receive(); } private bool validateSecWebSocketAcceptHeader(string value) { if (value != null) { return value == CreateResponseKey(_base64Key); } return false; } private bool validateSecWebSocketExtensionsClientHeader(string value) { if (value != null) { return value.Length > 0; } return true; } private bool validateSecWebSocketExtensionsServerHeader(string value) { if (value == null) { return true; } if (value.Length == 0) { return false; } if (!_extensionsRequested) { return false; } bool flag = _compression != CompressionMethod.None; foreach (string item in value.SplitHeaderValue(',')) { string text = item.Trim(); if (flag && text.IsCompressionExtension(_compression)) { if (!text.Contains("server_no_context_takeover")) { _logger.Error("The server hasn't sent back 'server_no_context_takeover'."); return false; } if (!text.Contains("client_no_context_takeover")) { _logger.Warn("The server hasn't sent back 'client_no_context_takeover'."); } string method = _compression.ToExtensionString(); if (text.SplitHeaderValue(';').Contains(delegate(string t) { t = t.Trim(); return t != method && t != "server_no_context_takeover" && t != "client_no_context_takeover"; })) { return false; } continue; } return false; } return true; } private bool validateSecWebSocketKeyHeader(string value) { if (value != null) { return value.Length > 0; } return false; } private bool validateSecWebSo
plugins/Valheim_Data/Managed/final_ik.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using RootMotion.FinalIK; using UnityEngine; using UnityEngine.Events; using UnityEngine.Serialization; using Valve.VR; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] namespace RootMotion.Demos { public class AimBoxing : MonoBehaviour { public AimIK aimIK; public Transform pin; private void LateUpdate() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) aimIK.solver.transform.LookAt(pin.position); aimIK.solver.IKPosition = ((Component)this).transform.position; } } public class AimSwing : MonoBehaviour { public AimIK ik; [Tooltip("The direction of the animated weapon swing in character space. Tweak this value to adjust the aiming.")] public Vector3 animatedSwingDirection = Vector3.forward; private void LateUpdate() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) ik.solver.axis = ik.solver.transform.InverseTransformVector(((Component)ik).transform.rotation * animatedSwingDirection); } } public class SecondHandOnGun : MonoBehaviour { public AimIK aim; public LimbIK leftArmIK; public Transform leftHand; public Transform rightHand; public Vector3 leftHandPositionOffset; public Vector3 leftHandRotationOffset; private Vector3 leftHandPosRelToRight; private Quaternion leftHandRotRelToRight; private void Start() { ((Behaviour)aim).enabled = false; ((Behaviour)leftArmIK).enabled = false; } private void LateUpdate() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) leftHandPosRelToRight = rightHand.InverseTransformPoint(leftHand.position); leftHandRotRelToRight = Quaternion.Inverse(rightHand.rotation) * leftHand.rotation; aim.solver.Update(); leftArmIK.solver.IKPosition = rightHand.TransformPoint(leftHandPosRelToRight + leftHandPositionOffset); leftArmIK.solver.IKRotation = rightHand.rotation * Quaternion.Euler(leftHandRotationOffset) * leftHandRotRelToRight; leftArmIK.solver.Update(); } } public class SimpleAimingSystem : MonoBehaviour { [Tooltip("AimPoser is a tool that returns an animation name based on direction.")] public AimPoser aimPoser; [Tooltip("Reference to the AimIK component.")] public AimIK aim; [Tooltip("Reference to the LookAt component (only used for the head in this instance).")] public LookAtIK lookAt; [Tooltip("Reference to the Animator component.")] public Animator animator; [Tooltip("Time of cross-fading from pose to pose.")] public float crossfadeTime = 0.2f; [Tooltip("Will keep the aim target at a distance.")] public float minAimDistance = 0.5f; private AimPoser.Pose aimPose; private AimPoser.Pose lastPose; private void Start() { ((Behaviour)aim).enabled = false; ((Behaviour)lookAt).enabled = false; } private void LateUpdate() { if ((Object)(object)aim.solver.target == (Object)null) { Debug.LogWarning((object)"AimIK and LookAtIK need to have their 'Target' value assigned.", (Object)(object)((Component)this).transform); } Pose(); aim.solver.Update(); if ((Object)(object)lookAt != (Object)null) { lookAt.solver.Update(); } } private void Pose() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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) LimitAimTarget(); Vector3 val = aim.solver.target.position - aim.solver.bones[0].transform.position; Vector3 localDirection = ((Component)this).transform.InverseTransformDirection(val); aimPose = aimPoser.GetPose(localDirection); if (aimPose != lastPose) { aimPoser.SetPoseActive(aimPose); lastPose = aimPose; } AimPoser.Pose[] poses = aimPoser.poses; foreach (AimPoser.Pose pose in poses) { if (pose == aimPose) { DirectCrossFade(pose.name, 1f); } else { DirectCrossFade(pose.name, 0f); } } } private void LimitAimTarget() { //IL_0017: 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) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) Vector3 position = aim.solver.bones[0].transform.position; Vector3 val = aim.solver.target.position - position; val = ((Vector3)(ref val)).normalized * Mathf.Max(((Vector3)(ref val)).magnitude, minAimDistance); aim.solver.target.position = position + val; } private void DirectCrossFade(string state, float target) { float num = Mathf.MoveTowards(animator.GetFloat(state), target, Time.deltaTime * (1f / crossfadeTime)); animator.SetFloat(state, num); } } public class TerrainOffset : MonoBehaviour { public AimIK aimIK; public Vector3 raycastOffset = new Vector3(0f, 2f, 1.5f); public LayerMask raycastLayers; public float min = -2f; public float max = 2f; public float lerpSpeed = 10f; private RaycastHit hit; private Vector3 offset; private void LateUpdate() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_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_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.rotation * raycastOffset; Vector3 groundHeightOffset = GetGroundHeightOffset(((Component)this).transform.position + val); offset = Vector3.Lerp(offset, groundHeightOffset, Time.deltaTime * lerpSpeed); Vector3 val2 = ((Component)this).transform.position + new Vector3(val.x, 0f, val.z); aimIK.solver.transform.LookAt(val2); aimIK.solver.IKPosition = val2 + offset; } private Vector3 GetGroundHeightOffset(Vector3 worldPosition) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) Debug.DrawRay(worldPosition, Vector3.down * raycastOffset.y * 2f, Color.green); if (Physics.Raycast(worldPosition, Vector3.down, ref hit, raycastOffset.y * 2f)) { return Mathf.Clamp(((RaycastHit)(ref hit)).point.y - ((Component)this).transform.position.y, min, max) * Vector3.up; } return Vector3.zero; } } public class BipedIKvsAnimatorIK : MonoBehaviour { [LargeHeader("References")] public Animator animator; public BipedIK bipedIK; [LargeHeader("Look At")] public Transform lookAtTargetBiped; public Transform lookAtTargetAnimator; [Range(0f, 1f)] public float lookAtWeight = 1f; [Range(0f, 1f)] public float lookAtBodyWeight = 1f; [Range(0f, 1f)] public float lookAtHeadWeight = 1f; [Range(0f, 1f)] public float lookAtEyesWeight = 1f; [Range(0f, 1f)] public float lookAtClampWeight = 0.5f; [Range(0f, 1f)] public float lookAtClampWeightHead = 0.5f; [Range(0f, 1f)] public float lookAtClampWeightEyes = 0.5f; [LargeHeader("Foot")] public Transform footTargetBiped; public Transform footTargetAnimator; [Range(0f, 1f)] public float footPositionWeight; [Range(0f, 1f)] public float footRotationWeight; [LargeHeader("Hand")] public Transform handTargetBiped; public Transform handTargetAnimator; [Range(0f, 1f)] public float handPositionWeight; [Range(0f, 1f)] public float handRotationWeight; private void OnAnimatorIK(int layer) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) ((Component)animator).transform.rotation = ((Component)bipedIK).transform.rotation; Vector3 val = ((Component)animator).transform.position - ((Component)bipedIK).transform.position; lookAtTargetAnimator.position = lookAtTargetBiped.position + val; bipedIK.SetLookAtPosition(lookAtTargetBiped.position); bipedIK.SetLookAtWeight(lookAtWeight, lookAtBodyWeight, lookAtHeadWeight, lookAtEyesWeight, lookAtClampWeight, lookAtClampWeightHead, lookAtClampWeightEyes); animator.SetLookAtPosition(lookAtTargetAnimator.position); animator.SetLookAtWeight(lookAtWeight, lookAtBodyWeight, lookAtHeadWeight, lookAtEyesWeight, lookAtClampWeight); footTargetAnimator.position = footTargetBiped.position + val; footTargetAnimator.rotation = footTargetBiped.rotation; bipedIK.SetIKPosition((AvatarIKGoal)0, footTargetBiped.position); bipedIK.SetIKRotation((AvatarIKGoal)0, footTargetBiped.rotation); bipedIK.SetIKPositionWeight((AvatarIKGoal)0, footPositionWeight); bipedIK.SetIKRotationWeight((AvatarIKGoal)0, footRotationWeight); animator.SetIKPosition((AvatarIKGoal)0, footTargetAnimator.position); animator.SetIKRotation((AvatarIKGoal)0, footTargetAnimator.rotation); animator.SetIKPositionWeight((AvatarIKGoal)0, footPositionWeight); animator.SetIKRotationWeight((AvatarIKGoal)0, footRotationWeight); handTargetAnimator.position = handTargetBiped.position + val; handTargetAnimator.rotation = handTargetBiped.rotation; bipedIK.SetIKPosition((AvatarIKGoal)2, handTargetBiped.position); bipedIK.SetIKRotation((AvatarIKGoal)2, handTargetBiped.rotation); bipedIK.SetIKPositionWeight((AvatarIKGoal)2, handPositionWeight); bipedIK.SetIKRotationWeight((AvatarIKGoal)2, handRotationWeight); animator.SetIKPosition((AvatarIKGoal)2, handTargetAnimator.position); animator.SetIKRotation((AvatarIKGoal)2, handTargetAnimator.rotation); animator.SetIKPositionWeight((AvatarIKGoal)2, handPositionWeight); animator.SetIKRotationWeight((AvatarIKGoal)2, handRotationWeight); } } public class MechSpider : MonoBehaviour { public LayerMask raycastLayers; public float scale = 1f; public Transform body; public MechSpiderLeg[] legs; public float legRotationWeight = 1f; public float rootPositionSpeed = 5f; public float rootRotationSpeed = 30f; public float breatheSpeed = 2f; public float breatheMagnitude = 0.2f; public float height = 3.5f; public float minHeight = 2f; public float raycastHeight = 10f; public float raycastDistance = 5f; private Vector3 lastPosition; private Vector3 defaultBodyLocalPosition; private float sine; private RaycastHit rootHit; public Vector3 velocity { get; private set; } private void Start() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) lastPosition = ((Component)this).transform.position; } private void Update() { //IL_0007: 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_0012: 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) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) velocity = (((Component)this).transform.position - lastPosition) / Time.deltaTime; lastPosition = ((Component)this).transform.position; Vector3 legsPlaneNormal = GetLegsPlaneNormal(); Quaternion val = Quaternion.FromToRotation(((Component)this).transform.up, legsPlaneNormal); ((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, val * ((Component)this).transform.rotation, Time.deltaTime * rootRotationSpeed); Vector3 val2 = Vector3.Project(GetLegCentroid() + ((Component)this).transform.up * height * scale - ((Component)this).transform.position, ((Component)this).transform.up); Transform transform = ((Component)this).transform; transform.position += val2 * Time.deltaTime * (rootPositionSpeed * scale); if (Physics.Raycast(((Component)this).transform.position + ((Component)this).transform.up * raycastHeight * scale, -((Component)this).transform.up, ref rootHit, raycastHeight * scale + raycastDistance * scale, LayerMask.op_Implicit(raycastLayers))) { ref RaycastHit reference = ref rootHit; ((RaycastHit)(ref reference)).distance = ((RaycastHit)(ref reference)).distance - (raycastHeight * scale + minHeight * scale); if (((RaycastHit)(ref rootHit)).distance < 0f) { Vector3 val3 = ((Component)this).transform.position - ((Component)this).transform.up * ((RaycastHit)(ref rootHit)).distance; ((Component)this).transform.position = Vector3.Lerp(((Component)this).transform.position, val3, Time.deltaTime * rootPositionSpeed * scale); } } sine += Time.deltaTime * breatheSpeed; if (sine >= MathF.PI * 2f) { sine -= MathF.PI * 2f; } float num = Mathf.Sin(sine) * breatheMagnitude * scale; Vector3 val4 = ((Component)this).transform.up * num; ((Component)body).transform.position = ((Component)this).transform.position + val4; } private Vector3 GetLegCentroid() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Vector3.zero; float num = 1f / (float)legs.Length; for (int i = 0; i < legs.Length; i++) { val += legs[i].position * num; } return val; } private Vector3 GetLegsPlaneNormal() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.up; if (legRotationWeight <= 0f) { return val; } float num = 1f / Mathf.Lerp((float)legs.Length, 1f, legRotationWeight); for (int i = 0; i < legs.Length; i++) { Vector3 val2 = legs[i].position - (((Component)this).transform.position - ((Component)this).transform.up * height * scale); Vector3 up = ((Component)this).transform.up; Vector3 val3 = val2; Vector3.OrthoNormalize(ref up, ref val3); Quaternion val4 = Quaternion.FromToRotation(val3, val2); val4 = Quaternion.Lerp(Quaternion.identity, val4, num); val = val4 * val; } return val; } } public class MechSpiderController : MonoBehaviour { public MechSpider mechSpider; public Transform cameraTransform; public float speed = 6f; public float turnSpeed = 30f; public Vector3 inputVector => new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")); private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) Vector3 forward = cameraTransform.forward; Vector3 up = ((Component)this).transform.up; Vector3.OrthoNormalize(ref up, ref forward); Quaternion val = Quaternion.LookRotation(forward, ((Component)this).transform.up); Transform transform = ((Component)this).transform; Vector3 val2 = inputVector; transform.Translate(val * ((Vector3)(ref val2)).normalized * Time.deltaTime * speed * mechSpider.scale, (Space)0); ((Component)this).transform.rotation = Quaternion.RotateTowards(((Component)this).transform.rotation, val, Time.deltaTime * turnSpeed); } } public class MechSpiderLeg : MonoBehaviour { public MechSpider mechSpider; public MechSpiderLeg unSync; public Vector3 offset; public float minDelay = 0.2f; public float maxOffset = 1f; public float stepSpeed = 5f; public float footHeight = 0.15f; public float velocityPrediction = 0.2f; public float raycastFocus = 0.1f; public AnimationCurve yOffset; public Transform foot; public Vector3 footUpAxis; public float footRotationSpeed = 10f; public ParticleSystem sand; private IK ik; private float stepProgress = 1f; private float lastStepTime; private Vector3 defaultPosition; private RaycastHit hit; private Quaternion lastFootLocalRotation; private Vector3 smoothHitNormal = Vector3.up; private Vector3 lastStepPosition; public bool isStepping => stepProgress < 1f; public Vector3 position { get { //IL_000b: Unknown result type (might be due to invalid IL or missing references) return ik.GetIKSolver().GetIKPosition(); } set { //IL_000b: Unknown result type (might be due to invalid IL or missing references) ik.GetIKSolver().SetIKPosition(value); } } private void Awake() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_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) ik = ((Component)this).GetComponent<IK>(); if ((Object)(object)foot != (Object)null) { if (footUpAxis == Vector3.zero) { footUpAxis = Quaternion.Inverse(foot.rotation) * Vector3.up; } lastFootLocalRotation = foot.localRotation; IKSolver iKSolver = ik.GetIKSolver(); iKSolver.OnPostUpdate = (IKSolver.UpdateDelegate)Delegate.Combine(iKSolver.OnPostUpdate, new IKSolver.UpdateDelegate(AfterIK)); } } private void AfterIK() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)foot == (Object)null)) { foot.localRotation = lastFootLocalRotation; smoothHitNormal = Vector3.Slerp(smoothHitNormal, ((RaycastHit)(ref hit)).normal, Time.deltaTime * footRotationSpeed); Quaternion val = Quaternion.FromToRotation(foot.rotation * footUpAxis, smoothHitNormal); foot.rotation = val * foot.rotation; } } private void Start() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) stepProgress = 1f; hit = default(RaycastHit); position = ik.GetIKSolver().GetPoints()[^1].transform.position; lastStepPosition = position; ((RaycastHit)(ref hit)).point = position; defaultPosition = ((Component)mechSpider).transform.InverseTransformPoint(position + offset * mechSpider.scale); ((MonoBehaviour)this).StartCoroutine(Step(position, position)); } private Vector3 GetStepTarget(out bool stepFound, float focus, float distance) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) stepFound = false; Vector3 val = ((Component)mechSpider).transform.TransformPoint(defaultPosition) + mechSpider.velocity * velocityPrediction; Vector3 up = ((Component)mechSpider).transform.up; Vector3 val2 = mechSpider.body.position - position; Vector3 val3 = Vector3.Cross(up, val2); up = Quaternion.AngleAxis(focus, val3) * up; if (Physics.Raycast(val + up * mechSpider.raycastHeight * mechSpider.scale, -up, ref hit, mechSpider.raycastHeight * mechSpider.scale + distance, LayerMask.op_Implicit(mechSpider.raycastLayers))) { stepFound = true; } return ((RaycastHit)(ref hit)).point + ((RaycastHit)(ref hit)).normal * footHeight * mechSpider.scale; } private void UpdatePosition(float distance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) Vector3 up = ((Component)mechSpider).transform.up; if (Physics.Raycast(lastStepPosition + up * mechSpider.raycastHeight * mechSpider.scale, -up, ref hit, mechSpider.raycastHeight * mechSpider.scale + distance, LayerMask.op_Implicit(mechSpider.raycastLayers))) { position = ((RaycastHit)(ref hit)).point + ((RaycastHit)(ref hit)).normal * footHeight * mechSpider.scale; } } private void Update() { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) UpdatePosition(mechSpider.raycastDistance * mechSpider.scale); if (!isStepping && !(Time.time < lastStepTime + minDelay) && (!((Object)(object)unSync != (Object)null) || !unSync.isStepping)) { bool stepFound = false; Vector3 stepTarget = GetStepTarget(out stepFound, raycastFocus, mechSpider.raycastDistance * mechSpider.scale); if (!stepFound) { stepTarget = GetStepTarget(out stepFound, 0f - raycastFocus, mechSpider.raycastDistance * 3f * mechSpider.scale); } if (stepFound && !(Vector3.Distance(position, stepTarget) < maxOffset * mechSpider.scale * Random.Range(0.9f, 1.2f))) { ((MonoBehaviour)this).StopAllCoroutines(); ((MonoBehaviour)this).StartCoroutine(Step(position, stepTarget)); } } } private IEnumerator Step(Vector3 stepStartPosition, Vector3 targetPosition) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) stepProgress = 0f; while (stepProgress < 1f) { stepProgress += Time.deltaTime * stepSpeed; position = Vector3.Lerp(stepStartPosition, targetPosition, stepProgress); position += ((Component)mechSpider).transform.up * yOffset.Evaluate(stepProgress) * mechSpider.scale; lastStepPosition = position; yield return null; } position = targetPosition; lastStepPosition = position; if ((Object)(object)sand != (Object)null) { ((Component)sand).transform.position = position - ((Component)mechSpider).transform.up * footHeight * mechSpider.scale; sand.Emit(20); } lastStepTime = Time.time; } } public class MechSpiderParticles : MonoBehaviour { public MechSpiderController mechSpiderController; private ParticleSystem particles; private void Start() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown particles = (ParticleSystem)((Component)this).GetComponent(typeof(ParticleSystem)); } private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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) Vector3 inputVector = mechSpiderController.inputVector; float magnitude = ((Vector3)(ref inputVector)).magnitude; float num = Mathf.Clamp(magnitude * 50f, 30f, 50f); EmissionModule emission = particles.emission; ((EmissionModule)(ref emission)).rateOverTime = new MinMaxCurve(num); MainModule main = particles.main; MainModule main2 = particles.main; MinMaxGradient startColor = ((MainModule)(ref main2)).startColor; float r = ((MinMaxGradient)(ref startColor)).color.r; main2 = particles.main; startColor = ((MainModule)(ref main2)).startColor; float g = ((MinMaxGradient)(ref startColor)).color.g; main2 = particles.main; startColor = ((MainModule)(ref main2)).startColor; ((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(r, g, ((MinMaxGradient)(ref startColor)).color.b, Mathf.Clamp(magnitude, 0.4f, 1f))); } } public class AnimationWarping : OffsetModifier { [Serializable] public struct Warp { [Tooltip("Layer of the 'Animation State' in the Animator.")] public int animationLayer; [Tooltip("Name of the state in the Animator to warp.")] public string animationState; [Tooltip("Warping weight by normalized time of the animation state.")] public AnimationCurve weightCurve; [Tooltip("Animated point to warp from. This should be in character space so keep this Transform parented to the root of the character.")] public Transform warpFrom; [Tooltip("World space point to warp to.")] public Transform warpTo; [Tooltip("Which FBBIK effector to use?")] public FullBodyBipedEffector effector; } [Serializable] public enum EffectorMode { PositionOffset, Position } [Tooltip("Reference to the Animator component to use")] public Animator animator; [Tooltip("Using effector.positionOffset or effector.position with effector.positionWeight? The former will enable you to use effector.position for other things, the latter will weigh in the effectors, hence using Reach and Pull in the process.")] public EffectorMode effectorMode; [Space(10f)] [Tooltip("The array of warps, can have multiple simultaneous warps.")] public Warp[] warps; private EffectorMode lastMode; protected override void Start() { base.Start(); lastMode = effectorMode; } public float GetWarpWeight(int warpIndex) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) if (warpIndex < 0) { Debug.LogError((object)"Warp index out of range."); return 0f; } if (warpIndex >= warps.Length) { Debug.LogError((object)"Warp index out of range."); return 0f; } if ((Object)(object)animator == (Object)null) { Debug.LogError((object)"Animator unassigned in AnimationWarping"); return 0f; } AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(warps[warpIndex].animationLayer); if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName(warps[warpIndex].animationState)) { return 0f; } return warps[warpIndex].weightCurve.Evaluate(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime - (float)(int)((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime); } protected override void OnModifyOffset() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < warps.Length; i++) { float warpWeight = GetWarpWeight(i); Vector3 val = warps[i].warpTo.position - warps[i].warpFrom.position; switch (effectorMode) { case EffectorMode.PositionOffset: { IKEffector effector = ik.solver.GetEffector(warps[i].effector); effector.positionOffset += val * warpWeight * weight; break; } case EffectorMode.Position: ik.solver.GetEffector(warps[i].effector).position = ik.solver.GetEffector(warps[i].effector).bone.position + val; ik.solver.GetEffector(warps[i].effector).positionWeight = weight * warpWeight; break; } } if (lastMode == EffectorMode.Position && effectorMode == EffectorMode.PositionOffset) { Warp[] array = warps; for (int j = 0; j < array.Length; j++) { Warp warp = array[j]; ik.solver.GetEffector(warp.effector).positionWeight = 0f; } } lastMode = effectorMode; } private void OnDisable() { if (effectorMode == EffectorMode.Position) { Warp[] array = warps; for (int i = 0; i < array.Length; i++) { Warp warp = array[i]; ik.solver.GetEffector(warp.effector).positionWeight = 0f; } } } } public class AnimatorController3rdPerson : MonoBehaviour { public float rotateSpeed = 7f; public float blendSpeed = 10f; public float maxAngle = 90f; public float moveSpeed = 1.5f; public float rootMotionWeight; protected Animator animator; protected Vector3 moveBlend; protected Vector3 moveInput; protected Vector3 velocity; protected virtual void Start() { animator = ((Component)this).GetComponent<Animator>(); } private void OnAnimatorMove() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_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) velocity = Vector3.Lerp(velocity, ((Component)this).transform.rotation * Vector3.ClampMagnitude(moveInput, 1f) * moveSpeed, Time.deltaTime * blendSpeed); Transform transform = ((Component)this).transform; transform.position += Vector3.Lerp(velocity * Time.deltaTime, animator.deltaPosition, rootMotionWeight); } public virtual void Move(Vector3 moveInput, bool isMoving, Vector3 faceDirection, Vector3 aimTarget) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) this.moveInput = moveInput; Vector3 val = ((Component)this).transform.InverseTransformDirection(faceDirection); float num = Mathf.Atan2(val.x, val.z) * 57.29578f; float num2 = num * Time.deltaTime * rotateSpeed; if (num > maxAngle) { num2 = Mathf.Clamp(num2, num - maxAngle, num2); } if (num < 0f - maxAngle) { num2 = Mathf.Clamp(num2, num2, num + maxAngle); } ((Component)this).transform.Rotate(Vector3.up, num2); moveBlend = Vector3.Lerp(moveBlend, moveInput, Time.deltaTime * blendSpeed); animator.SetFloat("X", moveBlend.x); animator.SetFloat("Z", moveBlend.z); animator.SetBool("IsMoving", isMoving); } } public class AnimatorController3rdPersonIK : AnimatorController3rdPerson { [Range(0f, 1f)] public float headLookWeight = 1f; public Vector3 gunHoldOffset; public Vector3 leftHandOffset; public Recoil recoil; private AimIK aim; private FullBodyBipedIK ik; private Vector3 headLookAxis; private Vector3 leftHandPosRelToRightHand; private Quaternion leftHandRotRelToRightHand; private Vector3 aimTarget; private Quaternion rightHandRotation; protected override void Start() { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) base.Start(); aim = ((Component)this).GetComponent<AimIK>(); ik = ((Component)this).GetComponent<FullBodyBipedIK>(); IKSolverFullBodyBiped solver = ik.solver; solver.OnPreRead = (IKSolver.UpdateDelegate)Delegate.Combine(solver.OnPreRead, new IKSolver.UpdateDelegate(OnPreRead)); ((Behaviour)aim).enabled = false; ((Behaviour)ik).enabled = false; headLookAxis = ik.references.head.InverseTransformVector(ik.references.root.forward); animator.SetLayerWeight(1, 1f); } public override void Move(Vector3 moveInput, bool isMoving, Vector3 faceDirection, Vector3 aimTarget) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: 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_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) base.Move(moveInput, isMoving, faceDirection, aimTarget); this.aimTarget = aimTarget; Read(); AimIK(); FBBIK(); AimIK(); HeadLookAt(aimTarget); } private void Read() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) leftHandPosRelToRightHand = ik.references.rightHand.InverseTransformPoint(ik.references.leftHand.position); leftHandRotRelToRightHand = Quaternion.Inverse(ik.references.rightHand.rotation) * ik.references.leftHand.rotation; } private void AimIK() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) aim.solver.IKPosition = aimTarget; aim.solver.Update(); } private void FBBIK() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_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_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) rightHandRotation = ik.references.rightHand.rotation; Vector3 val = ik.references.rightHand.rotation * gunHoldOffset; IKEffector rightHandEffector = ik.solver.rightHandEffector; rightHandEffector.positionOffset += val; if ((Object)(object)recoil != (Object)null) { recoil.SetHandRotations(rightHandRotation * leftHandRotRelToRightHand, rightHandRotation); } ik.solver.Update(); if ((Object)(object)recoil != (Object)null) { ik.references.rightHand.rotation = recoil.rotationOffset * rightHandRotation; ik.references.leftHand.rotation = recoil.rotationOffset * rightHandRotation * leftHandRotRelToRightHand; } else { ik.references.rightHand.rotation = rightHandRotation; ik.references.leftHand.rotation = rightHandRotation * leftHandRotRelToRightHand; } } private void OnPreRead() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) Quaternion val = (((Object)(object)recoil != (Object)null) ? (recoil.rotationOffset * rightHandRotation) : rightHandRotation); Vector3 val2 = ik.references.rightHand.position + ik.solver.rightHandEffector.positionOffset + val * leftHandPosRelToRightHand; IKEffector leftHandEffector = ik.solver.leftHandEffector; leftHandEffector.positionOffset += val2 - ik.references.leftHand.position - ik.solver.leftHandEffector.positionOffset + val * leftHandOffset; } private void HeadLookAt(Vector3 lookAtTarget) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.FromToRotation(ik.references.head.rotation * headLookAxis, lookAtTarget - ik.references.head.position); ik.references.head.rotation = Quaternion.Lerp(Quaternion.identity, val, headLookWeight) * ik.references.head.rotation; } private void OnDestroy() { if ((Object)(object)ik != (Object)null) { IKSolverFullBodyBiped solver = ik.solver; solver.OnPreRead = (IKSolver.UpdateDelegate)Delegate.Remove(solver.OnPreRead, new IKSolver.UpdateDelegate(OnPreRead)); } } } public class CharacterAnimationThirdPersonIK : CharacterAnimationThirdPerson { private FullBodyBipedIK ik; protected override void Start() { ((CharacterAnimationThirdPerson)this).Start(); ik = ((Component)this).GetComponent<FullBodyBipedIK>(); } protected override void LateUpdate() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) ((CharacterAnimationBase)this).LateUpdate(); if (!(Vector3.Angle(((Component)this).transform.up, Vector3.up) <= 0.01f)) { Quaternion rotation = Quaternion.FromToRotation(((Component)this).transform.up, Vector3.up); RotateEffector(ik.solver.bodyEffector, rotation, 0.1f); RotateEffector(ik.solver.leftShoulderEffector, rotation, 0.2f); RotateEffector(ik.solver.rightShoulderEffector, rotation, 0.2f); RotateEffector(ik.solver.leftHandEffector, rotation, 0.1f); RotateEffector(ik.solver.rightHandEffector, rotation, 0.1f); } } private void RotateEffector(IKEffector effector, Quaternion rotation, float mlp) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) Vector3 val = effector.bone.position - ((Component)this).transform.position; Vector3 val2 = rotation * val - val; effector.positionOffset += val2 * mlp; } } public class CharacterController3rdPerson : MonoBehaviour { public CameraController cam; private AnimatorController3rdPerson animatorController; private static Vector3 inputVector => new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")); private static Vector3 inputVectorRaw => new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")); private void Start() { animatorController = ((Component)this).GetComponent<AnimatorController3rdPerson>(); ((Behaviour)cam).enabled = false; } private void LateUpdate() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) cam.UpdateInput(); cam.UpdateTransform(); Vector3 moveInput = inputVector; bool isMoving = inputVector != Vector3.zero || inputVectorRaw != Vector3.zero; Vector3 forward = ((Component)cam).transform.forward; Vector3 aimTarget = ((Component)cam).transform.position + forward * 10f; animatorController.Move(moveInput, isMoving, forward, aimTarget); } } public class EffectorOffset : OffsetModifier { [Range(0f, 1f)] public float handsMaintainRelativePositionWeight; public Vector3 bodyOffset; public Vector3 leftShoulderOffset; public Vector3 rightShoulderOffset; public Vector3 leftThighOffset; public Vector3 rightThighOffset; public Vector3 leftHandOffset; public Vector3 rightHandOffset; public Vector3 leftFootOffset; public Vector3 rightFootOffset; protected override void OnModifyOffset() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: 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_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020e: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) ik.solver.leftHandEffector.maintainRelativePositionWeight = handsMaintainRelativePositionWeight; ik.solver.rightHandEffector.maintainRelativePositionWeight = handsMaintainRelativePositionWeight; IKEffector bodyEffector = ik.solver.bodyEffector; bodyEffector.positionOffset += ((Component)this).transform.rotation * bodyOffset * weight; IKEffector leftShoulderEffector = ik.solver.leftShoulderEffector; leftShoulderEffector.positionOffset += ((Component)this).transform.rotation * leftShoulderOffset * weight; IKEffector rightShoulderEffector = ik.solver.rightShoulderEffector; rightShoulderEffector.positionOffset += ((Component)this).transform.rotation * rightShoulderOffset * weight; IKEffector leftThighEffector = ik.solver.leftThighEffector; leftThighEffector.positionOffset += ((Component)this).transform.rotation * leftThighOffset * weight; IKEffector rightThighEffector = ik.solver.rightThighEffector; rightThighEffector.positionOffset += ((Component)this).transform.rotation * rightThighOffset * weight; IKEffector leftHandEffector = ik.solver.leftHandEffector; leftHandEffector.positionOffset += ((Component)this).transform.rotation * leftHandOffset * weight; IKEffector rightHandEffector = ik.solver.rightHandEffector; rightHandEffector.positionOffset += ((Component)this).transform.rotation * rightHandOffset * weight; IKEffector leftFootEffector = ik.solver.leftFootEffector; leftFootEffector.positionOffset += ((Component)this).transform.rotation * leftFootOffset * weight; IKEffector rightFootEffector = ik.solver.rightFootEffector; rightFootEffector.positionOffset += ((Component)this).transform.rotation * rightFootOffset * weight; } } public class ExplosionDemo : MonoBehaviour { public SimpleLocomotion character; public float forceMlp = 1f; public float upForce = 1f; public float weightFalloffSpeed = 1f; public AnimationCurve weightFalloff; public AnimationCurve explosionForceByDistance; public AnimationCurve scale; private float weight; private Vector3 defaultScale = Vector3.one; private Rigidbody r; private FullBodyBipedIK ik; private void Start() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) defaultScale = ((Component)this).transform.localScale; r = ((Component)character).GetComponent<Rigidbody>(); ik = ((Component)character).GetComponent<FullBodyBipedIK>(); } private void Update() { //IL_0203: 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_007e: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0163: 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_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017e: 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) weight = Mathf.Clamp(weight - Time.deltaTime * weightFalloffSpeed, 0f, 1f); if (Input.GetKeyDown((KeyCode)101) && character.isGrounded) { ik.solver.IKPositionWeight = 1f; ik.solver.leftHandEffector.position = ik.solver.leftHandEffector.bone.position; ik.solver.rightHandEffector.position = ik.solver.rightHandEffector.bone.position; ik.solver.leftFootEffector.position = ik.solver.leftFootEffector.bone.position; ik.solver.rightFootEffector.position = ik.solver.rightFootEffector.bone.position; weight = 1f; Vector3 val = r.position - ((Component)this).transform.position; val.y = 0f; float num = explosionForceByDistance.Evaluate(((Vector3)(ref val)).magnitude); r.velocity = (((Vector3)(ref val)).normalized + Vector3.up * upForce) * num * forceMlp; } if (weight < 0.5f && character.isGrounded) { weight = Mathf.Clamp(weight - Time.deltaTime * 3f, 0f, 1f); } SetEffectorWeights(weightFalloff.Evaluate(weight)); ((Component)this).transform.localScale = scale.Evaluate(weight) * defaultScale; } private void SetEffectorWeights(float w) { ik.solver.leftHandEffector.positionWeight = w; ik.solver.rightHandEffector.positionWeight = w; ik.solver.leftFootEffector.positionWeight = w; ik.solver.rightFootEffector.positionWeight = w; } } public class FBBIKSettings : MonoBehaviour { [Serializable] public class Limb { public FBIKChain.Smoothing reachSmoothing; public float maintainRelativePositionWeight; public float mappingWeight = 1f; public void Apply(FullBodyBipedChain chain, IKSolverFullBodyBiped solver) { solver.GetChain(chain).reachSmoothing = reachSmoothing; solver.GetEndEffector(chain).maintainRelativePositionWeight = maintainRelativePositionWeight; solver.GetLimbMapping(chain).weight = mappingWeight; } } public FullBodyBipedIK ik; public bool disableAfterStart; public Limb leftArm; public Limb rightArm; public Limb leftLeg; public Limb rightLeg; public float rootPin; public bool bodyEffectChildNodes = true; public void UpdateSettings() { if (!((Object)(object)ik == (Object)null)) { leftArm.Apply(FullBodyBipedChain.LeftArm, ik.solver); rightArm.Apply(FullBodyBipedChain.RightArm, ik.solver); leftLeg.Apply(FullBodyBipedChain.LeftLeg, ik.solver); rightLeg.Apply(FullBodyBipedChain.RightLeg, ik.solver); ik.solver.chain[0].pin = rootPin; ik.solver.bodyEffector.effectChildNodes = bodyEffectChildNodes; } } private void Start() { Debug.Log((object)"FBBIKSettings is deprecated, you can now edit all the settings from the custom inspector of the FullBodyBipedIK component."); UpdateSettings(); if (disableAfterStart) { ((Behaviour)this).enabled = false; } } private void Update() { UpdateSettings(); } } public class FBIKBendGoal : MonoBehaviour { public FullBodyBipedIK ik; public FullBodyBipedChain chain; public float weight; private void Start() { Debug.Log((object)"FBIKBendGoal is deprecated, you can now a bend goal from the custom inspector of the FullBodyBipedIK component."); } private void Update() { if (!((Object)(object)ik == (Object)null)) { ik.solver.GetBendConstraint(chain).bendGoal = ((Component)this).transform; ik.solver.GetBendConstraint(chain).weight = weight; } } } public class FBIKBoxing : MonoBehaviour { [Tooltip("The target we want to hit")] public Transform target; [Tooltip("The pin Transform is used to reference the exact hit point in the animation (used by AimIK to aim the upper body to follow the target).In Legacy and Generic modes you can just create and position a reference point in your animating software and include it in the FBX. Then in Unity if you added a GameObject with the exact same name under the character's root, it would be animated to the required position.In Humanoid mode however, Mecanim loses track of any Transform that does not belong to the avatar, so in this case the pin point has to be manually set inside the Unity Editor.")] public Transform pin; [Tooltip("The Full Body Biped IK component")] public FullBodyBipedIK ik; [Tooltip("The Aim IK component. Aim IK is ust used for following the target slightly with the body.")] public AimIK aim; [Tooltip("The master weight")] public float weight; [Tooltip("The effector type of the punching hand")] public FullBodyBipedEffector effector; [Tooltip("Weight of aiming the body to follow the target")] public AnimationCurve aimWeight; private Animator animator; private void Start() { animator = ((Component)this).GetComponent<Animator>(); } private void LateUpdate() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) float @float = animator.GetFloat("HitWeight"); ik.solver.GetEffector(effector).position = target.position; ik.solver.GetEffector(effector).positionWeight = @float * weight; if ((Object)(object)aim != (Object)null) { aim.solver.transform.LookAt(pin.position); aim.solver.IKPosition = target.position; aim.solver.IKPositionWeight = aimWeight.Evaluate(@float) * weight; } } } public class FBIKHandsOnProp : MonoBehaviour { public FullBodyBipedIK ik; public bool leftHanded; private void Awake() { IKSolverFullBodyBiped solver = ik.solver; solver.OnPreRead = (IKSolver.UpdateDelegate)Delegate.Combine(solver.OnPreRead, new IKSolver.UpdateDelegate(OnPreRead)); } private void OnPreRead() { if (leftHanded) { HandsOnProp(ik.solver.leftHandEffector, ik.solver.rightHandEffector); } else { HandsOnProp(ik.solver.rightHandEffector, ik.solver.leftHandEffector); } } private void HandsOnProp(IKEffector mainHand, IKEffector otherHand) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) Vector3 val = otherHand.bone.position - mainHand.bone.position; Vector3 val2 = Quaternion.Inverse(mainHand.bone.rotation) * val; Vector3 val3 = mainHand.bone.position + val * 0.5f; Quaternion val4 = Quaternion.Inverse(mainHand.bone.rotation) * otherHand.bone.rotation; Vector3 val5 = otherHand.bone.position + otherHand.positionOffset - (mainHand.bone.position + mainHand.positionOffset); Vector3 val6 = mainHand.bone.position + mainHand.positionOffset + val * 0.5f; mainHand.position = mainHand.bone.position + mainHand.positionOffset + (val6 - val3); mainHand.positionWeight = 1f; Quaternion val7 = Quaternion.FromToRotation(val, val5); mainHand.bone.rotation = val7 * mainHand.bone.rotation; otherHand.position = mainHand.position + mainHand.bone.rotation * val2; otherHand.positionWeight = 1f; otherHand.bone.rotation = mainHand.bone.rotation * val4; ik.solver.leftArmMapping.maintainRotationWeight = 1f; ik.solver.rightArmMapping.maintainRotationWeight = 1f; } private void OnDestroy() { if ((Object)(object)ik != (Object)null) { IKSolverFullBodyBiped solver = ik.solver; solver.OnPreRead = (IKSolver.UpdateDelegate)Delegate.Remove(solver.OnPreRead, new IKSolver.UpdateDelegate(OnPreRead)); } } } public class FPSAiming : MonoBehaviour { [Range(0f, 1f)] public float aimWeight = 1f; [Range(0f, 1f)] public float sightWeight = 1f; [Range(0f, 180f)] public float maxAngle = 80f; public Vector3 aimOffset; public bool animatePhysics; public Transform gun; public Transform gunTarget; public FullBodyBipedIK ik; public AimIK gunAim; public AimIK headAim; public CameraControllerFPS cam; public Recoil recoil; [Range(0f, 1f)] public float cameraRecoilWeight = 0.5f; private Vector3 gunTargetDefaultLocalPosition; private Vector3 gunTargetDefaultLocalRotation; private Vector3 camDefaultLocalPosition; private Vector3 camRelativeToGunTarget; private bool updateFrame; private void Start() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) gunTargetDefaultLocalPosition = gunTarget.localPosition; gunTargetDefaultLocalRotation = gunTarget.localEulerAngles; camDefaultLocalPosition = ((Component)cam).transform.localPosition; ((Behaviour)cam).enabled = false; ((Behaviour)gunAim).enabled = false; if ((Object)(object)headAim != (Object)null) { ((Behaviour)headAim).enabled = false; } ((Behaviour)ik).enabled = false; if ((Object)(object)recoil != (Object)null && ik.solver.iterations == 0) { Debug.LogWarning((object)"FPSAiming with Recoil needs FBBIK solver iteration count to be at least 1 to maintain accuracy."); } } private void FixedUpdate() { updateFrame = true; } private void LateUpdate() { //IL_002b: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) if (!animatePhysics) { updateFrame = true; } if (updateFrame) { updateFrame = false; ((Component)cam).transform.localPosition = camDefaultLocalPosition; camRelativeToGunTarget = gunTarget.InverseTransformPoint(((Component)cam).transform.position); cam.LateUpdate(); RotateCharacter(); Aiming(); LookDownTheSight(); } } private void Aiming() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)headAim == (Object)null) || !(aimWeight <= 0f)) { Quaternion rotation = ((Component)cam).transform.rotation; headAim.solver.IKPosition = ((Component)cam).transform.position + ((Component)cam).transform.forward * 10f; headAim.solver.IKPositionWeight = 1f - aimWeight; headAim.solver.Update(); gunAim.solver.IKPosition = ((Component)cam).transform.position + ((Component)cam).transform.forward * 10f + ((Component)cam).transform.rotation * aimOffset; gunAim.solver.IKPositionWeight = aimWeight; gunAim.solver.Update(); ((Component)cam).transform.rotation = rotation; } } private void LookDownTheSight() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed:
plugins/Valheim_Data/Managed/NDesk.Options.dll
Decompiled 5 months agousing System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; [assembly: AssemblyTitle("NDesk.Options")] [assembly: AssemblyDescription("C# Option Parser.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AssemblyVersion("0.2.1.0")] namespace NDesk.Options; public class OptionValueCollection : IList, ICollection, IEnumerable, IList<string>, ICollection<string>, IEnumerable<string> { private List<string> values = new List<string>(); private OptionContext c; bool ICollection.IsSynchronized => ((ICollection)values).IsSynchronized; object ICollection.SyncRoot => ((ICollection)values).SyncRoot; bool IList.IsFixedSize => false; object IList.this[int index] { get { return this[index]; } set { ((IList)values)[index] = value; } } public int Count => values.Count; public bool IsReadOnly => false; public string this[int index] { get { AssertValid(index); return (index < values.Count) ? values[index] : null; } set { values[index] = value; } } internal OptionValueCollection(OptionContext c) { this.c = c; } void ICollection.CopyTo(Array array, int index) { ((ICollection)values).CopyTo(array, index); } IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } int IList.Add(object value) { return ((IList)values).Add(value); } bool IList.Contains(object value) { return ((IList)values).Contains(value); } int IList.IndexOf(object value) { return ((IList)values).IndexOf(value); } void IList.Insert(int index, object value) { ((IList)values).Insert(index, value); } void IList.Remove(object value) { ((IList)values).Remove(value); } void IList.RemoveAt(int index) { ((IList)values).RemoveAt(index); } public void Add(string item) { values.Add(item); } public void Clear() { values.Clear(); } public bool Contains(string item) { return values.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } public bool Remove(string item) { return values.Remove(item); } public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); } public int IndexOf(string item) { return values.IndexOf(item); } public void Insert(int index, string item) { values.Insert(index, item); } public void RemoveAt(int index) { values.RemoveAt(index); } private void AssertValid(int index) { if (c.Option == null) { throw new InvalidOperationException("OptionContext.Option is null."); } if (index >= c.Option.MaxValueCount) { throw new ArgumentOutOfRangeException("index"); } if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) { throw new OptionException(string.Format(c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } } public List<string> ToList() { return new List<string>(values); } public string[] ToArray() { return values.ToArray(); } public override string ToString() { return string.Join(", ", values.ToArray()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public Option Option { get { return option; } set { option = value; } } public string OptionName { get { return name; } set { name = value; } } public int OptionIndex { get { return index; } set { index = value; } } public OptionSet OptionSet => set; public OptionValueCollection OptionValues => c; public OptionContext(OptionSet set) { this.set = set; c = new OptionValueCollection(this); } } public enum OptionValueType { None, Optional, Required } public abstract class Option { private string prototype; private string description; private string[] names; private OptionValueType type; private int count; private string[] separators; private static readonly char[] NameTerminator = new char[2] { '=', ':' }; public string Prototype => prototype; public string Description => description; public OptionValueType OptionValueType => type; public int MaxValueCount => count; internal string[] Names => names; internal string[] ValueSeparators => separators; protected Option(string prototype, string description) : this(prototype, description, 1) { } protected Option(string prototype, string description, int maxValueCount) { if (prototype == null) { throw new ArgumentNullException("prototype"); } if (prototype.Length == 0) { throw new ArgumentException("Cannot be the empty string.", "prototype"); } if (maxValueCount < 0) { throw new ArgumentOutOfRangeException("maxValueCount"); } this.prototype = prototype; names = prototype.Split(new char[1] { '|' }); this.description = description; count = maxValueCount; type = ParsePrototype(); if (count == 0 && type != 0) { throw new ArgumentException("Cannot provide maxValueCount of 0 for OptionValueType.Required or OptionValueType.Optional.", "maxValueCount"); } if (type == OptionValueType.None && maxValueCount > 1) { throw new ArgumentException($"Cannot provide maxValueCount of {maxValueCount} for OptionValueType.None.", "maxValueCount"); } if (Array.IndexOf(names, "<>") >= 0 && ((names.Length == 1 && type != 0) || (names.Length > 1 && MaxValueCount > 1))) { throw new ArgumentException("The default option handler '<>' cannot require values.", "prototype"); } } protected static T Parse<T>(string value, OptionContext c) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); T result = default(T); try { if (value != null) { result = (T)converter.ConvertFromString(value); } } catch (Exception innerException) { throw new OptionException(string.Format(c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof(T).Name, c.OptionName), c.OptionName, innerException); } return result; } public string[] GetNames() { return (string[])names.Clone(); } public string[] GetValueSeparators() { if (separators == null) { return new string[0]; } return (string[])separators.Clone(); } private OptionValueType ParsePrototype() { char c = '\0'; List<string> list = new List<string>(); for (int i = 0; i < names.Length; i++) { string text = names[i]; if (text.Length == 0) { throw new ArgumentException("Empty option names are not supported.", "prototype"); } int num = text.IndexOfAny(NameTerminator); if (num != -1) { names[i] = text.Substring(0, num); if (c != 0 && c != text[num]) { throw new ArgumentException($"Conflicting option types: '{c}' vs. '{text[num]}'.", "prototype"); } c = text[num]; AddSeparators(text, num, list); } } if (c == '\0') { return OptionValueType.None; } if (count <= 1 && list.Count != 0) { throw new ArgumentException($"Cannot provide key/value separators for Options taking {count} value(s).", "prototype"); } if (count > 1) { if (list.Count == 0) { separators = new string[2] { ":", "=" }; } else if (list.Count == 1 && list[0].Length == 0) { separators = null; } else { separators = list.ToArray(); } } return (c != '=') ? OptionValueType.Optional : OptionValueType.Required; } private static void AddSeparators(string name, int end, ICollection<string> seps) { int num = -1; for (int i = end + 1; i < name.Length; i++) { switch (name[i]) { case '{': if (num != -1) { throw new ArgumentException($"Ill-formed name/value separator found in \"{name}\".", "prototype"); } num = i + 1; break; case '}': if (num == -1) { throw new ArgumentException($"Ill-formed name/value separator found in \"{name}\".", "prototype"); } seps.Add(name.Substring(num, i - num)); num = -1; break; default: if (num == -1) { seps.Add(name[i].ToString()); } break; } } if (num != -1) { throw new ArgumentException($"Ill-formed name/value separator found in \"{name}\".", "prototype"); } } public void Invoke(OptionContext c) { OnParseComplete(c); c.OptionName = null; c.Option = null; c.OptionValues.Clear(); } protected abstract void OnParseComplete(OptionContext c); public override string ToString() { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public string OptionName => option; public OptionException() { } public OptionException(string message, string optionName) : base(message) { option = optionName; } public OptionException(string message, string optionName, Exception innerException) : base(message, innerException) { option = optionName; } protected OptionException(SerializationInfo info, StreamingContext context) : base(info, context) { option = info.GetString("OptionName"); } [PermissionSet(SecurityAction.LinkDemand, XML = "<PermissionSet class=\"System.Security.PermissionSet\"\nversion=\"1\">\n<IPermission class=\"System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"\nversion=\"1\"\nFlags=\"SerializationFormatter\"/>\n</PermissionSet>\n")] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OptionName", option); } } public class OptionSet : KeyedCollection<string, Option> { private sealed class ActionOption : Option { private Action<OptionValueCollection> action; public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action) : base(prototype, description, count) { if (action == null) { throw new ArgumentNullException("action"); } this.action = action; } protected override void OnParseComplete(OptionContext c) { action(c.OptionValues); } } private sealed class ActionOption<T> : Option { private Action<T> action; public ActionOption(string prototype, string description, Action<T> action) : base(prototype, description, 1) { if (action == null) { throw new ArgumentNullException("action"); } this.action = action; } protected override void OnParseComplete(OptionContext c) { action(Option.Parse<T>(c.OptionValues[0], c)); } } private sealed class ActionOption<TKey, TValue> : Option { private OptionAction<TKey, TValue> action; public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action) : base(prototype, description, 2) { if (action == null) { throw new ArgumentNullException("action"); } this.action = action; } protected override void OnParseComplete(OptionContext c) { action(Option.Parse<TKey>(c.OptionValues[0], c), Option.Parse<TValue>(c.OptionValues[1], c)); } } [CompilerGenerated] private class <>c__CompilerGenerated0 { internal Action<string> <1:action>; internal OptionSet <1:<>THIS>; public <>c__CompilerGenerated0(OptionSet parent) { <1:<>THIS> = parent; } } [CompilerGenerated] private class <>c__CompilerGenerated1 { internal OptionAction<string, string> <2:action>; internal OptionSet <2:<>THIS>; public <>c__CompilerGenerated1(OptionSet parent) { <2:<>THIS> = parent; } } [CompilerGenerated] private class <>c__CompilerGenerated2 { } private const int OptionWidth = 29; private Converter<string, string> localizer; private readonly Regex ValueOption; public Converter<string, string> MessageLocalizer => localizer; public OptionSet() { _ = 1; this..ctor(new <>c__CompilerGenerated2().<OptionSet>c__3<string, string>); } public OptionSet(Converter<string, string> localizer) { ValueOption = new Regex("^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); base..ctor(); this.localizer = localizer; } public OptionSet Add<T>(string prototype, Action<T> action) { return Add(prototype, null, action); } public OptionSet Add<T>(string prototype, string description, Action<T> action) { return Add(new ActionOption<T>(prototype, description, action)); } public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action) { return Add(prototype, null, action); } public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action) { return Add(new ActionOption<TKey, TValue>(prototype, description, action)); } protected override string GetKeyForItem(Option item) { if (item == null) { throw new ArgumentNullException("option"); } if (item.Names != null && item.Names.Length > 0) { return item.Names[0]; } throw new InvalidOperationException("Option has no names!"); } [Obsolete("Use KeyedCollection.this[string]")] protected Option GetOptionForName(string option) { if (option == null) { throw new ArgumentNullException("option"); } try { return base[option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem(int index, Option item) { base.InsertItem(index, item); AddImpl(item); } protected override void RemoveItem(int index) { base.RemoveItem(index); Option option = base.Items[index]; for (int i = 1; i < option.Names.Length; i++) { base.Dictionary.Remove(option.Names[i]); } } protected override void SetItem(int index, Option item) { base.SetItem(index, item); RemoveItem(index); AddImpl(item); } private void AddImpl(Option option) { if (option == null) { throw new ArgumentNullException("option"); } List<string> list = new List<string>(option.Names.Length); try { for (int i = 1; i < option.Names.Length; i++) { base.Dictionary.Add(option.Names[i], option); list.Add(option.Names[i]); } } catch (Exception) { List<string>.Enumerator enumerator = list.GetEnumerator(); try { while (enumerator.MoveNext()) { string current = enumerator.Current; base.Dictionary.Remove(current); } } finally { enumerator.Dispose(); } throw; } } public new OptionSet Add(Option option) { base.Add(option); return this; } public OptionSet Add(string prototype, Action<string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, Action<string> action) { _ = 2; <>c__CompilerGenerated0 <>c__CompilerGenerated = new <>c__CompilerGenerated0(this); <>c__CompilerGenerated.<1:action> = action; if (<>c__CompilerGenerated.<1:action> == null) { throw new ArgumentNullException("action"); } Option item = new ActionOption(prototype, description, 1, <>c__CompilerGenerated.<Add>c__4<OptionValueCollection>); ((Collection<Option>)<>c__CompilerGenerated.<1:<>THIS>).Add(item); return <>c__CompilerGenerated.<1:<>THIS>; } public OptionSet Add(string prototype, OptionAction<string, string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, OptionAction<string, string> action) { _ = 3; <>c__CompilerGenerated1 <>c__CompilerGenerated = new <>c__CompilerGenerated1(this); <>c__CompilerGenerated.<2:action> = action; if (<>c__CompilerGenerated.<2:action> == null) { throw new ArgumentNullException("action"); } Option item = new ActionOption(prototype, description, 2, <>c__CompilerGenerated.<Add>c__5<OptionValueCollection>); ((Collection<Option>)<>c__CompilerGenerated.<2:<>THIS>).Add(item); return <>c__CompilerGenerated.<2:<>THIS>; } protected virtual OptionContext CreateOptionContext() { return new OptionContext(this); } public List<string> Parse(IEnumerable<string> arguments) { OptionContext optionContext = CreateOptionContext(); optionContext.OptionIndex = -1; bool flag = true; List<string> list = new List<string>(); Option def = ((!Contains("<>")) ? null : base["<>"]); foreach (string argument in arguments) { optionContext.OptionIndex++; if (argument == "--") { flag = false; } else if (!flag) { Unprocessed(list, def, optionContext, argument); } else if (!Parse(argument, optionContext)) { Unprocessed(list, def, optionContext, argument); } } if (optionContext.Option != null) { optionContext.Option.Invoke(optionContext); } return list; } private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add(argument); return false; } c.OptionValues.Add(argument); c.Option = def; c.Option.Invoke(c); return false; } protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) { throw new ArgumentNullException("argument"); } flag = (name = (sep = (value = null))); Match match = ValueOption.Match(argument); if (!match.Success) { return false; } flag = match.Groups["flag"].Value; name = match.Groups["name"].Value; if (match.Groups["sep"].Success && match.Groups["value"].Success) { sep = match.Groups["sep"].Value; value = match.Groups["value"].Value; } return true; } protected virtual bool Parse(string argument, OptionContext c) { if (c.Option != null) { ParseValue(argument, c); return true; } if (!GetOptionParts(argument, out var flag, out var name, out var sep, out var value)) { return false; } if (Contains(name)) { Option option = base[name]; c.OptionName = flag + name; c.Option = option; switch (option.OptionValueType) { case OptionValueType.None: c.OptionValues.Add(name); c.Option.Invoke(c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue(value, c); break; } return true; } if (ParseBool(argument, name, c)) { return true; } if (ParseBundledValue(flag, string.Concat(name + sep + value), c)) { return true; } return false; } private void ParseValue(string option, OptionContext c) { if (option != null) { string[] array = ((c.Option.ValueSeparators != null) ? option.Split(c.Option.ValueSeparators, StringSplitOptions.None) : new string[1] { option }); int num = array.Length; for (int i = 0; i < num; i++) { string item = array[i]; c.OptionValues.Add(item); } } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) { c.Option.Invoke(c); } else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException(localizer($"Error: Found {c.OptionValues.Count} option values when expecting {c.Option.MaxValueCount}."), c.OptionName); } } private bool ParseBool(string option, string n, OptionContext c) { string key; if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && Contains(key = n.Substring(0, n.Length - 1))) { Option option2 = base[key]; string item = ((n[n.Length - 1] != '+') ? null : option); c.OptionName = option; c.Option = option2; c.OptionValues.Add(item); option2.Invoke(c); return true; } return false; } private bool ParseBundledValue(string f, string n, OptionContext c) { if (f != "-") { return false; } for (int i = 0; i < n.Length; i++) { string text = f + n[i]; string key = n[i].ToString(); if (!Contains(key)) { if (i == 0) { return false; } throw new OptionException(string.Format(localizer("Cannot bundle unregistered option '{0}'."), text), text); } Option option = base[key]; switch (option.OptionValueType) { case OptionValueType.None: break; case OptionValueType.Optional: case OptionValueType.Required: { string text2 = n.Substring(i + 1); c.Option = option; c.OptionName = text; ParseValue((text2.Length == 0) ? null : text2, c); return true; } default: throw new InvalidOperationException("Unknown OptionValueType: " + option.OptionValueType); } Invoke(c, text, n, option); } return true; } private static void Invoke(OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add(value); option.Invoke(c); } public void WriteOptionDescriptions(TextWriter o) { using IEnumerator<Option> enumerator = GetEnumerator(); while (enumerator.MoveNext()) { Option current = enumerator.Current; int written = 0; if (WriteOptionPrototype(o, current, ref written)) { if (written < 29) { o.Write(new string(' ', 29 - written)); } else { o.WriteLine(); o.Write(new string(' ', 29)); } List<string> lines = GetLines(localizer(GetDescription(current.Description))); o.WriteLine(lines[0]); string value = new string(' ', 31); for (int i = 1; i < lines.Count; i++) { o.Write(value); o.WriteLine(lines[i]); } } } } private bool WriteOptionPrototype(TextWriter o, Option p, ref int written) { string[] names = p.Names; int nextOptionIndex = GetNextOptionIndex(names, 0); if (nextOptionIndex == names.Length) { return false; } if (names[nextOptionIndex].Length == 1) { Write(o, ref written, " -"); Write(o, ref written, names[0]); } else { Write(o, ref written, " --"); Write(o, ref written, names[0]); } for (nextOptionIndex = GetNextOptionIndex(names, nextOptionIndex + 1); nextOptionIndex < names.Length; nextOptionIndex = GetNextOptionIndex(names, nextOptionIndex + 1)) { Write(o, ref written, ", "); Write(o, ref written, (names[nextOptionIndex].Length != 1) ? "--" : "-"); Write(o, ref written, names[nextOptionIndex]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("[")); } Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); string text = ((p.ValueSeparators == null || p.ValueSeparators.Length <= 0) ? " " : p.ValueSeparators[0]); for (int i = 1; i < p.MaxValueCount; i++) { Write(o, ref written, localizer(text + GetArgumentName(i, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("]")); } } return true; } private static int GetNextOptionIndex(string[] names, int i) { while (i < names.Length && names[i] == "<>") { i++; } return i; } private static void Write(TextWriter o, ref int n, string s) { n += s.Length; o.Write(s); } private static string GetArgumentName(int index, int maxIndex, string description) { if (description == null) { return (maxIndex != 1) ? ("VALUE" + (index + 1)) : "VALUE"; } string[] array = ((maxIndex != 1) ? new string[1] { "{" + index + ":" } : new string[2] { "{0:", "{" }); for (int i = 0; i < array.Length; i++) { int num = 0; int num2; do { num2 = description.IndexOf(array[i], num); } while (num2 >= 0 && num != 0 && description[num++ - 1] == '{'); if (num2 != -1) { int num3 = description.IndexOf("}", num2); if (num3 != -1) { return description.Substring(num2 + array[i].Length, num3 - num2 - array[i].Length); } } } return (maxIndex != 1) ? ("VALUE" + (index + 1)) : "VALUE"; } private static string GetDescription(string description) { if (description == null) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(description.Length); int num = -1; for (int i = 0; i < description.Length; i++) { switch (description[i]) { case '{': if (i == num) { stringBuilder.Append('{'); num = -1; } else if (num < 0) { num = i + 1; } continue; case '}': if (num < 0) { if (i + 1 == description.Length || description[i + 1] != '}') { throw new InvalidOperationException("Invalid option description: " + description); } i++; stringBuilder.Append("}"); } else { stringBuilder.Append(description.Substring(num, i - num)); num = -1; } continue; case ':': if (num < 0) { break; } num = i + 1; continue; } if (num < 0) { stringBuilder.Append(description[i]); } } return stringBuilder.ToString(); } private static List<string> GetLines(string description) { List<string> list = new List<string>(); if (string.IsNullOrEmpty(description)) { list.Add(string.Empty); return list; } int length = 49; int num = 0; int num2; do { num2 = GetLineEnd(num, length, description); bool flag = false; if (num2 < description.Length) { char c = description[num2]; if (c == '-' || (char.IsWhiteSpace(c) && c != '\n')) { num2++; } else if (c != '\n') { flag = true; num2--; } } list.Add(description.Substring(num, num2 - num)); if (flag) { List<string> list2; List<string> list3 = (list2 = list); int index; int index2 = (index = list.Count - 1); string text = list2[index]; list3[index2] = text + "-"; } num = num2; if (num < description.Length && description[num] == '\n') { num++; } } while (num2 < description.Length); return list; } private static int GetLineEnd(int start, int length, string description) { int num = Math.Min(start + length, description.Length); int num2 = -1; for (int i = start; i < num; i++) { switch (description[i]) { case '\t': case '\v': case ' ': case ',': case '-': case '.': case ';': num2 = i; break; case '\n': return i; } } if (num2 == -1 || num == description.Length) { return num; } return num2; } } public delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
plugins/Valheim_Data/Managed/root_motion_demo_assets.dll
Decompiled 5 months agousing System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] namespace RootMotion { public class CameraController : MonoBehaviour { [Serializable] public enum UpdateMode { Update, FixedUpdate, LateUpdate, FixedLateUpdate } public Transform target; public Transform rotationSpace; public UpdateMode updateMode = UpdateMode.LateUpdate; public bool lockCursor = true; [Header("Position")] public bool smoothFollow; public Vector3 offset = new Vector3(0f, 1.5f, 0.5f); public float followSpeed = 10f; [Header("Rotation")] public float rotationSensitivity = 3.5f; public float yMinLimit = -20f; public float yMaxLimit = 80f; public bool rotateAlways = true; public bool rotateOnLeftButton; public bool rotateOnRightButton; public bool rotateOnMiddleButton; [Header("Distance")] public float distance = 10f; public float minDistance = 4f; public float maxDistance = 10f; public float zoomSpeed = 10f; public float zoomSensitivity = 1f; [Header("Blocking")] public LayerMask blockingLayers; public float blockingRadius = 1f; public float blockingSmoothTime = 0.1f; public float blockingOriginOffset; [Range(0f, 1f)] public float blockedOffset = 0.5f; private Vector3 targetDistance; private Vector3 position; private Quaternion rotation = Quaternion.identity; private Vector3 smoothPosition; private Camera cam; private bool fixedFrame; private float fixedDeltaTime; private Quaternion r = Quaternion.identity; private Vector3 lastUp; private float blockedDistance = 10f; private float blockedDistanceV; public float x { get; private set; } public float y { get; private set; } public float distanceTarget { get; private set; } private float zoomAdd { get { float axis = Input.GetAxis("Mouse ScrollWheel"); if (axis > 0f) { return 0f - zoomSensitivity; } if (axis < 0f) { return zoomSensitivity; } return 0f; } } public void SetAngles(Quaternion rotation) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) Vector3 eulerAngles = ((Quaternion)(ref rotation)).eulerAngles; x = eulerAngles.y; y = eulerAngles.x; } public void SetAngles(float yaw, float pitch) { x = yaw; y = pitch; } protected virtual void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) Vector3 eulerAngles = ((Component)this).transform.eulerAngles; x = eulerAngles.y; y = eulerAngles.x; distanceTarget = distance; smoothPosition = ((Component)this).transform.position; cam = ((Component)this).GetComponent<Camera>(); lastUp = (((Object)(object)rotationSpace != (Object)null) ? rotationSpace.up : Vector3.up); } protected virtual void Update() { if (updateMode == UpdateMode.Update) { UpdateTransform(); } } protected virtual void FixedUpdate() { fixedFrame = true; fixedDeltaTime += Time.deltaTime; if (updateMode == UpdateMode.FixedUpdate) { UpdateTransform(); } } protected virtual void LateUpdate() { UpdateInput(); if (updateMode == UpdateMode.LateUpdate) { UpdateTransform(); } if (updateMode == UpdateMode.FixedLateUpdate && fixedFrame) { UpdateTransform(fixedDeltaTime); fixedDeltaTime = 0f; fixedFrame = false; } } public void UpdateInput() { if (((Behaviour)cam).enabled) { Cursor.lockState = (CursorLockMode)(lockCursor ? 1 : 0); Cursor.visible = ((!lockCursor) ? true : false); if (rotateAlways || (rotateOnLeftButton && Input.GetMouseButton(0)) || (rotateOnRightButton && Input.GetMouseButton(1)) || (rotateOnMiddleButton && Input.GetMouseButton(2))) { x += Input.GetAxis("Mouse X") * rotationSensitivity; y = ClampAngle(y - Input.GetAxis("Mouse Y") * rotationSensitivity, yMinLimit, yMaxLimit); } distanceTarget = Mathf.Clamp(distanceTarget + zoomAdd, minDistance, maxDistance); } } public void UpdateTransform() { UpdateTransform(Time.deltaTime); } public void UpdateTransform(float deltaTime) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0211: 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_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) if (!((Behaviour)cam).enabled) { return; } rotation = Quaternion.AngleAxis(x, Vector3.up) * Quaternion.AngleAxis(y, Vector3.right); if ((Object)(object)rotationSpace != (Object)null) { r = Quaternion.FromToRotation(lastUp, rotationSpace.up) * r; rotation = r * rotation; lastUp = rotationSpace.up; } if ((Object)(object)target != (Object)null) { distance += (distanceTarget - distance) * zoomSpeed * deltaTime; if (!smoothFollow) { smoothPosition = target.position; } else { smoothPosition = Vector3.Lerp(smoothPosition, target.position, deltaTime * followSpeed); } Vector3 val = smoothPosition + rotation * offset; Vector3 val2 = rotation * -Vector3.forward; if (LayerMask.op_Implicit(blockingLayers) != -1) { RaycastHit val3 = default(RaycastHit); if (Physics.SphereCast(val - val2 * blockingOriginOffset, blockingRadius, val2, ref val3, blockingOriginOffset + distanceTarget - blockingRadius, LayerMask.op_Implicit(blockingLayers))) { blockedDistance = Mathf.SmoothDamp(blockedDistance, ((RaycastHit)(ref val3)).distance + blockingRadius * (1f - blockedOffset) - blockingOriginOffset, ref blockedDistanceV, blockingSmoothTime); } else { blockedDistance = distanceTarget; } distance = Mathf.Min(distance, blockedDistance); } position = val + val2 * distance; ((Component)this).transform.position = position; } ((Component)this).transform.rotation = rotation; } private float ClampAngle(float angle, float min, float max) { if (angle < -360f) { angle += 360f; } if (angle > 360f) { angle -= 360f; } return Mathf.Clamp(angle, min, max); } } public class CameraControllerFPS : MonoBehaviour { public float rotationSensitivity = 3f; public float yMinLimit = -89f; public float yMaxLimit = 89f; private float x; private float y; private void Awake() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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) Vector3 eulerAngles = ((Component)this).transform.eulerAngles; x = eulerAngles.y; y = eulerAngles.x; } public void LateUpdate() { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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) Cursor.lockState = (CursorLockMode)1; x += Input.GetAxis("Mouse X") * rotationSensitivity; y = ClampAngle(y - Input.GetAxis("Mouse Y") * rotationSensitivity, yMinLimit, yMaxLimit); ((Component)this).transform.rotation = Quaternion.AngleAxis(x, Vector3.up) * Quaternion.AngleAxis(y, Vector3.right); } private float ClampAngle(float angle, float min, float max) { if (angle < -360f) { angle += 360f; } if (angle > 360f) { angle -= 360f; } return Mathf.Clamp(angle, min, max); } } } namespace RootMotion.Demos { public abstract class CharacterAnimationBase : MonoBehaviour { public bool smoothFollow = true; public float smoothFollowSpeed = 20f; protected bool animatePhysics; private Vector3 lastPosition; private Vector3 localPosition; private Quaternion localRotation; private Quaternion lastRotation; public virtual bool animationGrounded => true; public virtual Vector3 GetPivotPoint() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return ((Component)this).transform.position; } public float GetAngleFromForward(Vector3 worldDirection) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.InverseTransformDirection(worldDirection); return Mathf.Atan2(val.x, val.z) * 57.29578f; } protected virtual void Start() { //IL_002f: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)((Component)((Component)this).transform.parent).GetComponent<CharacterBase>() == (Object)null) { Debug.LogWarning((object)"Animation controllers should be parented to character controllers!", (Object)(object)((Component)this).transform); } lastPosition = ((Component)this).transform.position; localPosition = ((Component)this).transform.localPosition; lastRotation = ((Component)this).transform.rotation; localRotation = ((Component)this).transform.localRotation; } protected virtual void LateUpdate() { if (!animatePhysics) { SmoothFollow(); } } protected virtual void FixedUpdate() { if (animatePhysics) { SmoothFollow(); } } private void SmoothFollow() { //IL_0086: 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_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0036: 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_0057: 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_0062: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) if (smoothFollow) { ((Component)this).transform.position = Vector3.Lerp(lastPosition, ((Component)this).transform.parent.TransformPoint(localPosition), Time.deltaTime * smoothFollowSpeed); ((Component)this).transform.rotation = Quaternion.Lerp(lastRotation, ((Component)this).transform.parent.rotation * localRotation, Time.deltaTime * smoothFollowSpeed); } else { ((Component)this).transform.localPosition = localPosition; ((Component)this).transform.localRotation = localRotation; } lastPosition = ((Component)this).transform.position; lastRotation = ((Component)this).transform.rotation; } } public class CharacterAnimationSimple : CharacterAnimationBase { public CharacterThirdPerson characterController; public float pivotOffset; public AnimationCurve moveSpeed; private Animator animator; protected override void Start() { base.Start(); animator = ((Component)this).GetComponentInChildren<Animator>(); } public override Vector3 GetPivotPoint() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0013: Unknown result type (might be due to invalid IL or missing references) if (pivotOffset == 0f) { return ((Component)this).transform.position; } return ((Component)this).transform.position + ((Component)this).transform.forward * pivotOffset; } private void Update() { //IL_0043: 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) //IL_0058: Unknown result type (might be due to invalid IL or missing references) float num = moveSpeed.Evaluate(characterController.animState.moveDirection.z); animator.SetFloat("Speed", num); characterController.Move(((Component)characterController).transform.forward * Time.deltaTime * num, Quaternion.identity); } } public class CharacterAnimationThirdPerson : CharacterAnimationBase { public CharacterThirdPerson characterController; [SerializeField] private float turnSensitivity = 0.2f; [SerializeField] private float turnSpeed = 5f; [SerializeField] private float runCycleLegOffset = 0.2f; [Range(0.1f, 3f)] [SerializeField] private float animSpeedMultiplier = 1f; protected Animator animator; private Vector3 lastForward; private const string groundedDirectional = "Grounded Directional"; private const string groundedStrafe = "Grounded Strafe"; private float deltaAngle; private float jumpLeg; private bool lastJump; public override bool animationGrounded { get { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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) AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); if (!((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Grounded Directional")) { currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); return ((AnimatorStateInfo)(ref currentAnimatorStateInfo)).IsName("Grounded Strafe"); } return true; } } protected override void Start() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) base.Start(); animator = ((Component)this).GetComponent<Animator>(); lastForward = ((Component)this).transform.forward; } public override Vector3 GetPivotPoint() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return animator.pivotPosition; } protected virtual void Update() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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) if (Time.deltaTime != 0f) { animatePhysics = (int)animator.updateMode == 1; if (characterController.animState.jump && !lastJump) { AnimatorStateInfo currentAnimatorStateInfo = animator.GetCurrentAnimatorStateInfo(0); float num = (float)((Mathf.Repeat(((AnimatorStateInfo)(ref currentAnimatorStateInfo)).normalizedTime + runCycleLegOffset, 1f) < 0.5f) ? 1 : (-1)) * characterController.animState.moveDirection.z; animator.SetFloat("JumpLeg", num); } lastJump = characterController.animState.jump; float num2 = 0f - GetAngleFromForward(lastForward) - deltaAngle; deltaAngle = 0f; lastForward = ((Component)this).transform.forward; num2 *= turnSensitivity * 0.01f; num2 = Mathf.Clamp(num2 / Time.deltaTime, -1f, 1f); animator.SetFloat("Turn", Mathf.Lerp(animator.GetFloat("Turn"), num2, Time.deltaTime * turnSpeed)); animator.SetFloat("Forward", characterController.animState.moveDirection.z); animator.SetFloat("Right", characterController.animState.moveDirection.x); animator.SetBool("Crouch", characterController.animState.crouch); animator.SetBool("OnGround", characterController.animState.onGround); animator.SetBool("IsStrafing", characterController.animState.isStrafing); if (!characterController.animState.onGround) { animator.SetFloat("Jump", characterController.animState.yVelocity); } if (characterController.doubleJumpEnabled) { animator.SetBool("DoubleJump", characterController.animState.doubleJump); } characterController.animState.doubleJump = false; if (characterController.animState.onGround && characterController.animState.moveDirection.z > 0f) { animator.speed = animSpeedMultiplier; } else { animator.speed = 1f; } } } private void OnAnimatorMove() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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) Vector3 val = animator.deltaRotation * Vector3.forward; deltaAngle += Mathf.Atan2(val.x, val.z) * 57.29578f; characterController.Move(animator.deltaPosition, animator.deltaRotation); } } public abstract class CharacterBase : MonoBehaviour { [Header("Base Parameters")] [Tooltip("If specified, will use the direction from the character to this Transform as the gravity vector instead of Physics.gravity. Physics.gravity.magnitude will be used as the magnitude of the gravity vector.")] public Transform gravityTarget; [Tooltip("Multiplies gravity applied to the character even if 'Individual Gravity' is unchecked.")] public float gravityMultiplier = 2f; public float airborneThreshold = 0.6f; public float slopeStartAngle = 50f; public float slopeEndAngle = 85f; public float spherecastRadius = 0.1f; public LayerMask groundLayers; private PhysicMaterial zeroFrictionMaterial; private PhysicMaterial highFrictionMaterial; protected Rigidbody r; protected const float half = 0.5f; protected float originalHeight; protected Vector3 originalCenter; protected CapsuleCollider capsule; public abstract void Move(Vector3 deltaPosition, Quaternion deltaRotation); protected Vector3 GetGravity() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)gravityTarget != (Object)null) { Vector3 val = gravityTarget.position - ((Component)this).transform.position; Vector3 normalized = ((Vector3)(ref val)).normalized; val = Physics.gravity; return normalized * ((Vector3)(ref val)).magnitude; } return Physics.gravity; } protected virtual void Start() { //IL_0035: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown ref CapsuleCollider reference = ref capsule; Collider component = ((Component)this).GetComponent<Collider>(); reference = (CapsuleCollider)(object)((component is CapsuleCollider) ? component : null); r = ((Component)this).GetComponent<Rigidbody>(); originalHeight = capsule.height; originalCenter = capsule.center; zeroFrictionMaterial = new PhysicMaterial(); zeroFrictionMaterial.dynamicFriction = 0f; zeroFrictionMaterial.staticFriction = 0f; zeroFrictionMaterial.frictionCombine = (PhysicMaterialCombine)2; zeroFrictionMaterial.bounciness = 0f; zeroFrictionMaterial.bounceCombine = (PhysicMaterialCombine)2; highFrictionMaterial = new PhysicMaterial(); r.constraints = (RigidbodyConstraints)112; } protected virtual RaycastHit GetSpherecastHit() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_005e: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) Vector3 up = ((Component)this).transform.up; Ray val = new Ray(r.position + up * airborneThreshold, -up); RaycastHit result = default(RaycastHit); ((RaycastHit)(ref result)).point = ((Component)this).transform.position - ((Component)((Component)this).transform).transform.up * airborneThreshold; ((RaycastHit)(ref result)).normal = ((Component)this).transform.up; Physics.SphereCast(val, spherecastRadius, ref result, airborneThreshold * 2f, LayerMask.op_Implicit(groundLayers)); return result; } public float GetAngleFromForward(Vector3 worldDirection) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.InverseTransformDirection(worldDirection); return Mathf.Atan2(val.x, val.z) * 57.29578f; } protected void RigidbodyRotateAround(Vector3 point, Vector3 axis, float angle) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.AngleAxis(angle, axis); Vector3 val2 = ((Component)this).transform.position - point; r.MovePosition(point + val * val2); r.MoveRotation(val * ((Component)this).transform.rotation); } protected void ScaleCapsule(float mlp) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) if (capsule.height != originalHeight * mlp) { capsule.height = Mathf.MoveTowards(capsule.height, originalHeight * mlp, Time.deltaTime * 4f); capsule.center = Vector3.MoveTowards(capsule.center, originalCenter * mlp, Time.deltaTime * 2f); } } protected void HighFriction() { ((Collider)capsule).material = highFrictionMaterial; } protected void ZeroFriction() { ((Collider)capsule).material = zeroFrictionMaterial; } protected float GetSlopeDamper(Vector3 velocity, Vector3 groundNormal) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) float num = 90f - Vector3.Angle(velocity, groundNormal); num -= slopeStartAngle; float num2 = slopeEndAngle - slopeStartAngle; return 1f - Mathf.Clamp(num / num2, 0f, 1f); } } public class CharacterThirdPerson : CharacterBase { [Serializable] public enum MoveMode { Directional, Strafe } public struct AnimState { public Vector3 moveDirection; public bool jump; public bool crouch; public bool onGround; public bool isStrafing; public float yVelocity; public bool doubleJump; } [Header("References")] public CharacterAnimationBase characterAnimation; public UserControlThirdPerson userControl; public CameraController cam; [Header("Movement")] public MoveMode moveMode; public bool smoothPhysics = true; public float smoothAccelerationTime = 0.2f; public float linearAccelerationSpeed = 3f; public float platformFriction = 7f; public float groundStickyEffect = 4f; public float maxVerticalVelocityOnGround = 3f; public float velocityToGroundTangentWeight; [Header("Rotation")] public bool lookInCameraDirection; public float turnSpeed = 5f; public float stationaryTurnSpeedMlp = 1f; [Header("Jumping and Falling")] public bool smoothJump = true; public float airSpeed = 6f; public float airControl = 2f; public float jumpPower = 12f; public float jumpRepeatDelayTime; public bool doubleJumpEnabled; public float doubleJumpPowerMlp = 1f; [Header("Wall Running")] public LayerMask wallRunLayers; public float wallRunMaxLength = 1f; public float wallRunMinMoveMag = 0.6f; public float wallRunMinVelocityY = -1f; public float wallRunRotationSpeed = 1.5f; public float wallRunMaxRotationAngle = 70f; public float wallRunWeightSpeed = 5f; [Header("Crouching")] public float crouchCapsuleScaleMlp = 0.6f; public AnimState animState; protected Vector3 moveDirection; private Animator animator; private Vector3 normal; private Vector3 platformVelocity; private Vector3 platformAngularVelocity; private RaycastHit hit; private float jumpLeg; private float jumpEndTime; private float forwardMlp; private float groundDistance; private float lastAirTime; private float stickyForce; private Vector3 wallNormal = Vector3.up; private Vector3 moveDirectionVelocity; private float wallRunWeight; private float lastWallRunWeight; private float fixedDeltaTime; private Vector3 fixedDeltaPosition; private Quaternion fixedDeltaRotation = Quaternion.identity; private bool fixedFrame; private float wallRunEndTime; private Vector3 gravity; private Vector3 verticalVelocity; private float velocityY; private bool doubleJumped; private bool jumpReleased; public bool onGround { get; private set; } protected override void Start() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) base.Start(); animator = ((Component)this).GetComponent<Animator>(); if ((Object)(object)animator == (Object)null) { animator = ((Component)characterAnimation).GetComponent<Animator>(); } wallNormal = -((Vector3)(ref gravity)).normalized; onGround = true; animState.onGround = true; if ((Object)(object)cam != (Object)null) { ((Behaviour)cam).enabled = false; } } private void OnAnimatorMove() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) Move(animator.deltaPosition, animator.deltaRotation); } public override void Move(Vector3 deltaPosition, Quaternion deltaRotation) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) fixedDeltaTime += Time.deltaTime; fixedDeltaPosition += deltaPosition; fixedDeltaRotation *= deltaRotation; } private void FixedUpdate() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: 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_019d: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //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) gravity = GetGravity(); verticalVelocity = V3Tools.ExtractVertical(r.velocity, gravity, 1f); velocityY = ((Vector3)(ref verticalVelocity)).magnitude; if (Vector3.Dot(verticalVelocity, gravity) > 0f) { velocityY = 0f - velocityY; } r.interpolation = (RigidbodyInterpolation)(smoothPhysics ? 1 : 0); characterAnimation.smoothFollow = smoothPhysics; MoveFixed(fixedDeltaPosition); fixedDeltaTime = 0f; fixedDeltaPosition = Vector3.zero; r.MoveRotation(((Component)this).transform.rotation * fixedDeltaRotation); fixedDeltaRotation = Quaternion.identity; Rotate(); GroundCheck(); if (userControl.state.move == Vector3.zero && groundDistance < airborneThreshold * 0.5f) { HighFriction(); } else { ZeroFriction(); } int num; if (onGround && userControl.state.move == Vector3.zero) { Vector3 velocity = r.velocity; if (((Vector3)(ref velocity)).magnitude < 0.5f) { num = ((groundDistance < airborneThreshold * 0.5f) ? 1 : 0); goto IL_0178; } } num = 0; goto IL_0178; IL_0178: bool flag = (byte)num != 0; if ((Object)(object)gravityTarget != (Object)null) { r.useGravity = false; if (!flag) { r.AddForce(gravity); } } if (flag) { r.useGravity = false; r.velocity = Vector3.zero; } else if ((Object)(object)gravityTarget == (Object)null) { r.useGravity = true; } if (onGround) { animState.jump = Jump(); jumpReleased = false; doubleJumped = false; } else { if (!userControl.state.jump) { jumpReleased = true; } if (jumpReleased && userControl.state.jump && !doubleJumped && doubleJumpEnabled) { jumpEndTime = Time.time + 0.1f; animState.doubleJump = true; Vector3 velocity2 = userControl.state.move * airSpeed; r.velocity = velocity2; Rigidbody obj = r; obj.velocity += ((Component)this).transform.up * jumpPower * doubleJumpPowerMlp; doubleJumped = true; } } ScaleCapsule(userControl.state.crouch ? crouchCapsuleScaleMlp : 1f); fixedFrame = true; } protected virtual void Update() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) animState.onGround = onGround; animState.moveDirection = GetMoveDirection(); animState.yVelocity = Mathf.Lerp(animState.yVelocity, velocityY, Time.deltaTime * 10f); animState.crouch = userControl.state.crouch; animState.isStrafing = moveMode == MoveMode.Strafe; } protected virtual void LateUpdate() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)cam == (Object)null)) { cam.UpdateInput(); if (fixedFrame || (int)r.interpolation != 0) { cam.UpdateTransform(((int)r.interpolation == 0) ? Time.fixedDeltaTime : Time.deltaTime); fixedFrame = false; } } } private void MoveFixed(Vector3 deltaPosition) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) WallRun(); Vector3 val = ((fixedDeltaTime > 0f) ? (deltaPosition / fixedDeltaTime) : Vector3.zero); val += V3Tools.ExtractHorizontal(platformVelocity, gravity, 1f); if (onGround) { if (velocityToGroundTangentWeight > 0f) { Quaternion val2 = Quaternion.FromToRotation(((Component)this).transform.up, normal); val = Quaternion.Lerp(Quaternion.identity, val2, velocityToGroundTangentWeight) * val; } } else { Vector3 val3 = V3Tools.ExtractHorizontal(userControl.state.move * airSpeed, gravity, 1f); val = Vector3.Lerp(r.velocity, val3, Time.deltaTime * airControl); } if (onGround && Time.time > jumpEndTime) { r.velocity -= ((Component)this).transform.up * stickyForce * Time.deltaTime; } Vector3 val4 = V3Tools.ExtractVertical(r.velocity, gravity, 1f); Vector3 val5 = V3Tools.ExtractHorizontal(val, gravity, 1f); if (onGround && Vector3.Dot(val4, gravity) < 0f) { val4 = Vector3.ClampMagnitude(val4, maxVerticalVelocityOnGround); } r.velocity = val5 + val4; forwardMlp = 1f; } private void WallRun() { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: 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_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0118: 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_018f: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) bool flag = CanWallRun(); if (wallRunWeight > 0f && !flag) { wallRunEndTime = Time.time; } if (Time.time < wallRunEndTime + 0.5f) { flag = false; } wallRunWeight = Mathf.MoveTowards(wallRunWeight, flag ? 1f : 0f, Time.deltaTime * wallRunWeightSpeed); if (wallRunWeight <= 0f && lastWallRunWeight > 0f) { Vector3 val = V3Tools.ExtractHorizontal(((Component)this).transform.forward, gravity, 1f); ((Component)this).transform.rotation = Quaternion.LookRotation(val, -gravity); wallNormal = -((Vector3)(ref gravity)).normalized; } lastWallRunWeight = wallRunWeight; if (!(wallRunWeight <= 0f)) { if (onGround && velocityY < 0f) { r.velocity = V3Tools.ExtractHorizontal(r.velocity, gravity, 1f); } Vector3 val2 = V3Tools.ExtractHorizontal(((Component)this).transform.forward, gravity, 1f); RaycastHit val3 = default(RaycastHit); ((RaycastHit)(ref val3)).normal = -((Vector3)(ref gravity)).normalized; Vector3 val4; if (!onGround) { Bounds bounds = ((Collider)capsule).bounds; val4 = ((Bounds)(ref bounds)).center; } else { val4 = ((Component)this).transform.position; } Physics.Raycast(val4, val2, ref val3, 3f, LayerMask.op_Implicit(wallRunLayers)); wallNormal = Vector3.Lerp(wallNormal, ((RaycastHit)(ref val3)).normal, Time.deltaTime * wallRunRotationSpeed); wallNormal = Vector3.RotateTowards(-((Vector3)(ref gravity)).normalized, wallNormal, wallRunMaxRotationAngle * (MathF.PI / 180f), 0f); Vector3 forward = ((Component)this).transform.forward; Vector3 val5 = wallNormal; Vector3.OrthoNormalize(ref val5, ref forward); ((Component)this).transform.rotation = Quaternion.Slerp(Quaternion.LookRotation(val2, -gravity), Quaternion.LookRotation(forward, wallNormal), wallRunWeight); } } private bool CanWallRun() { if (Time.time < jumpEndTime - 0.1f) { return false; } if (Time.time > jumpEndTime - 0.1f + wallRunMaxLength) { return false; } if (velocityY < wallRunMinVelocityY) { return false; } if (((Vector3)(ref userControl.state.move)).magnitude < wallRunMinMoveMag) { return false; } return true; } private Vector3 GetMoveDirection() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) switch (moveMode) { case MoveMode.Directional: moveDirection = Vector3.SmoothDamp(moveDirection, new Vector3(0f, 0f, ((Vector3)(ref userControl.state.move)).magnitude), ref moveDirectionVelocity, smoothAccelerationTime); moveDirection = Vector3.MoveTowards(moveDirection, new Vector3(0f, 0f, ((Vector3)(ref userControl.state.move)).magnitude), Time.deltaTime * linearAccelerationSpeed); return moveDirection * forwardMlp; case MoveMode.Strafe: moveDirection = Vector3.SmoothDamp(moveDirection, userControl.state.move, ref moveDirectionVelocity, smoothAccelerationTime); moveDirection = Vector3.MoveTowards(moveDirection, userControl.state.move, Time.deltaTime * linearAccelerationSpeed); return ((Component)this).transform.InverseTransformDirection(moveDirection); default: return Vector3.zero; } } protected virtual void Rotate() { //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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)gravityTarget != (Object)null) { r.MoveRotation(Quaternion.FromToRotation(((Component)this).transform.up, ((Component)this).transform.position - gravityTarget.position) * ((Component)this).transform.rotation); } if (platformAngularVelocity != Vector3.zero) { r.MoveRotation(Quaternion.Euler(platformAngularVelocity) * ((Component)this).transform.rotation); } float num = GetAngleFromForward(GetForwardDirection()); if (userControl.state.move == Vector3.zero) { num *= (1.01f - Mathf.Abs(num) / 180f) * stationaryTurnSpeedMlp; } r.MoveRotation(Quaternion.AngleAxis(num * Time.deltaTime * turnSpeed, ((Component)this).transform.up) * r.rotation); } private Vector3 GetForwardDirection() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) bool flag = userControl.state.move != Vector3.zero; switch (moveMode) { case MoveMode.Directional: if (flag) { return userControl.state.move; } if (!lookInCameraDirection) { return ((Component)this).transform.forward; } return userControl.state.lookPos - r.position; case MoveMode.Strafe: if (flag) { return userControl.state.lookPos - r.position; } if (!lookInCameraDirection) { return ((Component)this).transform.forward; } return userControl.state.lookPos - r.position; default: return Vector3.zero; } } protected virtual bool Jump() { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) if (!userControl.state.jump) { return false; } if (userControl.state.crouch) { return false; } if (!characterAnimation.animationGrounded) { return false; } if (Time.time < lastAirTime + jumpRepeatDelayTime) { return false; } onGround = false; jumpEndTime = Time.time + 0.1f; Vector3 val = userControl.state.move * airSpeed; val += ((Component)this).transform.up * jumpPower; if (smoothJump) { ((MonoBehaviour)this).StopAllCoroutines(); ((MonoBehaviour)this).StartCoroutine(JumpSmooth(val - r.velocity)); } else { r.velocity = val; } return true; } private IEnumerator JumpSmooth(Vector3 jumpVelocity) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) int steps = 0; int stepsToTake = 3; while (steps < stepsToTake) { r.AddForce(jumpVelocity / (float)stepsToTake, (ForceMode)2); steps++; yield return (object)new WaitForFixedUpdate(); } } private void GroundCheck() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Vector3.zero; platformAngularVelocity = Vector3.zero; float num = 0f; hit = GetSpherecastHit(); normal = ((Component)this).transform.up; Vector3 val2 = Vector3.Project(r.position - ((RaycastHit)(ref hit)).point, ((Component)this).transform.up); groundDistance = ((Vector3)(ref val2)).magnitude; if (Time.time > jumpEndTime && velocityY < jumpPower * 0.5f) { bool num2 = onGround; onGround = false; float num3 = ((!num2) ? (airborneThreshold * 0.5f) : airborneThreshold); Vector3 val3 = V3Tools.ExtractHorizontal(r.velocity, gravity, 1f); float magnitude = ((Vector3)(ref val3)).magnitude; if (groundDistance < num3) { num = groundStickyEffect * magnitude * num3; if ((Object)(object)((RaycastHit)(ref hit)).rigidbody != (Object)null) { val = ((RaycastHit)(ref hit)).rigidbody.GetPointVelocity(((RaycastHit)(ref hit)).point); platformAngularVelocity = Vector3.Project(((RaycastHit)(ref hit)).rigidbody.angularVelocity, ((Component)this).transform.up); } onGround = true; } } platformVelocity = Vector3.Lerp(platformVelocity, val, Time.deltaTime * platformFriction); stickyForce = num; if (!onGround) { lastAirTime = Time.time; } } } public class SimpleLocomotion : MonoBehaviour { [Serializable] public enum RotationMode { Smooth, Linear } [Tooltip("The component that updates the camera.")] public CameraController cameraController; [Tooltip("Acceleration of movement.")] public float accelerationTime = 0.2f; [Tooltip("Turning speed.")] public float turnTime = 0.2f; [Tooltip("If true, will run on left shift, if not will walk on left shift.")] public bool walkByDefault = true; [Tooltip("Smooth or linear rotation.")] public RotationMode rotationMode; [Tooltip("Procedural motion speed (if not using root motion).")] public float moveSpeed = 3f; private Animator animator; private float speed; private float angleVel; private float speedVel; private Vector3 linearTargetDirection; private CharacterController characterController; public bool isGrounded { get; private set; } private void Start() { animator = ((Component)this).GetComponent<Animator>(); characterController = ((Component)this).GetComponent<CharacterController>(); ((Behaviour)cameraController).enabled = false; } private void Update() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) isGrounded = ((Component)this).transform.position.y < 0.1f; Rotate(); Move(); } private void LateUpdate() { cameraController.UpdateInput(); cameraController.UpdateTransform(); } private void Rotate() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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) if (!isGrounded) { return; } Vector3 inputVector = GetInputVector(); if (inputVector == Vector3.zero) { return; } Vector3 forward = ((Component)this).transform.forward; switch (rotationMode) { case RotationMode.Smooth: { Vector3 val = ((Component)cameraController).transform.rotation * inputVector; float num = Mathf.Atan2(forward.x, forward.z) * 57.29578f; float num2 = Mathf.Atan2(val.x, val.z) * 57.29578f; float num3 = Mathf.SmoothDampAngle(num, num2, ref angleVel, turnTime); ((Component)this).transform.rotation = Quaternion.AngleAxis(num3, Vector3.up); break; } case RotationMode.Linear: { Vector3 inputVectorRaw = GetInputVectorRaw(); if (inputVectorRaw != Vector3.zero) { linearTargetDirection = ((Component)cameraController).transform.rotation * inputVectorRaw; } forward = Vector3.RotateTowards(forward, linearTargetDirection, Time.deltaTime * (1f / turnTime), 1f); forward.y = 0f; ((Component)this).transform.rotation = Quaternion.LookRotation(forward); break; } } } private void Move() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) float num = ((!walkByDefault) ? (Input.GetKey((KeyCode)304) ? 0.5f : 1f) : (Input.GetKey((KeyCode)304) ? 1f : 0.5f)); speed = Mathf.SmoothDamp(speed, num, ref speedVel, accelerationTime); Vector3 inputVector = GetInputVector(); float num2 = ((Vector3)(ref inputVector)).magnitude * speed; animator.SetFloat("Speed", num2); if (!animator.hasRootMotion && isGrounded) { Vector3 val = ((Component)this).transform.forward * num2 * moveSpeed; if ((Object)(object)characterController != (Object)null) { characterController.SimpleMove(val); return; } Transform transform = ((Component)this).transform; transform.position += val * Time.deltaTime; } } private Vector3 GetInputVector() { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")); val.z += Mathf.Abs(val.x) * 0.05f; val.x -= Mathf.Abs(val.z) * 0.05f; return val; } private Vector3 GetInputVectorRaw() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) return new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")); } } public class UserControlAI : UserControlThirdPerson { public Transform moveTarget; public float stoppingDistance = 0.5f; public float stoppingThreshold = 1.5f; public Navigator navigator; protected override void Start() { base.Start(); navigator.Initiate(((Component)this).transform); } protected override void Update() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) float num = (walkByDefault ? 0.5f : 1f); if (navigator.activeTargetSeeking) { navigator.Update(moveTarget.position); state.move = navigator.normalizedDeltaPosition * num; return; } Vector3 val = moveTarget.position - ((Component)this).transform.position; float magnitude = ((Vector3)(ref val)).magnitude; Vector3 up = ((Component)this).transform.up; Vector3.OrthoNormalize(ref up, ref val); float num2 = ((state.move != Vector3.zero) ? stoppingDistance : (stoppingDistance * stoppingThreshold)); state.move = ((magnitude > num2) ? (val * num) : Vector3.zero); state.lookPos = moveTarget.position; } private void OnDrawGizmos() { if (navigator.activeTargetSeeking) { navigator.Visualize(); } } } public class UserControlThirdPerson : MonoBehaviour { public struct State { public Vector3 move; public Vector3 lookPos; public bool crouch; public bool jump; public int actionIndex; } public bool walkByDefault; public bool canCrouch = true; public bool canJump = true; public State state; protected Transform cam; protected virtual void Start() { cam = ((Component)Camera.main).transform; } protected virtual void Update() { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) state.crouch = canCrouch && Input.GetKey((KeyCode)99); state.jump = canJump && Input.GetButton("Jump"); float axisRaw = Input.GetAxisRaw("Horizontal"); float axisRaw2 = Input.GetAxisRaw("Vertical"); Quaternion rotation = cam.rotation; Vector3 val = new Vector3(axisRaw, 0f, axisRaw2); Vector3 val2 = rotation * ((Vector3)(ref val)).normalized; if (val2 != Vector3.zero) { Vector3 up = ((Component)this).transform.up; Vector3.OrthoNormalize(ref up, ref val2); state.move = val2; } else { state.move = Vector3.zero; } bool key = Input.GetKey((KeyCode)304); float num = ((!walkByDefault) ? (key ? 0.5f : 1f) : (key ? 1f : 0.5f)); ref Vector3 move = ref state.move; move *= num; state.lookPos = ((Component)this).transform.position + cam.forward * 100f; } } public class ApplicationQuit : MonoBehaviour { private void Update() { if (Input.GetKeyDown((KeyCode)113) || Input.GetKeyDown((KeyCode)27)) { Application.Quit(); } } } public class SlowMo : MonoBehaviour { public KeyCode[] keyCodes; public bool mouse0; public bool mouse1; public float slowMoTimeScale = 0.3f; private void Update() { Time.timeScale = (IsSlowMotion() ? slowMoTimeScale : 1f); } private bool IsSlowMotion() { if (mouse0 && Input.GetMouseButton(0)) { return true; } if (mouse1 && Input.GetMouseButton(1)) { return true; } for (int i = 0; i < keyCodes.Length; i++) { if (Input.GetKey(keyCodes[i])) { return true; } } return false; } } }
plugins/Valheim_Data/Managed/root_motion_shared.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.AI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] namespace RootMotion { [Serializable] public enum Axis { X, Y, Z } public class AxisTools { public static Vector3 ToVector3(Axis axis) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return (Vector3)(axis switch { Axis.X => Vector3.right, Axis.Y => Vector3.up, _ => Vector3.forward, }); } public static Axis ToAxis(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Abs(v.x); float num2 = Mathf.Abs(v.y); float num3 = Mathf.Abs(v.z); Axis result = Axis.X; if (num2 > num && num2 > num3) { result = Axis.Y; } if (num3 > num && num3 > num2) { result = Axis.Z; } return result; } public static Axis GetAxisToPoint(Transform t, Vector3 worldPosition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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) Vector3 axisVectorToPoint = GetAxisVectorToPoint(t, worldPosition); if (axisVectorToPoint == Vector3.right) { return Axis.X; } if (axisVectorToPoint == Vector3.up) { return Axis.Y; } return Axis.Z; } public static Axis GetAxisToDirection(Transform t, Vector3 direction) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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) Vector3 axisVectorToDirection = GetAxisVectorToDirection(t, direction); if (axisVectorToDirection == Vector3.right) { return Axis.X; } if (axisVectorToDirection == Vector3.up) { return Axis.Y; } return Axis.Z; } public static Vector3 GetAxisVectorToPoint(Transform t, Vector3 worldPosition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return GetAxisVectorToDirection(t, worldPosition - t.position); } public static Vector3 GetAxisVectorToDirection(Transform t, Vector3 direction) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return GetAxisVectorToDirection(t.rotation, direction); } public static Vector3 GetAxisVectorToDirection(Quaternion r, Vector3 direction) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_007b: 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) direction = ((Vector3)(ref direction)).normalized; Vector3 result = Vector3.right; float num = Mathf.Abs(Vector3.Dot(Vector3.Normalize(r * Vector3.right), direction)); float num2 = Mathf.Abs(Vector3.Dot(Vector3.Normalize(r * Vector3.up), direction)); if (num2 > num) { result = Vector3.up; } float num3 = Mathf.Abs(Vector3.Dot(Vector3.Normalize(r * Vector3.forward), direction)); if (num3 > num && num3 > num2) { result = Vector3.forward; } return result; } } [Serializable] public class BipedLimbOrientations { [Serializable] public class LimbOrientation { public Vector3 upperBoneForwardAxis; public Vector3 lowerBoneForwardAxis; public Vector3 lastBoneLeftAxis; public LimbOrientation(Vector3 upperBoneForwardAxis, Vector3 lowerBoneForwardAxis, Vector3 lastBoneLeftAxis) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) this.upperBoneForwardAxis = upperBoneForwardAxis; this.lowerBoneForwardAxis = lowerBoneForwardAxis; this.lastBoneLeftAxis = lastBoneLeftAxis; } } public LimbOrientation leftArm; public LimbOrientation rightArm; public LimbOrientation leftLeg; public LimbOrientation rightLeg; public static BipedLimbOrientations UMA => new BipedLimbOrientations(new LimbOrientation(Vector3.forward, Vector3.forward, Vector3.forward), new LimbOrientation(Vector3.forward, Vector3.forward, Vector3.back), new LimbOrientation(Vector3.forward, Vector3.forward, Vector3.down), new LimbOrientation(Vector3.forward, Vector3.forward, Vector3.down)); public static BipedLimbOrientations MaxBiped => new BipedLimbOrientations(new LimbOrientation(Vector3.down, Vector3.down, Vector3.down), new LimbOrientation(Vector3.down, Vector3.down, Vector3.up), new LimbOrientation(Vector3.up, Vector3.up, Vector3.back), new LimbOrientation(Vector3.up, Vector3.up, Vector3.back)); public BipedLimbOrientations(LimbOrientation leftArm, LimbOrientation rightArm, LimbOrientation leftLeg, LimbOrientation rightLeg) { this.leftArm = leftArm; this.rightArm = rightArm; this.leftLeg = leftLeg; this.rightLeg = rightLeg; } } public static class BipedNaming { [Serializable] public enum BoneType { Unassigned, Spine, Head, Arm, Leg, Tail, Eye } [Serializable] public enum BoneSide { Center, Left, Right } public static string[] typeLeft = new string[9] { " L ", "_L_", "-L-", " l ", "_l_", "-l-", "Left", "left", "CATRigL" }; public static string[] typeRight = new string[9] { " R ", "_R_", "-R-", " r ", "_r_", "-r-", "Right", "right", "CATRigR" }; public static string[] typeSpine = new string[16] { "Spine", "spine", "Pelvis", "pelvis", "Root", "root", "Torso", "torso", "Body", "body", "Hips", "hips", "Neck", "neck", "Chest", "chest" }; public static string[] typeHead = new string[2] { "Head", "head" }; public static string[] typeArm = new string[10] { "Arm", "arm", "Hand", "hand", "Wrist", "Wrist", "Elbow", "elbow", "Palm", "palm" }; public static string[] typeLeg = new string[16] { "Leg", "leg", "Thigh", "thigh", "Calf", "calf", "Femur", "femur", "Knee", "knee", "Foot", "foot", "Ankle", "ankle", "Hip", "hip" }; public static string[] typeTail = new string[2] { "Tail", "tail" }; public static string[] typeEye = new string[2] { "Eye", "eye" }; public static string[] typeExclude = new string[6] { "Nub", "Dummy", "dummy", "Tip", "IK", "Mesh" }; public static string[] typeExcludeSpine = new string[2] { "Head", "head" }; public static string[] typeExcludeHead = new string[2] { "Top", "End" }; public static string[] typeExcludeArm = new string[19] { "Collar", "collar", "Clavicle", "clavicle", "Finger", "finger", "Index", "index", "Mid", "mid", "Pinky", "pinky", "Ring", "Thumb", "thumb", "Adjust", "adjust", "Twist", "twist" }; public static string[] typeExcludeLeg = new string[7] { "Toe", "toe", "Platform", "Adjust", "adjust", "Twist", "twist" }; public static string[] typeExcludeTail = new string[0]; public static string[] typeExcludeEye = new string[6] { "Lid", "lid", "Brow", "brow", "Lash", "lash" }; public static string[] pelvis = new string[4] { "Pelvis", "pelvis", "Hip", "hip" }; public static string[] hand = new string[6] { "Hand", "hand", "Wrist", "wrist", "Palm", "palm" }; public static string[] foot = new string[4] { "Foot", "foot", "Ankle", "ankle" }; public static Transform[] GetBonesOfType(BoneType boneType, Transform[] bones) { Transform[] array = (Transform[])(object)new Transform[0]; foreach (Transform val in bones) { if ((Object)(object)val != (Object)null && GetBoneType(((Object)val).name) == boneType) { Array.Resize(ref array, array.Length + 1); array[^1] = val; } } return array; } public static Transform[] GetBonesOfSide(BoneSide boneSide, Transform[] bones) { Transform[] array = (Transform[])(object)new Transform[0]; foreach (Transform val in bones) { if ((Object)(object)val != (Object)null && GetBoneSide(((Object)val).name) == boneSide) { Array.Resize(ref array, array.Length + 1); array[^1] = val; } } return array; } public static Transform[] GetBonesOfTypeAndSide(BoneType boneType, BoneSide boneSide, Transform[] bones) { Transform[] bonesOfType = GetBonesOfType(boneType, bones); return GetBonesOfSide(boneSide, bonesOfType); } public static Transform GetFirstBoneOfTypeAndSide(BoneType boneType, BoneSide boneSide, Transform[] bones) { Transform[] bonesOfTypeAndSide = GetBonesOfTypeAndSide(boneType, boneSide, bones); if (bonesOfTypeAndSide.Length == 0) { return null; } return bonesOfTypeAndSide[0]; } public static Transform GetNamingMatch(Transform[] transforms, params string[][] namings) { foreach (Transform val in transforms) { bool flag = true; foreach (string[] namingConvention in namings) { if (!matchesNaming(((Object)val).name, namingConvention)) { flag = false; break; } } if (flag) { return val; } } return null; } public static BoneType GetBoneType(string boneName) { if (isSpine(boneName)) { return BoneType.Spine; } if (isHead(boneName)) { return BoneType.Head; } if (isArm(boneName)) { return BoneType.Arm; } if (isLeg(boneName)) { return BoneType.Leg; } if (isTail(boneName)) { return BoneType.Tail; } if (isEye(boneName)) { return BoneType.Eye; } return BoneType.Unassigned; } public static BoneSide GetBoneSide(string boneName) { if (isLeft(boneName)) { return BoneSide.Left; } if (isRight(boneName)) { return BoneSide.Right; } return BoneSide.Center; } public static Transform GetBone(Transform[] transforms, BoneType boneType, BoneSide boneSide = BoneSide.Center, params string[][] namings) { return GetNamingMatch(GetBonesOfTypeAndSide(boneType, boneSide, transforms), namings); } private static bool isLeft(string boneName) { if (!matchesNaming(boneName, typeLeft) && !(lastLetter(boneName) == "L")) { return firstLetter(boneName) == "L"; } return true; } private static bool isRight(string boneName) { if (!matchesNaming(boneName, typeRight) && !(lastLetter(boneName) == "R")) { return firstLetter(boneName) == "R"; } return true; } private static bool isSpine(string boneName) { if (matchesNaming(boneName, typeSpine)) { return !excludesNaming(boneName, typeExcludeSpine); } return false; } private static bool isHead(string boneName) { if (matchesNaming(boneName, typeHead)) { return !excludesNaming(boneName, typeExcludeHead); } return false; } private static bool isArm(string boneName) { if (matchesNaming(boneName, typeArm)) { return !excludesNaming(boneName, typeExcludeArm); } return false; } private static bool isLeg(string boneName) { if (matchesNaming(boneName, typeLeg)) { return !excludesNaming(boneName, typeExcludeLeg); } return false; } private static bool isTail(string boneName) { if (matchesNaming(boneName, typeTail)) { return !excludesNaming(boneName, typeExcludeTail); } return false; } private static bool isEye(string boneName) { if (matchesNaming(boneName, typeEye)) { return !excludesNaming(boneName, typeExcludeEye); } return false; } private static bool isTypeExclude(string boneName) { return matchesNaming(boneName, typeExclude); } private static bool matchesNaming(string boneName, string[] namingConvention) { if (excludesNaming(boneName, typeExclude)) { return false; } foreach (string value in namingConvention) { if (boneName.Contains(value)) { return true; } } return false; } private static bool excludesNaming(string boneName, string[] namingConvention) { foreach (string value in namingConvention) { if (boneName.Contains(value)) { return true; } } return false; } private static bool matchesLastLetter(string boneName, string[] namingConvention) { foreach (string letter in namingConvention) { if (LastLetterIs(boneName, letter)) { return true; } } return false; } private static bool LastLetterIs(string boneName, string letter) { return boneName.Substring(boneName.Length - 1, 1) == letter; } private static string firstLetter(string boneName) { if (boneName.Length > 0) { return boneName.Substring(0, 1); } return ""; } private static string lastLetter(string boneName) { if (boneName.Length > 0) { return boneName.Substring(boneName.Length - 1, 1); } return ""; } } [Serializable] public class BipedReferences { public struct AutoDetectParams { public bool legsParentInSpine; public bool includeEyes; public static AutoDetectParams Default => new AutoDetectParams(legsParentInSpine: true, includeEyes: true); public AutoDetectParams(bool legsParentInSpine, bool includeEyes) { this.legsParentInSpine = legsParentInSpine; this.includeEyes = includeEyes; } } public Transform root; public Transform pelvis; public Transform leftThigh; public Transform leftCalf; public Transform leftFoot; public Transform rightThigh; public Transform rightCalf; public Transform rightFoot; public Transform leftUpperArm; public Transform leftForearm; public Transform leftHand; public Transform rightUpperArm; public Transform rightForearm; public Transform rightHand; public Transform head; public Transform[] spine = (Transform[])(object)new Transform[0]; public Transform[] eyes = (Transform[])(object)new Transform[0]; public virtual bool isFilled { get { if ((Object)(object)root == (Object)null) { return false; } if ((Object)(object)pelvis == (Object)null) { return false; } if ((Object)(object)leftThigh == (Object)null || (Object)(object)leftCalf == (Object)null || (Object)(object)leftFoot == (Object)null) { return false; } if ((Object)(object)rightThigh == (Object)null || (Object)(object)rightCalf == (Object)null || (Object)(object)rightFoot == (Object)null) { return false; } if ((Object)(object)leftUpperArm == (Object)null || (Object)(object)leftForearm == (Object)null || (Object)(object)leftHand == (Object)null) { return false; } if ((Object)(object)rightUpperArm == (Object)null || (Object)(object)rightForearm == (Object)null || (Object)(object)rightHand == (Object)null) { return false; } Transform[] array = spine; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] == (Object)null) { return false; } } array = eyes; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] == (Object)null) { return false; } } return true; } } public bool isEmpty => IsEmpty(includeRoot: true); public virtual bool IsEmpty(bool includeRoot) { if (includeRoot && (Object)(object)root != (Object)null) { return false; } if ((Object)(object)pelvis != (Object)null || (Object)(object)head != (Object)null) { return false; } if ((Object)(object)leftThigh != (Object)null || (Object)(object)leftCalf != (Object)null || (Object)(object)leftFoot != (Object)null) { return false; } if ((Object)(object)rightThigh != (Object)null || (Object)(object)rightCalf != (Object)null || (Object)(object)rightFoot != (Object)null) { return false; } if ((Object)(object)leftUpperArm != (Object)null || (Object)(object)leftForearm != (Object)null || (Object)(object)leftHand != (Object)null) { return false; } if ((Object)(object)rightUpperArm != (Object)null || (Object)(object)rightForearm != (Object)null || (Object)(object)rightHand != (Object)null) { return false; } Transform[] array = spine; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null) { return false; } } array = eyes; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null) { return false; } } return true; } public virtual bool Contains(Transform t, bool ignoreRoot = false) { if (!ignoreRoot && (Object)(object)root == (Object)(object)t) { return true; } if ((Object)(object)pelvis == (Object)(object)t) { return true; } if ((Object)(object)leftThigh == (Object)(object)t) { return true; } if ((Object)(object)leftCalf == (Object)(object)t) { return true; } if ((Object)(object)leftFoot == (Object)(object)t) { return true; } if ((Object)(object)rightThigh == (Object)(object)t) { return true; } if ((Object)(object)rightCalf == (Object)(object)t) { return true; } if ((Object)(object)rightFoot == (Object)(object)t) { return true; } if ((Object)(object)leftUpperArm == (Object)(object)t) { return true; } if ((Object)(object)leftForearm == (Object)(object)t) { return true; } if ((Object)(object)leftHand == (Object)(object)t) { return true; } if ((Object)(object)rightUpperArm == (Object)(object)t) { return true; } if ((Object)(object)rightForearm == (Object)(object)t) { return true; } if ((Object)(object)rightHand == (Object)(object)t) { return true; } if ((Object)(object)head == (Object)(object)t) { return true; } Transform[] array = spine; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] == (Object)(object)t) { return true; } } array = eyes; for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] == (Object)(object)t) { return true; } } return false; } public static bool AutoDetectReferences(ref BipedReferences references, Transform root, AutoDetectParams autoDetectParams) { if (references == null) { references = new BipedReferences(); } references.root = root; Animator component = ((Component)root).GetComponent<Animator>(); if ((Object)(object)component != (Object)null && component.isHuman) { AssignHumanoidReferences(ref references, component, autoDetectParams); return true; } DetectReferencesByNaming(ref references, root, autoDetectParams); Warning.logged = false; if (!references.isFilled) { Warning.Log("BipedReferences contains one or more missing Transforms.", root, logInEditMode: true); return false; } string errorMessage = ""; if (SetupError(references, ref errorMessage)) { Warning.Log(errorMessage, references.root, logInEditMode: true); return false; } if (SetupWarning(references, ref errorMessage)) { Warning.Log(errorMessage, references.root, logInEditMode: true); } return true; } public static void DetectReferencesByNaming(ref BipedReferences references, Transform root, AutoDetectParams autoDetectParams) { if (references == null) { references = new BipedReferences(); } Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(); DetectLimb(BipedNaming.BoneType.Arm, BipedNaming.BoneSide.Left, ref references.leftUpperArm, ref references.leftForearm, ref references.leftHand, componentsInChildren); DetectLimb(BipedNaming.BoneType.Arm, BipedNaming.BoneSide.Right, ref references.rightUpperArm, ref references.rightForearm, ref references.rightHand, componentsInChildren); DetectLimb(BipedNaming.BoneType.Leg, BipedNaming.BoneSide.Left, ref references.leftThigh, ref references.leftCalf, ref references.leftFoot, componentsInChildren); DetectLimb(BipedNaming.BoneType.Leg, BipedNaming.BoneSide.Right, ref references.rightThigh, ref references.rightCalf, ref references.rightFoot, componentsInChildren); references.head = BipedNaming.GetBone(componentsInChildren, BipedNaming.BoneType.Head, BipedNaming.BoneSide.Center); references.pelvis = BipedNaming.GetNamingMatch(componentsInChildren, BipedNaming.pelvis); if (((Object)(object)references.pelvis == (Object)null || !Hierarchy.IsAncestor(references.leftThigh, references.pelvis)) && (Object)(object)references.leftThigh != (Object)null) { references.pelvis = references.leftThigh.parent; } if ((Object)(object)references.leftUpperArm != (Object)null && (Object)(object)references.rightUpperArm != (Object)null && (Object)(object)references.pelvis != (Object)null && (Object)(object)references.leftThigh != (Object)null) { Transform firstCommonAncestor = Hierarchy.GetFirstCommonAncestor(references.leftUpperArm, references.rightUpperArm); if ((Object)(object)firstCommonAncestor != (Object)null) { Transform[] array = (Transform[])(object)new Transform[1] { firstCommonAncestor }; Hierarchy.AddAncestors(array[0], references.pelvis, ref array); references.spine = (Transform[])(object)new Transform[0]; for (int num = array.Length - 1; num > -1; num--) { if (AddBoneToSpine(array[num], ref references, autoDetectParams)) { Array.Resize(ref references.spine, references.spine.Length + 1); references.spine[references.spine.Length - 1] = array[num]; } } if ((Object)(object)references.head == (Object)null) { for (int i = 0; i < firstCommonAncestor.childCount; i++) { Transform child = firstCommonAncestor.GetChild(i); if (!Hierarchy.ContainsChild(child, references.leftUpperArm) && !Hierarchy.ContainsChild(child, references.rightUpperArm)) { references.head = child; break; } } } } } Transform[] bonesOfType = BipedNaming.GetBonesOfType(BipedNaming.BoneType.Eye, componentsInChildren); references.eyes = (Transform[])(object)new Transform[0]; if (!autoDetectParams.includeEyes) { return; } for (int j = 0; j < bonesOfType.Length; j++) { if (AddBoneToEyes(bonesOfType[j], ref references, autoDetectParams)) { Array.Resize(ref references.eyes, references.eyes.Length + 1); references.eyes[references.eyes.Length - 1] = bonesOfType[j]; } } } public static void AssignHumanoidReferences(ref BipedReferences references, Animator animator, AutoDetectParams autoDetectParams) { if (references == null) { references = new BipedReferences(); } if (!((Object)(object)animator == (Object)null) && animator.isHuman) { references.spine = (Transform[])(object)new Transform[0]; references.eyes = (Transform[])(object)new Transform[0]; references.head = animator.GetBoneTransform((HumanBodyBones)10); references.leftThigh = animator.GetBoneTransform((HumanBodyBones)1); references.leftCalf = animator.GetBoneTransform((HumanBodyBones)3); references.leftFoot = animator.GetBoneTransform((HumanBodyBones)5); references.rightThigh = animator.GetBoneTransform((HumanBodyBones)2); references.rightCalf = animator.GetBoneTransform((HumanBodyBones)4); references.rightFoot = animator.GetBoneTransform((HumanBodyBones)6); references.leftUpperArm = animator.GetBoneTransform((HumanBodyBones)13); references.leftForearm = animator.GetBoneTransform((HumanBodyBones)15); references.leftHand = animator.GetBoneTransform((HumanBodyBones)17); references.rightUpperArm = animator.GetBoneTransform((HumanBodyBones)14); references.rightForearm = animator.GetBoneTransform((HumanBodyBones)16); references.rightHand = animator.GetBoneTransform((HumanBodyBones)18); references.pelvis = animator.GetBoneTransform((HumanBodyBones)0); AddBoneToHierarchy(ref references.spine, animator.GetBoneTransform((HumanBodyBones)7)); AddBoneToHierarchy(ref references.spine, animator.GetBoneTransform((HumanBodyBones)8)); if ((Object)(object)references.leftUpperArm != (Object)null && !IsNeckBone(animator.GetBoneTransform((HumanBodyBones)9), references.leftUpperArm)) { AddBoneToHierarchy(ref references.spine, animator.GetBoneTransform((HumanBodyBones)9)); } if (autoDetectParams.includeEyes) { AddBoneToHierarchy(ref references.eyes, animator.GetBoneTransform((HumanBodyBones)21)); AddBoneToHierarchy(ref references.eyes, animator.GetBoneTransform((HumanBodyBones)22)); } } } public static bool SetupError(BipedReferences references, ref string errorMessage) { if (!references.isFilled) { errorMessage = "BipedReferences contains one or more missing Transforms."; return true; } if (LimbError(references.leftThigh, references.leftCalf, references.leftFoot, ref errorMessage)) { return true; } if (LimbError(references.rightThigh, references.rightCalf, references.rightFoot, ref errorMessage)) { return true; } if (LimbError(references.leftUpperArm, references.leftForearm, references.leftHand, ref errorMessage)) { return true; } if (LimbError(references.rightUpperArm, references.rightForearm, references.rightHand, ref errorMessage)) { return true; } if (SpineError(references, ref errorMessage)) { return true; } if (EyesError(references, ref errorMessage)) { return true; } return false; } public static bool SetupWarning(BipedReferences references, ref string warningMessage) { if (LimbWarning(references.leftThigh, references.leftCalf, references.leftFoot, ref warningMessage)) { return true; } if (LimbWarning(references.rightThigh, references.rightCalf, references.rightFoot, ref warningMessage)) { return true; } if (LimbWarning(references.leftUpperArm, references.leftForearm, references.leftHand, ref warningMessage)) { return true; } if (LimbWarning(references.rightUpperArm, references.rightForearm, references.rightHand, ref warningMessage)) { return true; } if (SpineWarning(references, ref warningMessage)) { return true; } if (EyesWarning(references, ref warningMessage)) { return true; } if (RootHeightWarning(references, ref warningMessage)) { return true; } if (FacingAxisWarning(references, ref warningMessage)) { return true; } return false; } private static bool IsNeckBone(Transform bone, Transform leftUpperArm) { if ((Object)(object)leftUpperArm.parent != (Object)null && (Object)(object)leftUpperArm.parent == (Object)(object)bone) { return false; } if (Hierarchy.IsAncestor(leftUpperArm, bone)) { return false; } return true; } private static bool AddBoneToEyes(Transform bone, ref BipedReferences references, AutoDetectParams autoDetectParams) { if ((Object)(object)references.head != (Object)null && !Hierarchy.IsAncestor(bone, references.head)) { return false; } if ((Object)(object)((Component)bone).GetComponent<SkinnedMeshRenderer>() != (Object)null) { return false; } return true; } private static bool AddBoneToSpine(Transform bone, ref BipedReferences references, AutoDetectParams autoDetectParams) { if ((Object)(object)bone == (Object)(object)references.root) { return false; } if ((Object)(object)bone == (Object)(object)references.leftThigh.parent && !autoDetectParams.legsParentInSpine) { return false; } if ((Object)(object)references.pelvis != (Object)null) { if ((Object)(object)bone == (Object)(object)references.pelvis) { return false; } if (Hierarchy.IsAncestor(references.pelvis, bone)) { return false; } } return true; } private static void DetectLimb(BipedNaming.BoneType boneType, BipedNaming.BoneSide boneSide, ref Transform firstBone, ref Transform secondBone, ref Transform lastBone, Transform[] transforms) { Transform[] bonesOfTypeAndSide = BipedNaming.GetBonesOfTypeAndSide(boneType, boneSide, transforms); if (bonesOfTypeAndSide.Length >= 3) { if (bonesOfTypeAndSide.Length == 3) { firstBone = bonesOfTypeAndSide[0]; secondBone = bonesOfTypeAndSide[1]; lastBone = bonesOfTypeAndSide[2]; } if (bonesOfTypeAndSide.Length > 3) { firstBone = bonesOfTypeAndSide[0]; secondBone = bonesOfTypeAndSide[2]; lastBone = bonesOfTypeAndSide[^1]; } } } private static void AddBoneToHierarchy(ref Transform[] bones, Transform transform) { if (!((Object)(object)transform == (Object)null)) { Array.Resize(ref bones, bones.Length + 1); bones[bones.Length - 1] = transform; } } private static bool LimbError(Transform bone1, Transform bone2, Transform bone3, ref string errorMessage) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)bone1 == (Object)null) { errorMessage = "Bone 1 of a BipedReferences limb is null."; return true; } if ((Object)(object)bone2 == (Object)null) { errorMessage = "Bone 2 of a BipedReferences limb is null."; return true; } if ((Object)(object)bone3 == (Object)null) { errorMessage = "Bone 3 of a BipedReferences limb is null."; return true; } Object[] objects = (Object[])(object)new Transform[3] { bone1, bone2, bone3 }; Transform val = (Transform)Hierarchy.ContainsDuplicate(objects); if ((Object)(object)val != (Object)null) { errorMessage = ((Object)val).name + " is represented multiple times in the same BipedReferences limb."; return true; } if (bone2.position == bone1.position) { errorMessage = "Second bone's position equals first bone's position in the biped's limb."; return true; } if (bone3.position == bone2.position) { errorMessage = "Third bone's position equals second bone's position in the biped's limb."; return true; } if (!Hierarchy.HierarchyIsValid((Transform[])(object)new Transform[3] { bone1, bone2, bone3 })) { errorMessage = "BipedReferences limb hierarchy is invalid. Bone transforms in a limb do not belong to the same ancestry. Please make sure the bones are parented to each other. Bones: " + ((Object)bone1).name + ", " + ((Object)bone2).name + ", " + ((Object)bone3).name; return true; } return false; } private static bool LimbWarning(Transform bone1, Transform bone2, Transform bone3, ref string warningMessage) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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) if (Vector3.Cross(bone2.position - bone1.position, bone3.position - bone1.position) == Vector3.zero) { warningMessage = "BipedReferences limb is completely stretched out in the initial pose. IK solver can not calculate the default bend plane for the limb. Please make sure you character's limbs are at least slightly bent in the initial pose. First bone: " + ((Object)bone1).name + ", second bone: " + ((Object)bone2).name + "."; return true; } return false; } private static bool SpineError(BipedReferences references, ref string errorMessage) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) if (references.spine.Length == 0) { return false; } for (int i = 0; i < references.spine.Length; i++) { if ((Object)(object)references.spine[i] == (Object)null) { errorMessage = "BipedReferences spine bone at index " + i + " is null."; return true; } } Object[] objects = (Object[])(object)references.spine; Transform val = (Transform)Hierarchy.ContainsDuplicate(objects); if ((Object)(object)val != (Object)null) { errorMessage = ((Object)val).name + " is represented multiple times in BipedReferences spine."; return true; } if (!Hierarchy.HierarchyIsValid(references.spine)) { errorMessage = "BipedReferences spine hierarchy is invalid. Bone transforms in the spine do not belong to the same ancestry. Please make sure the bones are parented to each other."; return true; } for (int j = 0; j < references.spine.Length; j++) { bool flag = false; if (j == 0 && references.spine[j].position == references.pelvis.position) { flag = true; } if (j != 0 && references.spine.Length > 1 && references.spine[j].position == references.spine[j - 1].position) { flag = true; } if (flag) { errorMessage = "Biped's spine bone nr " + j + " position is the same as it's parent spine/pelvis bone's position. Please remove this bone from the spine."; return true; } } return false; } private static bool SpineWarning(BipedReferences references, ref string warningMessage) { return false; } private static bool EyesError(BipedReferences references, ref string errorMessage) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown if (references.eyes.Length == 0) { return false; } for (int i = 0; i < references.eyes.Length; i++) { if ((Object)(object)references.eyes[i] == (Object)null) { errorMessage = "BipedReferences eye bone at index " + i + " is null."; return true; } } Object[] objects = (Object[])(object)references.eyes; Transform val = (Transform)Hierarchy.ContainsDuplicate(objects); if ((Object)(object)val != (Object)null) { errorMessage = ((Object)val).name + " is represented multiple times in BipedReferences eyes."; return true; } return false; } private static bool EyesWarning(BipedReferences references, ref string warningMessage) { return false; } private static bool RootHeightWarning(BipedReferences references, ref string warningMessage) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)references.head == (Object)null) { return false; } float verticalOffset = GetVerticalOffset(references.head.position, references.leftFoot.position, references.root.rotation); if (GetVerticalOffset(references.root.position, references.leftFoot.position, references.root.rotation) / verticalOffset > 0.2f) { warningMessage = "Biped's root Transform's position should be at ground level relative to the character (at the character's feet not at it's pelvis)."; return true; } return false; } private static bool FacingAxisWarning(BipedReferences references, ref string warningMessage) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0045: 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_005c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = references.rightHand.position - references.leftHand.position; Vector3 val2 = references.rightFoot.position - references.leftFoot.position; float num = Vector3.Dot(((Vector3)(ref val)).normalized, references.root.right); float num2 = Vector3.Dot(((Vector3)(ref val2)).normalized, references.root.right); if (num < 0f || num2 < 0f) { warningMessage = "Biped does not seem to be facing it's forward axis. Please make sure that in the initial pose the character is facing towards the positive Z axis of the Biped root gameobject."; return true; } return false; } private static float GetVerticalOffset(Vector3 p1, Vector3 p2, Quaternion rotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return (Quaternion.Inverse(rotation) * (p1 - p2)).y; } } public class Comments : MonoBehaviour { [Multiline] public string text; } public class DemoGUIMessage : MonoBehaviour { public string text; public Color color = Color.white; private void OnGUI() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) GUI.color = color; GUILayout.Label(text, Array.Empty<GUILayoutOption>()); GUI.color = Color.white; } } public class Hierarchy { public static bool HierarchyIsValid(Transform[] bones) { for (int i = 1; i < bones.Length; i++) { if (!IsAncestor(bones[i], bones[i - 1])) { return false; } } return true; } public static Object ContainsDuplicate(Object[] objects) { for (int i = 0; i < objects.Length; i++) { for (int j = 0; j < objects.Length; j++) { if (i != j && objects[i] == objects[j]) { return objects[i]; } } } return null; } public static bool IsAncestor(Transform transform, Transform ancestor) { if ((Object)(object)transform == (Object)null) { return true; } if ((Object)(object)ancestor == (Object)null) { return true; } if ((Object)(object)transform.parent == (Object)null) { return false; } if ((Object)(object)transform.parent == (Object)(object)ancestor) { return true; } return IsAncestor(transform.parent, ancestor); } public static bool ContainsChild(Transform transform, Transform child) { if ((Object)(object)transform == (Object)(object)child) { return true; } Transform[] componentsInChildren = ((Component)transform).GetComponentsInChildren<Transform>(); for (int i = 0; i < componentsInChildren.Length; i++) { if ((Object)(object)componentsInChildren[i] == (Object)(object)child) { return true; } } return false; } public static void AddAncestors(Transform transform, Transform blocker, ref Transform[] array) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)transform.parent != (Object)null && (Object)(object)transform.parent != (Object)(object)blocker) { if (transform.parent.position != transform.position && transform.parent.position != blocker.position) { Array.Resize(ref array, array.Length + 1); array[array.Length - 1] = transform.parent; } AddAncestors(transform.parent, blocker, ref array); } } public static Transform GetAncestor(Transform transform, int minChildCount) { if ((Object)(object)transform == (Object)null) { return null; } if ((Object)(object)transform.parent != (Object)null) { if (transform.parent.childCount >= minChildCount) { return transform.parent; } return GetAncestor(transform.parent, minChildCount); } return null; } public static Transform GetFirstCommonAncestor(Transform t1, Transform t2) { if ((Object)(object)t1 == (Object)null) { return null; } if ((Object)(object)t2 == (Object)null) { return null; } if ((Object)(object)t1.parent == (Object)null) { return null; } if ((Object)(object)t2.parent == (Object)null) { return null; } if (IsAncestor(t2, t1.parent)) { return t1.parent; } return GetFirstCommonAncestor(t1.parent, t2); } public static Transform GetFirstCommonAncestor(Transform[] transforms) { if (transforms == null) { Debug.LogWarning((object)"Transforms is null."); return null; } if (transforms.Length == 0) { Debug.LogWarning((object)"Transforms.Length is 0."); return null; } for (int i = 0; i < transforms.Length; i++) { if ((Object)(object)transforms[i] == (Object)null) { return null; } if (IsCommonAncestor(transforms[i], transforms)) { return transforms[i]; } } return GetFirstCommonAncestorRecursive(transforms[0], transforms); } public static Transform GetFirstCommonAncestorRecursive(Transform transform, Transform[] transforms) { if ((Object)(object)transform == (Object)null) { Debug.LogWarning((object)"Transform is null."); return null; } if (transforms == null) { Debug.LogWarning((object)"Transforms is null."); return null; } if (transforms.Length == 0) { Debug.LogWarning((object)"Transforms.Length is 0."); return null; } if (IsCommonAncestor(transform, transforms)) { return transform; } if ((Object)(object)transform.parent == (Object)null) { return null; } return GetFirstCommonAncestorRecursive(transform.parent, transforms); } public static bool IsCommonAncestor(Transform transform, Transform[] transforms) { if ((Object)(object)transform == (Object)null) { Debug.LogWarning((object)"Transform is null."); return false; } for (int i = 0; i < transforms.Length; i++) { if ((Object)(object)transforms[i] == (Object)null) { Debug.Log((object)("Transforms[" + i + "] is null.")); return false; } if (!IsAncestor(transforms[i], transform) && (Object)(object)transforms[i] != (Object)(object)transform) { return false; } } return true; } } public class InspectorComment : PropertyAttribute { public string name; public string color = "white"; public InspectorComment(string name) { this.name = name; color = "white"; } public InspectorComment(string name, string color) { this.name = name; this.color = color; } } [Serializable] public enum InterpolationMode { None, InOutCubic, InOutQuintic, InOutSine, InQuintic, InQuartic, InCubic, InQuadratic, InElastic, InElasticSmall, InElasticBig, InSine, InBack, OutQuintic, OutQuartic, OutCubic, OutInCubic, OutInQuartic, OutElastic, OutElasticSmall, OutElasticBig, OutSine, OutBack, OutBackCubic, OutBackQuartic, BackInCubic, BackInQuartic } public class Interp { public static float Float(float t, InterpolationMode mode) { float num = 0f; return mode switch { InterpolationMode.None => None(t, 0f, 1f), InterpolationMode.InOutCubic => InOutCubic(t, 0f, 1f), InterpolationMode.InOutQuintic => InOutQuintic(t, 0f, 1f), InterpolationMode.InQuintic => InQuintic(t, 0f, 1f), InterpolationMode.InQuartic => InQuartic(t, 0f, 1f), InterpolationMode.InCubic => InCubic(t, 0f, 1f), InterpolationMode.InQuadratic => InQuadratic(t, 0f, 1f), InterpolationMode.OutQuintic => OutQuintic(t, 0f, 1f), InterpolationMode.OutQuartic => OutQuartic(t, 0f, 1f), InterpolationMode.OutCubic => OutCubic(t, 0f, 1f), InterpolationMode.OutInCubic => OutInCubic(t, 0f, 1f), InterpolationMode.OutInQuartic => OutInCubic(t, 0f, 1f), InterpolationMode.BackInCubic => BackInCubic(t, 0f, 1f), InterpolationMode.BackInQuartic => BackInQuartic(t, 0f, 1f), InterpolationMode.OutBackCubic => OutBackCubic(t, 0f, 1f), InterpolationMode.OutBackQuartic => OutBackQuartic(t, 0f, 1f), InterpolationMode.OutElasticSmall => OutElasticSmall(t, 0f, 1f), InterpolationMode.OutElasticBig => OutElasticBig(t, 0f, 1f), InterpolationMode.InElasticSmall => InElasticSmall(t, 0f, 1f), InterpolationMode.InElasticBig => InElasticBig(t, 0f, 1f), InterpolationMode.InSine => InSine(t, 0f, 1f), InterpolationMode.OutSine => OutSine(t, 0f, 1f), InterpolationMode.InOutSine => InOutSine(t, 0f, 1f), InterpolationMode.InElastic => OutElastic(t, 0f, 1f), InterpolationMode.OutElastic => OutElastic(t, 0f, 1f), InterpolationMode.InBack => InBack(t, 0f, 1f), InterpolationMode.OutBack => OutBack(t, 0f, 1f), _ => 0f, }; } public static Vector3 V3(Vector3 v1, Vector3 v2, float t, InterpolationMode mode) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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) float num = Float(t, mode); return (1f - num) * v1 + num * v2; } public static float LerpValue(float value, float target, float increaseSpeed, float decreaseSpeed) { if (value == target) { return target; } if (value < target) { return Mathf.Clamp(value + Time.deltaTime * increaseSpeed, float.NegativeInfinity, target); } return Mathf.Clamp(value - Time.deltaTime * decreaseSpeed, target, float.PositiveInfinity); } private static float None(float t, float b, float c) { return b + c * t; } private static float InOutCubic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (-2f * num2 + 3f * num); } private static float InOutQuintic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (6f * num2 * num + -15f * num * num + 10f * num2); } private static float InQuintic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (num2 * num); } private static float InQuartic(float t, float b, float c) { float num = t * t; return b + c * (num * num); } private static float InCubic(float t, float b, float c) { float num = t * t * t; return b + c * num; } private static float InQuadratic(float t, float b, float c) { float num = t * t; return b + c * num; } private static float OutQuintic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (num2 * num + -5f * num * num + 10f * num2 + -10f * num + 5f * t); } private static float OutQuartic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (-1f * num * num + 4f * num2 + -6f * num + 4f * t); } private static float OutCubic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (num2 + -3f * num + 3f * t); } private static float OutInCubic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (4f * num2 + -6f * num + 3f * t); } private static float OutInQuartic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (6f * num2 + -9f * num + 4f * t); } private static float BackInCubic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (4f * num2 + -3f * num); } private static float BackInQuartic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (2f * num * num + 2f * num2 + -3f * num); } private static float OutBackCubic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (4f * num2 + -9f * num + 6f * t); } private static float OutBackQuartic(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (-2f * num * num + 10f * num2 + -15f * num + 8f * t); } private static float OutElasticSmall(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (33f * num2 * num + -106f * num * num + 126f * num2 + -67f * num + 15f * t); } private static float OutElasticBig(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (56f * num2 * num + -175f * num * num + 200f * num2 + -100f * num + 20f * t); } private static float InElasticSmall(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (33f * num2 * num + -59f * num * num + 32f * num2 + -5f * num); } private static float InElasticBig(float t, float b, float c) { float num = t * t; float num2 = num * t; return b + c * (56f * num2 * num + -105f * num * num + 60f * num2 + -10f * num); } private static float InSine(float t, float b, float c) { c -= b; return (0f - c) * Mathf.Cos(t / 1f * (MathF.PI / 2f)) + c + b; } private static float OutSine(float t, float b, float c) { c -= b; return c * Mathf.Sin(t / 1f * (MathF.PI / 2f)) + b; } private static float InOutSine(float t, float b, float c) { c -= b; return (0f - c) / 2f * (Mathf.Cos(MathF.PI * t / 1f) - 1f) + b; } private static float InElastic(float t, float b, float c) { c -= b; float num = 1f; float num2 = num * 0.3f; float num3 = 0f; float num4 = 0f; if (t == 0f) { return b; } if ((t /= num) == 1f) { return b + c; } if (num4 == 0f || num4 < Mathf.Abs(c)) { num4 = c; num3 = num2 / 4f; } else { num3 = num2 / (MathF.PI * 2f) * Mathf.Asin(c / num4); } return 0f - num4 * Mathf.Pow(2f, 10f * (t -= 1f)) * Mathf.Sin((t * num - num3) * (MathF.PI * 2f) / num2) + b; } private static float OutElastic(float t, float b, float c) { c -= b; float num = 1f; float num2 = num * 0.3f; float num3 = 0f; float num4 = 0f; if (t == 0f) { return b; } if ((t /= num) == 1f) { return b + c; } if (num4 == 0f || num4 < Mathf.Abs(c)) { num4 = c; num3 = num2 / 4f; } else { num3 = num2 / (MathF.PI * 2f) * Mathf.Asin(c / num4); } return num4 * Mathf.Pow(2f, -10f * t) * Mathf.Sin((t * num - num3) * (MathF.PI * 2f) / num2) + c + b; } private static float InBack(float t, float b, float c) { c -= b; t /= 1f; float num = 1.70158f; return c * t * t * ((num + 1f) * t - num) + b; } private static float OutBack(float t, float b, float c) { float num = 1.70158f; c -= b; t = t / 1f - 1f; return c * (t * t * ((num + 1f) * t + num) + 1f) + b; } } public class LargeHeader : PropertyAttribute { public string name; public string color = "white"; public LargeHeader(string name) { this.name = name; color = "white"; } public LargeHeader(string name, string color) { this.name = name; this.color = color; } } public static class LayerMaskExtensions { public static bool Contains(LayerMask mask, int layer) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return LayerMask.op_Implicit(mask) == (LayerMask.op_Implicit(mask) | (1 << layer)); } public static LayerMask Create(params string[] layerNames) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return NamesToMask(layerNames); } public static LayerMask Create(params int[] layerNumbers) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return LayerNumbersToMask(layerNumbers); } public static LayerMask NamesToMask(params string[] layerNames) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) LayerMask val = LayerMask.op_Implicit(0); foreach (string text in layerNames) { val = LayerMask.op_Implicit(LayerMask.op_Implicit(val) | (1 << LayerMask.NameToLayer(text))); } return val; } public static LayerMask LayerNumbersToMask(params int[] layerNumbers) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) LayerMask val = LayerMask.op_Implicit(0); foreach (int num in layerNumbers) { val = LayerMask.op_Implicit(LayerMask.op_Implicit(val) | (1 << num)); } return val; } public static LayerMask Inverse(this LayerMask original) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return LayerMask.op_Implicit(~LayerMask.op_Implicit(original)); } public static LayerMask AddToMask(this LayerMask original, params string[] layerNames) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) return LayerMask.op_Implicit(LayerMask.op_Implicit(original) | LayerMask.op_Implicit(NamesToMask(layerNames))); } public static LayerMask RemoveFromMask(this LayerMask original, params string[] layerNames) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) return LayerMask.op_Implicit(~(LayerMask.op_Implicit(LayerMask.op_Implicit(~LayerMask.op_Implicit(original))) | LayerMask.op_Implicit(NamesToMask(layerNames)))); } public static string[] MaskToNames(this LayerMask original) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) List<string> list = new List<string>(); for (int i = 0; i < 32; i++) { int num = 1 << i; if ((LayerMask.op_Implicit(original) & num) == num) { string text = LayerMask.LayerToName(i); if (!string.IsNullOrEmpty(text)) { list.Add(text); } } } return list.ToArray(); } public static int[] MaskToNumbers(this LayerMask original) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) List<int> list = new List<int>(); for (int i = 0; i < 32; i++) { int num = 1 << i; if ((LayerMask.op_Implicit(original) & num) == num) { list.Add(i); } } return list.ToArray(); } public static string MaskToString(this LayerMask original) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return original.MaskToString(", "); } public static string MaskToString(this LayerMask original, string delimiter) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return string.Join(delimiter, original.MaskToNames()); } } public static class QuaTools { public static float GetYaw(Quaternion space, Vector3 forward) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Quaternion.Inverse(space) * forward; return Mathf.Atan2(val.x, val.z) * 57.29578f; } public static float GetPitch(Quaternion space, Vector3 forward) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) forward = ((Vector3)(ref forward)).normalized; return (0f - Mathf.Asin((Quaternion.Inverse(space) * forward).y)) * 57.29578f; } public static float GetBank(Quaternion space, Vector3 forward, Vector3 up) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) Vector3 val = space * Vector3.up; Quaternion val2 = Quaternion.Inverse(space); forward = val2 * forward; up = val2 * up; up = Quaternion.Inverse(Quaternion.LookRotation(val, forward)) * up; return Mathf.Atan2(up.x, up.z) * 57.29578f; } public static float GetYaw(Quaternion space, Quaternion rotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Quaternion.Inverse(space) * (rotation * Vector3.forward); return Mathf.Atan2(val.x, val.z) * 57.29578f; } public static float GetPitch(Quaternion space, Quaternion rotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (0f - Mathf.Asin((Quaternion.Inverse(space) * (rotation * Vector3.forward)).y)) * 57.29578f; } public static float GetBank(Quaternion space, Quaternion rotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = space * Vector3.up; Quaternion val2 = Quaternion.Inverse(space); Vector3 val3 = val2 * (rotation * Vector3.forward); Vector3 val4 = val2 * (rotation * Vector3.up); val4 = Quaternion.Inverse(Quaternion.LookRotation(val, val3)) * val4; return Mathf.Atan2(val4.x, val4.z) * 57.29578f; } public static Quaternion Lerp(Quaternion fromRotation, Quaternion toRotation, float weight) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return fromRotation; } if (weight >= 1f) { return toRotation; } return Quaternion.Lerp(fromRotation, toRotation, weight); } public static Quaternion Slerp(Quaternion fromRotation, Quaternion toRotation, float weight) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return fromRotation; } if (weight >= 1f) { return toRotation; } return Quaternion.Slerp(fromRotation, toRotation, weight); } public static Quaternion LinearBlend(Quaternion q, float weight) { //IL_0008: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return Quaternion.identity; } if (weight >= 1f) { return q; } return Quaternion.Lerp(Quaternion.identity, q, weight); } public static Quaternion SphericalBlend(Quaternion q, float weight) { //IL_0008: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return Quaternion.identity; } if (weight >= 1f) { return q; } return Quaternion.Slerp(Quaternion.identity, q, weight); } public static Quaternion FromToAroundAxis(Vector3 fromDirection, Vector3 toDirection, Vector3 axis) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.FromToRotation(fromDirection, toDirection); float num = 0f; Vector3 zero = Vector3.zero; ((Quaternion)(ref val)).ToAngleAxis(ref num, ref zero); if (Vector3.Dot(zero, axis) < 0f) { num = 0f - num; } return Quaternion.AngleAxis(num, axis); } public static Quaternion RotationToLocalSpace(Quaternion space, Quaternion rotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Inverse(Quaternion.Inverse(space) * rotation); } public static Quaternion FromToRotation(Quaternion from, Quaternion to) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (to == from) { return Quaternion.identity; } return to * Quaternion.Inverse(from); } public static Vector3 GetAxis(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Vector3.right; bool flag = false; float num = Vector3.Dot(v, Vector3.right); float num2 = Mathf.Abs(num); if (num < 0f) { flag = true; } float num3 = Vector3.Dot(v, Vector3.up); float num4 = Mathf.Abs(num3); if (num4 > num2) { num2 = num4; val = Vector3.up; flag = num3 < 0f; } float num5 = Vector3.Dot(v, Vector3.forward); num4 = Mathf.Abs(num5); if (num4 > num2) { val = Vector3.forward; flag = num5 < 0f; } if (flag) { val = -val; } return val; } public static Quaternion ClampRotation(Quaternion rotation, float clampWeight, int clampSmoothing) { //IL_0008: 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_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) if (clampWeight >= 1f) { return Quaternion.identity; } if (clampWeight <= 0f) { return rotation; } float num = Quaternion.Angle(Quaternion.identity, rotation); float num2 = 1f - num / 180f; float num3 = Mathf.Clamp(1f - (clampWeight - num2) / (1f - num2), 0f, 1f); float num4 = Mathf.Clamp(num2 / clampWeight, 0f, 1f); for (int i = 0; i < clampSmoothing; i++) { num4 = Mathf.Sin(num4 * MathF.PI * 0.5f); } return Quaternion.Slerp(Quaternion.identity, rotation, num4 * num3); } public static float ClampAngle(float angle, float clampWeight, int clampSmoothing) { if (clampWeight >= 1f) { return 0f; } if (clampWeight <= 0f) { return angle; } float num = 1f - Mathf.Abs(angle) / 180f; float num2 = Mathf.Clamp(1f - (clampWeight - num) / (1f - num), 0f, 1f); float num3 = Mathf.Clamp(num / clampWeight, 0f, 1f); for (int i = 0; i < clampSmoothing; i++) { num3 = Mathf.Sin(num3 * MathF.PI * 0.5f); } return Mathf.Lerp(0f, angle, num3 * num2); } public static Quaternion MatchRotation(Quaternion targetRotation, Vector3 targetforwardAxis, Vector3 targetUpAxis, Vector3 forwardAxis, Vector3 upAxis) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001e: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.LookRotation(forwardAxis, upAxis); Quaternion val2 = Quaternion.LookRotation(targetforwardAxis, targetUpAxis); return targetRotation * val2 * Quaternion.Inverse(val); } public static Vector3 ToBiPolar(Vector3 euler) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) return new Vector3(ToBiPolar(euler.x), ToBiPolar(euler.y), ToBiPolar(euler.z)); } public static float ToBiPolar(float angle) { angle %= 360f; if (angle >= 180f) { return angle - 360f; } if (angle <= -180f) { return angle + 360f; } return angle; } } public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T> { private static T sInstance; public static T instance => sInstance; protected virtual void Awake() { if ((Object)(object)sInstance != (Object)null) { Debug.LogError((object)(((Object)this).name + "error: already initialized"), (Object)(object)this); } sInstance = (T)this; } } public class SolverManager : MonoBehaviour { [Tooltip("If true, will fix all the Transforms used by the solver to their initial state in each Update. This prevents potential problems with unanimated bones and animator culling with a small cost of performance. Not recommended for CCD and FABRIK solvers.")] public bool fixTransforms = true; private Animator animator; private Animation legacy; private bool updateFrame; private bool componentInitiated; private bool skipSolverUpdate; private bool animatePhysics { get { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 if ((Object)(object)animator != (Object)null) { return (int)animator.updateMode == 1; } if ((Object)(object)legacy != (Object)null) { return legacy.animatePhysics; } return false; } } private bool isAnimated { get { if (!((Object)(object)animator != (Object)null)) { return (Object)(object)legacy != (Object)null; } return true; } } public void Disable() { Debug.Log((object)"IK.Disable() is deprecated. Use enabled = false instead", (Object)(object)((Component)this).transform); ((Behaviour)this).enabled = false; } protected virtual void InitiateSolver() { } protected virtual void UpdateSolver() { } protected virtual void FixTransforms() { } private void OnDisable() { if (Application.isPlaying) { Initiate(); } } private void Start() { Initiate(); } private void Initiate() { if (!componentInitiated) { FindAnimatorRecursive(((Component)this).transform, findInChildren: true); InitiateSolver(); componentInitiated = true; } } private void Update() { if (!skipSolverUpdate && !animatePhysics && fixTransforms) { FixTransforms(); } } private void FindAnimatorRecursive(Transform t, bool findInChildren) { if (isAnimated) { return; } animator = ((Component)t).GetComponent<Animator>(); legacy = ((Component)t).GetComponent<Animation>(); if (!isAnimated) { if ((Object)(object)animator == (Object)null && findInChildren) { animator = ((Component)t).GetComponentInChildren<Animator>(); } if ((Object)(object)legacy == (Object)null && findInChildren) { legacy = ((Component)t).GetComponentInChildren<Animation>(); } if (!isAnimated && (Object)(object)t.parent != (Object)null) { FindAnimatorRecursive(t.parent, findInChildren: false); } } } private void FixedUpdate() { if (skipSolverUpdate) { skipSolverUpdate = false; } updateFrame = true; if (animatePhysics && fixTransforms) { FixTransforms(); } } private void LateUpdate() { if (!skipSolverUpdate) { if (!animatePhysics) { updateFrame = true; } if (updateFrame) { updateFrame = false; UpdateSolver(); } } } public void UpdateSolverExternal() { if (((Behaviour)this).enabled) { skipSolverUpdate = true; UpdateSolver(); } } } public class TriggerEventBroadcaster : MonoBehaviour { public GameObject target; private void OnTriggerEnter(Collider collider) { if ((Object)(object)target != (Object)null) { target.SendMessage("OnTriggerEnter", (object)collider, (SendMessageOptions)1); } } private void OnTriggerStay(Collider collider) { if ((Object)(object)target != (Object)null) { target.SendMessage("OnTriggerStay", (object)collider, (SendMessageOptions)1); } } private void OnTriggerExit(Collider collider) { if ((Object)(object)target != (Object)null) { target.SendMessage("OnTriggerExit", (object)collider, (SendMessageOptions)1); } } } public static class V2Tools { public static Vector2 XZ(Vector3 v) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector2(v.x, v.z); } public static float DeltaAngle(Vector2 dir1, Vector2 dir2) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Atan2(dir1.x, dir1.y) * 57.29578f; float num2 = Mathf.Atan2(dir2.x, dir2.y) * 57.29578f; return Mathf.DeltaAngle(num, num2); } public static float DeltaAngleXZ(Vector3 dir1, Vector3 dir2) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Atan2(dir1.x, dir1.z) * 57.29578f; float num2 = Mathf.Atan2(dir2.x, dir2.z) * 57.29578f; return Mathf.DeltaAngle(num, num2); } public static bool LineCircleIntersect(Vector2 p1, Vector2 p2, Vector2 c, float r) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0026: 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) Vector2 val = p2 - p1; Vector2 val2 = c - p1; float num = Vector2.Dot(val, val); float num2 = 2f * Vector2.Dot(val2, val); float num3 = Vector2.Dot(val2, val2) - r * r; float num4 = num2 * num2 - 4f * num * num3; if (num4 < 0f) { return false; } num4 = Mathf.Sqrt(num4); float num5 = 2f * num; float num6 = (num2 - num4) / num5; float num7 = (num2 + num4) / num5; if (num6 >= 0f && num6 <= 1f) { return true; } if (num7 >= 0f && num7 <= 1f) { return true; } return false; } public static bool RayCircleIntersect(Vector2 p1, Vector2 dir, Vector2 c, float r) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) Vector2 val = p1 + dir; p1 -= c; val -= c; float num = val.x - p1.x; float num2 = val.y - p1.y; float num3 = Mathf.Sqrt(Mathf.Pow(num, 2f) + Mathf.Pow(num2, 2f)); float num4 = p1.x * val.y - val.x * p1.y; return Mathf.Pow(r, 2f) * Mathf.Pow(num3, 2f) - Mathf.Pow(num4, 2f) >= 0f; } } public static class V3Tools { public static float GetYaw(Vector3 forward) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return Mathf.Atan2(forward.x, forward.z) * 57.29578f; } public static float GetPitch(Vector3 forward) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) forward = ((Vector3)(ref forward)).normalized; return (0f - Mathf.Asin(forward.y)) * 57.29578f; } public static float GetBank(Vector3 forward, Vector3 up) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_001e: Unknown result type (might be due to invalid IL or missing references) up = Quaternion.Inverse(Quaternion.LookRotation(Vector3.up, forward)) * up; return Mathf.Atan2(up.x, up.z) * 57.29578f; } public static float GetYaw(Vector3 spaceForward, Vector3 spaceUp, Vector3 forward) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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) Vector3 val = Quaternion.Inverse(Quaternion.LookRotation(spaceForward, spaceUp)) * forward; return Mathf.Atan2(val.x, val.z) * 57.29578f; } public static float GetPitch(Vector3 spaceForward, Vector3 spaceUp, Vector3 forward) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return (0f - Mathf.Asin((Quaternion.Inverse(Quaternion.LookRotation(spaceForward, spaceUp)) * forward).y)) * 57.29578f; } public static float GetBank(Vector3 spaceForward, Vector3 spaceUp, Vector3 forward, Vector3 up) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.Inverse(Quaternion.LookRotation(spaceForward, spaceUp)); forward = val * forward; up = val * up; up = Quaternion.Inverse(Quaternion.LookRotation(spaceUp, forward)) * up; return Mathf.Atan2(up.x, up.z) * 57.29578f; } public static Vector3 Lerp(Vector3 fromVector, Vector3 toVector, float weight) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return fromVector; } if (weight >= 1f) { return toVector; } return Vector3.Lerp(fromVector, toVector, weight); } public static Vector3 Slerp(Vector3 fromVector, Vector3 toVector, float weight) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (weight <= 0f) { return fromVector; } if (weight >= 1f) { return toVector; } return Vector3.Slerp(fromVector, toVector, weight); } public static Vector3 ExtractVertical(Vector3 v, Vector3 verticalAxis, float weight) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (weight == 0f) { return Vector3.zero; } return Vector3.Project(v, verticalAxis) * weight; } public static Vector3 ExtractHorizontal(Vector3 v, Vector3 normal, float weight) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (weight == 0f) { return Vector3.zero; } Vector3 val = v; Vector3.OrthoNormalize(ref normal, ref val); return Vector3.Project(v, val) * weight; } public static Vector3 ClampDirection(Vector3 direction, Vector3 normalDirection, float clampWeight, int clampSmoothing) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if (clampWeight <= 0f) { return direction; } if (clampWeight >= 1f) { return normalDirection; } float num = Vector3.Angle(normalDirection, direction); float num2 = 1f - num / 180f; if (num2 > clampWeight) { return direction; } float num3 = ((clampWeight > 0f) ? Mathf.Clamp(1f - (clampWeight - num2) / (1f - num2), 0f, 1f) : 1f); float num4 = ((clampWeight > 0f) ? Mathf.Clamp(num2 / clampWeight, 0f, 1f) : 1f); for (int i = 0; i < clampSmoothing; i++) { num4 = Mathf.Sin(num4 * MathF.PI * 0.5f); } return Vector3.Slerp(normalDirection, direction, num4 * num3); } public static Vector3 ClampDirection(Vector3 direction, Vector3 normalDirection, float clampWeight, int clampSmoothing, out bool changed) { //IL_000c: 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) //IL_001d: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) changed = false; if (clampWeight <= 0f) { return direction; } if (clampWeight >= 1f) { changed = true; return normalDirection; } float num = Vector3.Angle(normalDirection, direction); float num2 = 1f - num / 180f; if (num2 > clampWeight) { return direction; } changed = true; float num3 = ((clampWeight > 0f) ? Mathf.Clamp(1f - (clampWeight - num2) / (1f - num2), 0f, 1f) : 1f); float num4 = ((clampWeight > 0f) ? Mathf.Clamp(num2 / clampWeight, 0f, 1f) : 1f); for (int i = 0; i < clampSmoothing; i++) { num4 = Mathf.Sin(num4 * MathF.PI * 0.5f); } return Vector3.Slerp(normalDirection, direction, num4 * num3); } public static Vector3 ClampDirection(Vector3 direction, Vector3 normalDirection, float clampWeight, int clampSmoothing, out float clampValue) { //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) //IL_001d: Unknown result type
plugins/Valheim_Data/Managed/SteamVR.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Unity.XR.OpenVR; using UnityEngine; using UnityEngine.AI; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityEngine.Serialization; using UnityEngine.SpatialTracking; using UnityEngine.UI; using UnityEngine.XR; using Valve.Newtonsoft.Json; using Valve.VR; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] [ExecuteInEditMode] public class URPMaterialSwitcher : MonoBehaviour { public bool children; } public static class SteamVR_Utils { public class Event { public delegate void Handler(params object[] args); private static Hashtable listeners = new Hashtable(); public static void Listen(string message, Handler action) { if (listeners[message] is Handler a) { listeners[message] = (Handler)Delegate.Combine(a, action); } else { listeners[message] = action; } } public static void Remove(string message, Handler action) { if (listeners[message] is Handler source) { listeners[message] = (Handler)Delegate.Remove(source, action); } } public static void Send(string message, params object[] args) { if (listeners[message] is Handler handler) { handler(args); } } } [Serializable] public struct RigidTransform { public Vector3 pos; public Quaternion rot; public static RigidTransform identity => new RigidTransform(Vector3.zero, Quaternion.identity); public static RigidTransform FromLocal(Transform t) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) return new RigidTransform(t.localPosition, t.localRotation); } public RigidTransform(Vector3 pos, Quaternion rot) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) this.pos = pos; this.rot = rot; } public RigidTransform(Transform t) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) pos = t.position; rot = t.rotation; } public RigidTransform(Transform from, Transform to) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Quaternion val = Quaternion.Inverse(from.rotation); rot = val * to.rotation; pos = val * (to.position - from.position); } public RigidTransform(HmdMatrix34_t pose) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 matrix = Matrix4x4.identity; ((Matrix4x4)(ref matrix))[0, 0] = pose.m0; ((Matrix4x4)(ref matrix))[0, 1] = pose.m1; ((Matrix4x4)(ref matrix))[0, 2] = 0f - pose.m2; ((Matrix4x4)(ref matrix))[0, 3] = pose.m3; ((Matrix4x4)(ref matrix))[1, 0] = pose.m4; ((Matrix4x4)(ref matrix))[1, 1] = pose.m5; ((Matrix4x4)(ref matrix))[1, 2] = 0f - pose.m6; ((Matrix4x4)(ref matrix))[1, 3] = pose.m7; ((Matrix4x4)(ref matrix))[2, 0] = 0f - pose.m8; ((Matrix4x4)(ref matrix))[2, 1] = 0f - pose.m9; ((Matrix4x4)(ref matrix))[2, 2] = pose.m10; ((Matrix4x4)(ref matrix))[2, 3] = 0f - pose.m11; pos = matrix.GetPosition(); rot = matrix.GetRotation(); } public RigidTransform(HmdMatrix44_t pose) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 matrix = Matrix4x4.identity; ((Matrix4x4)(ref matrix))[0, 0] = pose.m0; ((Matrix4x4)(ref matrix))[0, 1] = pose.m1; ((Matrix4x4)(ref matrix))[0, 2] = 0f - pose.m2; ((Matrix4x4)(ref matrix))[0, 3] = pose.m3; ((Matrix4x4)(ref matrix))[1, 0] = pose.m4; ((Matrix4x4)(ref matrix))[1, 1] = pose.m5; ((Matrix4x4)(ref matrix))[1, 2] = 0f - pose.m6; ((Matrix4x4)(ref matrix))[1, 3] = pose.m7; ((Matrix4x4)(ref matrix))[2, 0] = 0f - pose.m8; ((Matrix4x4)(ref matrix))[2, 1] = 0f - pose.m9; ((Matrix4x4)(ref matrix))[2, 2] = pose.m10; ((Matrix4x4)(ref matrix))[2, 3] = 0f - pose.m11; ((Matrix4x4)(ref matrix))[3, 0] = pose.m12; ((Matrix4x4)(ref matrix))[3, 1] = pose.m13; ((Matrix4x4)(ref matrix))[3, 2] = 0f - pose.m14; ((Matrix4x4)(ref matrix))[3, 3] = pose.m15; pos = matrix.GetPosition(); rot = matrix.GetRotation(); } public HmdMatrix44_t ToHmdMatrix44() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_0125: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 val = Matrix4x4.TRS(pos, rot, Vector3.one); HmdMatrix44_t result = default(HmdMatrix44_t); result.m0 = ((Matrix4x4)(ref val))[0, 0]; result.m1 = ((Matrix4x4)(ref val))[0, 1]; result.m2 = 0f - ((Matrix4x4)(ref val))[0, 2]; result.m3 = ((Matrix4x4)(ref val))[0, 3]; result.m4 = ((Matrix4x4)(ref val))[1, 0]; result.m5 = ((Matrix4x4)(ref val))[1, 1]; result.m6 = 0f - ((Matrix4x4)(ref val))[1, 2]; result.m7 = ((Matrix4x4)(ref val))[1, 3]; result.m8 = 0f - ((Matrix4x4)(ref val))[2, 0]; result.m9 = 0f - ((Matrix4x4)(ref val))[2, 1]; result.m10 = ((Matrix4x4)(ref val))[2, 2]; result.m11 = 0f - ((Matrix4x4)(ref val))[2, 3]; result.m12 = ((Matrix4x4)(ref val))[3, 0]; result.m13 = ((Matrix4x4)(ref val))[3, 1]; result.m14 = 0f - ((Matrix4x4)(ref val))[3, 2]; result.m15 = ((Matrix4x4)(ref val))[3, 3]; return result; } public HmdMatrix34_t ToHmdMatrix34() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_00e4: Unknown result type (might be due to invalid IL or missing references) Matrix4x4 val = Matrix4x4.TRS(pos, rot, Vector3.one); HmdMatrix34_t result = default(HmdMatrix34_t); result.m0 = ((Matrix4x4)(ref val))[0, 0]; result.m1 = ((Matrix4x4)(ref val))[0, 1]; result.m2 = 0f - ((Matrix4x4)(ref val))[0, 2]; result.m3 = ((Matrix4x4)(ref val))[0, 3]; result.m4 = ((Matrix4x4)(ref val))[1, 0]; result.m5 = ((Matrix4x4)(ref val))[1, 1]; result.m6 = 0f - ((Matrix4x4)(ref val))[1, 2]; result.m7 = ((Matrix4x4)(ref val))[1, 3]; result.m8 = 0f - ((Matrix4x4)(ref val))[2, 0]; result.m9 = 0f - ((Matrix4x4)(ref val))[2, 1]; result.m10 = ((Matrix4x4)(ref val))[2, 2]; result.m11 = 0f - ((Matrix4x4)(ref val))[2, 3]; return result; } public override bool Equals(object o) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (o is RigidTransform rigidTransform) { if (pos == rigidTransform.pos) { return rot == rigidTransform.rot; } return false; } return false; } public override int GetHashCode() { return ((object)(Vector3)(ref pos)).GetHashCode() ^ ((object)(Quaternion)(ref rot)).GetHashCode(); } public static bool operator ==(RigidTransform a, RigidTransform b) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (a.pos == b.pos) { return a.rot == b.rot; } return false; } public static bool operator !=(RigidTransform a, RigidTransform b) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (!(a.pos != b.pos)) { return a.rot != b.rot; } return true; } public static RigidTransform operator *(RigidTransform a, RigidTransform b) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) RigidTransform result = default(RigidTransform); result.rot = a.rot * b.rot; result.pos = a.pos + a.rot * b.pos; return result; } public void Inverse() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) rot = Quaternion.Inverse(rot); pos = -(rot * pos); } public RigidTransform GetInverse() { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) RigidTransform result = new RigidTransform(pos, rot); result.Inverse(); return result; } public void Multiply(RigidTransform a, RigidTransform b) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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) rot = a.rot * b.rot; pos = a.pos + a.rot * b.pos; } public Vector3 InverseTransformPoint(Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Inverse(rot) * (point - pos); } public Vector3 TransformPoint(Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) return pos + rot * point; } public static Vector3 operator *(RigidTransform t, Vector3 v) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) return t.TransformPoint(v); } public static RigidTransform Interpolate(RigidTransform a, RigidTransform b, float t) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) return new RigidTransform(Vector3.Lerp(a.pos, b.pos, t), Quaternion.Slerp(a.rot, b.rot, t)); } public void Interpolate(RigidTransform to, float t) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) pos = Lerp(pos, to.pos, t); rot = Slerp(rot, to.rot, t); } } public delegate object SystemFn(CVRSystem system, params object[] args); private const string secretKey = "foobar"; public static bool IsValid(Vector3 vector) { //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) if (!float.IsNaN(vector.x) && !float.IsNaN(vector.y)) { return !float.IsNaN(vector.z); } return false; } public static bool IsValid(Quaternion rotation) { //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_0041: 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_005b: Unknown result type (might be due to invalid IL or missing references) if (!float.IsNaN(rotation.x) && !float.IsNaN(rotation.y) && !float.IsNaN(rotation.z) && !float.IsNaN(rotation.w)) { if (rotation.x == 0f && rotation.y == 0f && rotation.z == 0f) { return rotation.w != 0f; } return true; } return false; } public static Quaternion Slerp(Quaternion A, Quaternion B, float t) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Clamp(A.x * B.x + A.y * B.y + A.z * B.z + A.w * B.w, -1f, 1f); if (num < 0f) { ((Quaternion)(ref B))..ctor(0f - B.x, 0f - B.y, 0f - B.z, 0f - B.w); num = 0f - num; } float num4; float num5; if (1f - num > 0.0001f) { float num2 = Mathf.Acos(num); float num3 = Mathf.Sin(num2); num4 = Mathf.Sin((1f - t) * num2) / num3; num5 = Mathf.Sin(t * num2) / num3; } else { num4 = 1f - t; num5 = t; } return new Quaternion(num4 * A.x + num5 * B.x, num4 * A.y + num5 * B.y, num4 * A.z + num5 * B.z, num4 * A.w + num5 * B.w); } public static Vector3 Lerp(Vector3 A, Vector3 B, float t) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) return new Vector3(Lerp(A.x, B.x, t), Lerp(A.y, B.y, t), Lerp(A.z, B.z, t)); } public static float Lerp(float A, float B, float t) { return A + (B - A) * t; } public static double Lerp(double A, double B, double t) { return A + (B - A) * t; } public static float InverseLerp(Vector3 A, Vector3 B, Vector3 result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) return Vector3.Dot(result - A, B - A); } public static float InverseLerp(float A, float B, float result) { return (result - A) / (B - A); } public static double InverseLerp(double A, double B, double result) { return (result - A) / (B - A); } public static float Saturate(float A) { if (!(A < 0f)) { if (!(A > 1f)) { return A; } return 1f; } return 0f; } public static Vector2 Saturate(Vector2 A) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) return new Vector2(Saturate(A.x), Saturate(A.y)); } public static float Abs(float A) { if (!(A < 0f)) { return A; } return 0f - A; } public static Vector2 Abs(Vector2 A) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) return new Vector2(Abs(A.x), Abs(A.y)); } private static float _copysign(float sizeval, float signval) { if (Mathf.Sign(signval) != 1f) { return 0f - Mathf.Abs(sizeval); } return Mathf.Abs(sizeval); } public static Quaternion GetRotation(this Matrix4x4 matrix) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) Quaternion val = default(Quaternion); val.w = Mathf.Sqrt(Mathf.Max(0f, 1f + matrix.m00 + matrix.m11 + matrix.m22)) / 2f; val.x = Mathf.Sqrt(Mathf.Max(0f, 1f + matrix.m00 - matrix.m11 - matrix.m22)) / 2f; val.y = Mathf.Sqrt(Mathf.Max(0f, 1f - matrix.m00 + matrix.m11 - matrix.m22)) / 2f; val.z = Mathf.Sqrt(Mathf.Max(0f, 1f - matrix.m00 - matrix.m11 + matrix.m22)) / 2f; val.x = _copysign(val.x, matrix.m21 - matrix.m12); val.y = _copysign(val.y, matrix.m02 - matrix.m20); val.z = _copysign(val.z, matrix.m10 - matrix.m01); return val; } public static Vector3 GetPosition(this Matrix4x4 matrix) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) float m = matrix.m03; float m2 = matrix.m13; float m3 = matrix.m23; return new Vector3(m, m2, m3); } public static Vector3 GetScale(this Matrix4x4 m) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002e: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) float num = Mathf.Sqrt(m.m00 * m.m00 + m.m01 * m.m01 + m.m02 * m.m02); float num2 = Mathf.Sqrt(m.m10 * m.m10 + m.m11 * m.m11 + m.m12 * m.m12); float num3 = Mathf.Sqrt(m.m20 * m.m20 + m.m21 * m.m21 + m.m22 * m.m22); return new Vector3(num, num2, num3); } public static float GetLossyScale(Transform t) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return t.lossyScale.x; } public static string GetBadMD5Hash(string usedString) { return GetBadMD5Hash(Encoding.UTF8.GetBytes(usedString + "foobar")); } public static string GetBadMD5Hash(byte[] bytes) { byte[] array = new MD5CryptoServiceProvider().ComputeHash(bytes); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("x2")); } return stringBuilder.ToString(); } public static string GetBadMD5HashFromFile(string filePath) { if (!File.Exists(filePath)) { return null; } return GetBadMD5Hash(File.ReadAllText(filePath) + "foobar"); } public static string SanitizePath(string path, bool allowLeadingSlash = true) { if (path.Contains("\\\\")) { path = path.Replace("\\\\", "\\"); } if (path.Contains("//")) { path = path.Replace("//", "/"); } if (!allowLeadingSlash && (path[0] == '/' || path[0] == '\\')) { path = path.Substring(1); } return path; } public static Type FindType(string typeName) { Type type = Type.GetType(typeName); if (type != null) { return type; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { type = assemblies[i].GetType(typeName); if (type != null) { return type; } } return null; } public static object CallSystemFn(SystemFn fn, params object[] args) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) bool flag = !SteamVR.active && !SteamVR.usingNativeSupport; if (flag) { EVRInitError val = (EVRInitError)0; OpenVR.Init(ref val, (EVRApplicationType)4, ""); } CVRSystem system = OpenVR.System; object result = ((system != null) ? fn(system, args) : null); if (flag) { OpenVR.Shutdown(); } return result; } public static void TakeStereoScreenshot(uint screenshotHandle, GameObject target, int cellSize, float ipd, ref string previewFilename, ref string VRFilename) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_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_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Expected O, but got Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0523: Unknown result type (might be due to invalid IL or missing references) //IL_059d: Unknown result type (might be due to invalid IL or missing references) //IL_05aa: Unknown result type (might be due to invalid IL or missing references) //IL_05b7: Unknown result type (might be due to invalid IL or missing references) //IL_04e6: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_029e: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: 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_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_036e: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0388: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_03a7: Unknown result type (might be due to invalid IL or missing references) //IL_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03be: Unknown result type (might be due to invalid IL or missing references) //IL_03c0: Unknown result type (might be due to invalid IL or missing references) //IL_03c2: Unknown result type (might be due to invalid IL or missing references) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03ce: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03d2: Unknown result type (might be due to invalid IL or missing references) //IL_03d4: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03e2: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_03fa: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0432: Unknown result type (might be due to invalid IL or missing references) //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_0438: Unknown result type (might be due to invalid IL or missing references) //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0441: Unknown result type (might be due to invalid IL or missing references) //IL_044b: 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_0451: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_048f: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(4096, 4096, (TextureFormat)5, false); Stopwatch stopwatch = new Stopwatch(); Camera val2 = null; stopwatch.Start(); Camera val3 = target.GetComponent<Camera>(); if ((Object)(object)val3 == (Object)null) { if ((Object)(object)val2 == (Object)null) { val2 = new GameObject().AddComponent<Camera>(); } val3 = val2; } Texture2D val4 = new Texture2D(2048, 2048, (TextureFormat)5, false); RenderTexture val5 = new RenderTexture(2048, 2048, 24); RenderTexture targetTexture = val3.targetTexture; bool orthographic = val3.orthographic; float fieldOfView = val3.fieldOfView; float aspect = val3.aspect; StereoTargetEyeMask stereoTargetEye = val3.stereoTargetEye; val3.stereoTargetEye = (StereoTargetEyeMask)0; val3.fieldOfView = 60f; val3.orthographic = false; val3.targetTexture = val5; val3.aspect = 1f; val3.Render(); RenderTexture.active = val5; val4.ReadPixels(new Rect(0f, 0f, (float)((Texture)val5).width, (float)((Texture)val5).height), 0, 0); RenderTexture.active = null; val3.targetTexture = null; Object.DestroyImmediate((Object)(object)val5); SteamVR_SphericalProjection steamVR_SphericalProjection = ((Component)val3).gameObject.AddComponent<SteamVR_SphericalProjection>(); Vector3 localPosition = target.transform.localPosition; Quaternion localRotation = target.transform.localRotation; Vector3 position = target.transform.position; Quaternion rotation = target.transform.rotation; Quaternion val6 = Quaternion.Euler(0f, ((Quaternion)(ref rotation)).eulerAngles.y, 0f); Transform transform = ((Component)val3).transform; int num = 1024 / cellSize; float num2 = 90f / (float)num; float num3 = num2 / 2f; RenderTexture val7 = new RenderTexture(cellSize, cellSize, 24); ((Texture)val7).wrapMode = (TextureWrapMode)1; val7.antiAliasing = 8; val3.fieldOfView = num2; val3.orthographic = false; val3.targetTexture = val7; val3.aspect = aspect; val3.stereoTargetEye = (StereoTargetEyeMask)0; for (int i = 0; i < num; i++) { float num4 = 90f - (float)i * num2 - num3; int num5 = 4096 / ((Texture)val7).width; float num6 = 360f / (float)num5; float num7 = num6 / 2f; int num8 = i * 1024 / num; for (int j = 0; j < 2; j++) { if (j == 1) { num4 = 0f - num4; num8 = 2048 - num8 - cellSize; } for (int k = 0; k < num5; k++) { float num9 = -180f + (float)k * num6 + num7; int num10 = k * 4096 / num5; int num11 = 0; float num12 = (0f - ipd) / 2f * Mathf.Cos(num4 * (MathF.PI / 180f)); for (int l = 0; l < 2; l++) { if (l == 1) { num11 = 2048; num12 = 0f - num12; } Vector3 val8 = val6 * Quaternion.Euler(0f, num9, 0f) * new Vector3(num12, 0f, 0f); transform.position = position + val8; Quaternion val9 = Quaternion.Euler(num4, num9, 0f); transform.rotation = val6 * val9; Vector3 val10 = val9 * Vector3.forward; float num13 = num9 - num6 / 2f; float num14 = num13 + num6; float num15 = num4 + num2 / 2f; float num16 = num15 - num2; float num17 = (num13 + num14) / 2f; float num18 = ((Mathf.Abs(num15) < Mathf.Abs(num16)) ? num15 : num16); Vector3 val11 = Quaternion.Euler(num18, num13, 0f) * Vector3.forward; Vector3 val12 = Quaternion.Euler(num18, num14, 0f) * Vector3.forward; Vector3 val13 = Quaternion.Euler(num15, num17, 0f) * Vector3.forward; Vector3 val14 = Quaternion.Euler(num16, num17, 0f) * Vector3.forward; Vector3 val15 = val11 / Vector3.Dot(val11, val10); Vector3 val16 = val12 / Vector3.Dot(val12, val10); Vector3 val17 = val13 / Vector3.Dot(val13, val10); Vector3 val18 = val14 / Vector3.Dot(val14, val10); Vector3 val19 = val16 - val15; Vector3 val20 = val18 - val17; float magnitude = ((Vector3)(ref val19)).magnitude; float magnitude2 = ((Vector3)(ref val20)).magnitude; float num19 = 1f / magnitude; float num20 = 1f / magnitude2; Vector3 uAxis = val19 * num19; Vector3 vAxis = val20 * num20; steamVR_SphericalProjection.Set(val10, num13, num14, num15, num16, uAxis, val15, num19, vAxis, val17, num20); val3.aspect = magnitude / magnitude2; val3.Render(); RenderTexture.active = val7; val.ReadPixels(new Rect(0f, 0f, (float)((Texture)val7).width, (float)((Texture)val7).height), num10, num8 + num11); RenderTexture.active = null; } float num21 = ((float)i * ((float)num5 * 2f) + (float)k + (float)(j * num5)) / ((float)num * ((float)num5 * 2f)); OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, num21); } } } OpenVR.Screenshots.UpdateScreenshotProgress(screenshotHandle, 1f); previewFilename += ".png"; VRFilename += ".png"; val4.Apply(); File.WriteAllBytes(previewFilename, ImageConversion.EncodeToPNG(val4)); val.Apply(); File.WriteAllBytes(VRFilename, ImageConversion.EncodeToPNG(val)); if ((Object)(object)val3 != (Object)(object)val2) { val3.targetTexture = targetTexture; val3.orthographic = orthographic; val3.fieldOfView = fieldOfView; val3.aspect = aspect; val3.stereoTargetEye = stereoTargetEye; target.transform.localPosition = localPosition; target.transform.localRotation = localRotation; } else { val2.targetTexture = null; } Object.DestroyImmediate((Object)(object)val7); Object.DestroyImmediate((Object)(object)steamVR_SphericalProjection); stopwatch.Stop(); Debug.Log((object)$"Screenshot took {stopwatch.Elapsed} seconds."); if ((Object)(object)val2 != (Object)null) { Object.DestroyImmediate((Object)(object)((Component)val2).gameObject); } Object.DestroyImmediate((Object)(object)val4); Object.DestroyImmediate((Object)(object)val); } } namespace Unity.XR.OpenVR.SimpleJSON { public enum JSONNodeType { Array = 1, Object = 2, String = 3, Number = 4, NullValue = 5, Boolean = 6, None = 7, Custom = 255 } public enum JSONTextMode { Compact, Indent } public abstract class JSONNode { public struct Enumerator { private enum Type { None, Array, Object } private Type type; private Dictionary<string, JSONNode>.Enumerator m_Object; private List<JSONNode>.Enumerator m_Array; public bool IsValid => type != Type.None; public KeyValuePair<string, JSONNode> Current { get { if (type == Type.Array) { return new KeyValuePair<string, JSONNode>(string.Empty, m_Array.Current); } if (type == Type.Object) { return m_Object.Current; } return new KeyValuePair<string, JSONNode>(string.Empty, null); } } public Enumerator(List<JSONNode>.Enumerator aArrayEnum) { type = Type.Array; m_Object = default(Dictionary<string, JSONNode>.Enumerator); m_Array = aArrayEnum; } public Enumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) { type = Type.Object; m_Object = aDictEnum; m_Array = default(List<JSONNode>.Enumerator); } public bool MoveNext() { if (type == Type.Array) { return m_Array.MoveNext(); } if (type == Type.Object) { return m_Object.MoveNext(); } return false; } } public struct ValueEnumerator { private Enumerator m_Enumerator; public JSONNode Current => m_Enumerator.Current.Value; public ValueEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public ValueEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public ValueEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public ValueEnumerator GetEnumerator() { return this; } } public struct KeyEnumerator { private Enumerator m_Enumerator; public string Current => m_Enumerator.Current.Key; public KeyEnumerator(List<JSONNode>.Enumerator aArrayEnum) : this(new Enumerator(aArrayEnum)) { } public KeyEnumerator(Dictionary<string, JSONNode>.Enumerator aDictEnum) : this(new Enumerator(aDictEnum)) { } public KeyEnumerator(Enumerator aEnumerator) { m_Enumerator = aEnumerator; } public bool MoveNext() { return m_Enumerator.MoveNext(); } public KeyEnumerator GetEnumerator() { return this; } } public class LinqEnumerator : IEnumerator<KeyValuePair<string, JSONNode>>, IEnumerator, IDisposable, IEnumerable<KeyValuePair<string, JSONNode>>, IEnumerable { private JSONNode m_Node; private Enumerator m_Enumerator; public KeyValuePair<string, JSONNode> Current => m_Enumerator.Current; object IEnumerator.Current => m_Enumerator.Current; internal LinqEnumerator(JSONNode aNode) { m_Node = aNode; if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } public bool MoveNext() { return m_Enumerator.MoveNext(); } public void Dispose() { m_Node = null; m_Enumerator = default(Enumerator); } public IEnumerator<KeyValuePair<string, JSONNode>> GetEnumerator() { return new LinqEnumerator(m_Node); } public void Reset() { if (m_Node != null) { m_Enumerator = m_Node.GetEnumerator(); } } IEnumerator IEnumerable.GetEnumerator() { return new LinqEnumerator(m_Node); } } public static bool forceASCII = false; public static bool longAsString = false; public static bool allowLineComments = true; [ThreadStatic] private static StringBuilder m_EscapeBuilder; public abstract JSONNodeType Tag { get; } public virtual JSONNode this[int aIndex] { get { return null; } set { } } public virtual JSONNode this[string aKey] { get { return null; } set { } } public virtual string Value { get { return ""; } set { } } public virtual int Count => 0; public virtual bool IsNumber => false; public virtual bool IsString => false; public virtual bool IsBoolean => false; public virtual bool IsNull => false; public virtual bool IsArray => false; public virtual bool IsObject => false; public virtual bool Inline { get { return false; } set { } } public virtual IEnumerable<JSONNode> Children { get { yield break; } } public IEnumerable<JSONNode> DeepChildren { get { foreach (JSONNode child in Children) { foreach (JSONNode deepChild in child.DeepChildren) { yield return deepChild; } } } } public IEnumerable<KeyValuePair<string, JSONNode>> Linq => new LinqEnumerator(this); public KeyEnumerator Keys => new KeyEnumerator(GetEnumerator()); public ValueEnumerator Values => new ValueEnumerator(GetEnumerator()); public virtual double AsDouble { get { double result = 0.0; if (double.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out result)) { return result; } return 0.0; } set { Value = value.ToString(CultureInfo.InvariantCulture); } } public virtual int AsInt { get { return (int)AsDouble; } set { AsDouble = value; } } public virtual float AsFloat { get { return (float)AsDouble; } set { AsDouble = value; } } public virtual bool AsBool { get { bool result = false; if (bool.TryParse(Value, out result)) { return result; } return !string.IsNullOrEmpty(Value); } set { Value = (value ? "true" : "false"); } } public virtual long AsLong { get { long result = 0L; if (long.TryParse(Value, out result)) { return result; } return 0L; } set { Value = value.ToString(); } } public virtual JSONArray AsArray => this as JSONArray; public virtual JSONObject AsObject => this as JSONObject; internal static StringBuilder EscapeBuilder { get { if (m_EscapeBuilder == null) { m_EscapeBuilder = new StringBuilder(); } return m_EscapeBuilder; } } public virtual void Add(string aKey, JSONNode aItem) { } public virtual void Add(JSONNode aItem) { Add("", aItem); } public virtual JSONNode Remove(string aKey) { return null; } public virtual JSONNode Remove(int aIndex) { return null; } public virtual JSONNode Remove(JSONNode aNode) { return aNode; } public virtual JSONNode Clone() { return null; } public virtual bool HasKey(string aKey) { return false; } public virtual JSONNode GetValueOrDefault(string aKey, JSONNode aDefault) { return aDefault; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, 0, JSONTextMode.Compact); return stringBuilder.ToString(); } public virtual string ToString(int aIndent) { StringBuilder stringBuilder = new StringBuilder(); WriteToStringBuilder(stringBuilder, 0, aIndent, JSONTextMode.Indent); return stringBuilder.ToString(); } internal abstract void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode); public abstract Enumerator GetEnumerator(); public static implicit operator JSONNode(string s) { return new JSONString(s); } public static implicit operator string(JSONNode d) { if (!(d == null)) { return d.Value; } return null; } public static implicit operator JSONNode(double n) { return new JSONNumber(n); } public static implicit operator double(JSONNode d) { if (!(d == null)) { return d.AsDouble; } return 0.0; } public static implicit operator JSONNode(float n) { return new JSONNumber(n); } public static implicit operator float(JSONNode d) { if (!(d == null)) { return d.AsFloat; } return 0f; } public static implicit operator JSONNode(int n) { return new JSONNumber(n); } public static implicit operator int(JSONNode d) { if (!(d == null)) { return d.AsInt; } return 0; } public static implicit operator JSONNode(long n) { if (longAsString) { return new JSONString(n.ToString()); } return new JSONNumber(n); } public static implicit operator long(JSONNode d) { if (!(d == null)) { return d.AsLong; } return 0L; } public static implicit operator JSONNode(bool b) { return new JSONBool(b); } public static implicit operator bool(JSONNode d) { if (!(d == null)) { return d.AsBool; } return false; } public static implicit operator JSONNode(KeyValuePair<string, JSONNode> aKeyValue) { return aKeyValue.Value; } public static bool operator ==(JSONNode a, object b) { if ((object)a == b) { return true; } bool flag = a is JSONNull || (object)a == null || a is JSONLazyCreator; bool flag2 = b is JSONNull || b == null || b is JSONLazyCreator; if (flag && flag2) { return true; } if (!flag) { return a.Equals(b); } return false; } public static bool operator !=(JSONNode a, object b) { return !(a == b); } public override bool Equals(object obj) { return (object)this == obj; } public override int GetHashCode() { return base.GetHashCode(); } internal static string Escape(string aText) { StringBuilder escapeBuilder = EscapeBuilder; escapeBuilder.Length = 0; if (escapeBuilder.Capacity < aText.Length + aText.Length / 10) { escapeBuilder.Capacity = aText.Length + aText.Length / 10; } foreach (char c in aText) { switch (c) { case '\\': escapeBuilder.Append("\\\\"); continue; case '"': escapeBuilder.Append("\\\""); continue; case '\n': escapeBuilder.Append("\\n"); continue; case '\r': escapeBuilder.Append("\\r"); continue; case '\t': escapeBuilder.Append("\\t"); continue; case '\b': escapeBuilder.Append("\\b"); continue; case '\f': escapeBuilder.Append("\\f"); continue; } if (c < ' ' || (forceASCII && c > '\u007f')) { ushort num = c; escapeBuilder.Append("\\u").Append(num.ToString("X4")); } else { escapeBuilder.Append(c); } } string result = escapeBuilder.ToString(); escapeBuilder.Length = 0; return result; } private static JSONNode ParseElement(string token, bool quoted) { if (quoted) { return token; } string text = token.ToLower(); switch (text) { case "false": case "true": return text == "true"; case "null": return JSONNull.CreateOrGet(); default: { if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } return token; } } } public static JSONNode Parse(string aJSON) { Stack<JSONNode> stack = new Stack<JSONNode>(); JSONNode jSONNode = null; int i = 0; StringBuilder stringBuilder = new StringBuilder(); string aKey = ""; bool flag = false; bool flag2 = false; for (; i < aJSON.Length; i++) { switch (aJSON[i]) { case '{': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONObject()); if (jSONNode != null) { jSONNode.Add(aKey, stack.Peek()); } aKey = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case '[': if (flag) { stringBuilder.Append(aJSON[i]); break; } stack.Push(new JSONArray()); if (jSONNode != null) { jSONNode.Add(aKey, stack.Peek()); } aKey = ""; stringBuilder.Length = 0; jSONNode = stack.Peek(); break; case ']': case '}': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stack.Count == 0) { throw new Exception("JSON Parse: Too many closing brackets"); } stack.Pop(); if (stringBuilder.Length > 0 || flag2) { jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2)); } flag2 = false; aKey = ""; stringBuilder.Length = 0; if (stack.Count > 0) { jSONNode = stack.Peek(); } break; case ':': if (flag) { stringBuilder.Append(aJSON[i]); break; } aKey = stringBuilder.ToString(); stringBuilder.Length = 0; flag2 = false; break; case '"': flag = !flag; flag2 = flag2 || flag; break; case ',': if (flag) { stringBuilder.Append(aJSON[i]); break; } if (stringBuilder.Length > 0 || flag2) { jSONNode.Add(aKey, ParseElement(stringBuilder.ToString(), flag2)); } flag2 = false; aKey = ""; stringBuilder.Length = 0; flag2 = false; break; case '\t': case ' ': if (flag) { stringBuilder.Append(aJSON[i]); } break; case '\\': i++; if (flag) { char c = aJSON[i]; switch (c) { case 't': stringBuilder.Append('\t'); break; case 'r': stringBuilder.Append('\r'); break; case 'n': stringBuilder.Append('\n'); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'u': { string s = aJSON.Substring(i + 1, 4); stringBuilder.Append((char)int.Parse(s, NumberStyles.AllowHexSpecifier)); i += 4; break; } default: stringBuilder.Append(c); break; } } break; case '/': if (allowLineComments && !flag && i + 1 < aJSON.Length && aJSON[i + 1] == '/') { while (++i < aJSON.Length && aJSON[i] != '\n' && aJSON[i] != '\r') { } } else { stringBuilder.Append(aJSON[i]); } break; default: stringBuilder.Append(aJSON[i]); break; case '\n': case '\r': case '\ufeff': break; } } if (flag) { throw new Exception("JSON Parse: Quotation marks seems to be messed up."); } if (jSONNode == null) { return ParseElement(stringBuilder.ToString(), flag2); } return jSONNode; } } public class JSONArray : JSONNode { private List<JSONNode> m_List = new List<JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Array; public override bool IsArray => true; public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_List.Count) { return new JSONLazyCreator(this); } return m_List[aIndex]; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex < 0 || aIndex >= m_List.Count) { m_List.Add(value); } else { m_List[aIndex] = value; } } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this); } set { if (value == null) { value = JSONNull.CreateOrGet(); } m_List.Add(value); } } public override int Count => m_List.Count; public override IEnumerable<JSONNode> Children { get { foreach (JSONNode item in m_List) { yield return item; } } } public override Enumerator GetEnumerator() { return new Enumerator(m_List.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } m_List.Add(aItem); } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_List.Count) { return null; } JSONNode result = m_List[aIndex]; m_List.RemoveAt(aIndex); return result; } public override JSONNode Remove(JSONNode aNode) { m_List.Remove(aNode); return aNode; } public override JSONNode Clone() { JSONArray jSONArray = new JSONArray(); jSONArray.m_List.Capacity = m_List.Capacity; foreach (JSONNode item in m_List) { if (item != null) { jSONArray.Add(item.Clone()); } else { jSONArray.Add(null); } } return jSONArray; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('['); int count = m_List.Count; if (inline) { aMode = JSONTextMode.Compact; } for (int i = 0; i < count; i++) { if (i > 0) { aSB.Append(','); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } m_List[i].WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append(']'); } } public class JSONObject : JSONNode { private Dictionary<string, JSONNode> m_Dict = new Dictionary<string, JSONNode>(); private bool inline; public override bool Inline { get { return inline; } set { inline = value; } } public override JSONNodeType Tag => JSONNodeType.Object; public override bool IsObject => true; public override JSONNode this[string aKey] { get { if (m_Dict.ContainsKey(aKey)) { return m_Dict[aKey]; } return new JSONLazyCreator(this, aKey); } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = value; } else { m_Dict.Add(aKey, value); } } } public override JSONNode this[int aIndex] { get { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } return m_Dict.ElementAt(aIndex).Value; } set { if (value == null) { value = JSONNull.CreateOrGet(); } if (aIndex >= 0 && aIndex < m_Dict.Count) { string key = m_Dict.ElementAt(aIndex).Key; m_Dict[key] = value; } } } public override int Count => m_Dict.Count; public override IEnumerable<JSONNode> Children { get { foreach (KeyValuePair<string, JSONNode> item in m_Dict) { yield return item.Value; } } } public override Enumerator GetEnumerator() { return new Enumerator(m_Dict.GetEnumerator()); } public override void Add(string aKey, JSONNode aItem) { if (aItem == null) { aItem = JSONNull.CreateOrGet(); } if (aKey != null) { if (m_Dict.ContainsKey(aKey)) { m_Dict[aKey] = aItem; } else { m_Dict.Add(aKey, aItem); } } else { m_Dict.Add(Guid.NewGuid().ToString(), aItem); } } public override JSONNode Remove(string aKey) { if (!m_Dict.ContainsKey(aKey)) { return null; } JSONNode result = m_Dict[aKey]; m_Dict.Remove(aKey); return result; } public override JSONNode Remove(int aIndex) { if (aIndex < 0 || aIndex >= m_Dict.Count) { return null; } KeyValuePair<string, JSONNode> keyValuePair = m_Dict.ElementAt(aIndex); m_Dict.Remove(keyValuePair.Key); return keyValuePair.Value; } public override JSONNode Remove(JSONNode aNode) { try { KeyValuePair<string, JSONNode> keyValuePair = m_Dict.Where((KeyValuePair<string, JSONNode> k) => k.Value == aNode).First(); m_Dict.Remove(keyValuePair.Key); return aNode; } catch { return null; } } public override JSONNode Clone() { JSONObject jSONObject = new JSONObject(); foreach (KeyValuePair<string, JSONNode> item in m_Dict) { jSONObject.Add(item.Key, item.Value.Clone()); } return jSONObject; } public override bool HasKey(string aKey) { return m_Dict.ContainsKey(aKey); } public override JSONNode GetValueOrDefault(string aKey, JSONNode aDefault) { if (m_Dict.TryGetValue(aKey, out var value)) { return value; } return aDefault; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('{'); bool flag = true; if (inline) { aMode = JSONTextMode.Compact; } foreach (KeyValuePair<string, JSONNode> item in m_Dict) { if (!flag) { aSB.Append(','); } flag = false; if (aMode == JSONTextMode.Indent) { aSB.AppendLine(); } if (aMode == JSONTextMode.Indent) { aSB.Append(' ', aIndent + aIndentInc); } aSB.Append('"').Append(JSONNode.Escape(item.Key)).Append('"'); if (aMode == JSONTextMode.Compact) { aSB.Append(':'); } else { aSB.Append(" : "); } item.Value.WriteToStringBuilder(aSB, aIndent + aIndentInc, aIndentInc, aMode); } if (aMode == JSONTextMode.Indent) { aSB.AppendLine().Append(' ', aIndent); } aSB.Append('}'); } } public class JSONString : JSONNode { private string m_Data; public override JSONNodeType Tag => JSONNodeType.String; public override bool IsString => true; public override string Value { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONString(string aData) { m_Data = aData; } public override JSONNode Clone() { return new JSONString(m_Data); } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append('"').Append(JSONNode.Escape(m_Data)).Append('"'); } public override bool Equals(object obj) { if (base.Equals(obj)) { return true; } if (obj is string text) { return m_Data == text; } JSONString jSONString = obj as JSONString; if (jSONString != null) { return m_Data == jSONString.m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNumber : JSONNode { private double m_Data; public override JSONNodeType Tag => JSONNodeType.Number; public override bool IsNumber => true; public override string Value { get { return m_Data.ToString(CultureInfo.InvariantCulture); } set { if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { m_Data = result; } } } public override double AsDouble { get { return m_Data; } set { m_Data = value; } } public override long AsLong { get { return (long)m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONNumber(double aData) { m_Data = aData; } public JSONNumber(string aData) { Value = aData; } public override JSONNode Clone() { return new JSONNumber(m_Data); } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(Value); } private static bool IsNumeric(object value) { if (!(value is int) && !(value is uint) && !(value is float) && !(value is double) && !(value is decimal) && !(value is long) && !(value is ulong) && !(value is short) && !(value is ushort) && !(value is sbyte)) { return value is byte; } return true; } public override bool Equals(object obj) { if (obj == null) { return false; } if (base.Equals(obj)) { return true; } JSONNumber jSONNumber = obj as JSONNumber; if (jSONNumber != null) { return m_Data == jSONNumber.m_Data; } if (IsNumeric(obj)) { return Convert.ToDouble(obj) == m_Data; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONBool : JSONNode { private bool m_Data; public override JSONNodeType Tag => JSONNodeType.Boolean; public override bool IsBoolean => true; public override string Value { get { return m_Data.ToString(); } set { if (bool.TryParse(value, out var result)) { m_Data = result; } } } public override bool AsBool { get { return m_Data; } set { m_Data = value; } } public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONBool(bool aData) { m_Data = aData; } public JSONBool(string aData) { Value = aData; } public override JSONNode Clone() { return new JSONBool(m_Data); } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append(m_Data ? "true" : "false"); } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is bool) { return m_Data == (bool)obj; } return false; } public override int GetHashCode() { return m_Data.GetHashCode(); } } public class JSONNull : JSONNode { private static JSONNull m_StaticInstance = new JSONNull(); public static bool reuseSameInstance = true; public override JSONNodeType Tag => JSONNodeType.NullValue; public override bool IsNull => true; public override string Value { get { return "null"; } set { } } public override bool AsBool { get { return false; } set { } } public static JSONNull CreateOrGet() { if (reuseSameInstance) { return m_StaticInstance; } return new JSONNull(); } private JSONNull() { } public override Enumerator GetEnumerator() { return default(Enumerator); } public override JSONNode Clone() { return CreateOrGet(); } public override bool Equals(object obj) { if ((object)this == obj) { return true; } return obj is JSONNull; } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append("null"); } } internal class JSONLazyCreator : JSONNode { private JSONNode m_Node; private string m_Key; public override JSONNodeType Tag => JSONNodeType.None; public override JSONNode this[int aIndex] { get { return new JSONLazyCreator(this); } set { Set(new JSONArray()).Add(value); } } public override JSONNode this[string aKey] { get { return new JSONLazyCreator(this, aKey); } set { Set(new JSONObject()).Add(aKey, value); } } public override int AsInt { get { Set(new JSONNumber(0.0)); return 0; } set { Set(new JSONNumber(value)); } } public override float AsFloat { get { Set(new JSONNumber(0.0)); return 0f; } set { Set(new JSONNumber(value)); } } public override double AsDouble { get { Set(new JSONNumber(0.0)); return 0.0; } set { Set(new JSONNumber(value)); } } public override long AsLong { get { if (JSONNode.longAsString) { Set(new JSONString("0")); } else { Set(new JSONNumber(0.0)); } return 0L; } set { if (JSONNode.longAsString) { Set(new JSONString(value.ToString())); } else { Set(new JSONNumber(value)); } } } public override bool AsBool { get { Set(new JSONBool(aData: false)); return false; } set { Set(new JSONBool(value)); } } public override JSONArray AsArray => Set(new JSONArray()); public override JSONObject AsObject => Set(new JSONObject()); public override Enumerator GetEnumerator() { return default(Enumerator); } public JSONLazyCreator(JSONNode aNode) { m_Node = aNode; m_Key = null; } public JSONLazyCreator(JSONNode aNode, string aKey) { m_Node = aNode; m_Key = aKey; } private T Set<T>(T aVal) where T : JSONNode { if (m_Key == null) { m_Node.Add(aVal); } else { m_Node.Add(m_Key, aVal); } m_Node = null; return aVal; } public override void Add(JSONNode aItem) { Set(new JSONArray()).Add(aItem); } public override void Add(string aKey, JSONNode aItem) { Set(new JSONObject()).Add(aKey, aItem); } public static bool operator ==(JSONLazyCreator a, object b) { if (b == null) { return true; } return (object)a == b; } public static bool operator !=(JSONLazyCreator a, object b) { return !(a == b); } public override bool Equals(object obj) { if (obj == null) { return true; } return (object)this == obj; } public override int GetHashCode() { return 0; } internal override void WriteToStringBuilder(StringBuilder aSB, int aIndent, int aIndentInc, JSONTextMode aMode) { aSB.Append("null"); } } public static class JSON { public static JSONNode Parse(string aJSON) { return JSONNode.Parse(aJSON); } } } namespace Valve.VR { public class SteamVR_CameraHelper : MonoBehaviour { private void Start() { if ((Object)(object)((Component)this).gameObject.GetComponent<TrackedPoseDriver>() == (Object)null) { ((Component)this).gameObject.AddComponent<TrackedPoseDriver>(); } } } [Serializable] public class SteamVR_Behaviour_BooleanEvent : UnityEvent<SteamVR_Behaviour_Boolean, SteamVR_Input_Sources, bool> { } [Serializable] public class SteamVR_Behaviour_PoseEvent : UnityEvent<SteamVR_Behaviour_Pose, SteamVR_Input_Sources> { } [Serializable] public class SteamVR_Behaviour_Pose_ConnectedChangedEvent : UnityEvent<SteamVR_Behaviour_Pose, SteamVR_Input_Sources, bool> { } [Serializable] public class SteamVR_Behaviour_Pose_DeviceIndexChangedEvent : UnityEvent<SteamVR_Behaviour_Pose, SteamVR_Input_Sources, int> { } [Serializable] public class SteamVR_Behaviour_Pose_TrackingChangedEvent : UnityEvent<SteamVR_Behaviour_Pose, SteamVR_Input_Sources, ETrackingResult> { } [Serializable] public class SteamVR_Behaviour_SingleEvent : UnityEvent<SteamVR_Behaviour_Single, SteamVR_Input_Sources, float, float> { } [Serializable] public class SteamVR_Behaviour_SkeletonEvent : UnityEvent<SteamVR_Behaviour_Skeleton, SteamVR_Input_Sources> { } [Serializable] public class SteamVR_Behaviour_Skeleton_ConnectedChangedEvent : UnityEvent<SteamVR_Behaviour_Skeleton, SteamVR_Input_Sources, bool> { } [Serializable] public class SteamVR_Behaviour_Skeleton_TrackingChangedEvent : UnityEvent<SteamVR_Behaviour_Skeleton, SteamVR_Input_Sources, ETrackingResult> { } [Serializable] public class SteamVR_Behaviour_Vector2Event : UnityEvent<SteamVR_Behaviour_Vector2, SteamVR_Input_Sources, Vector2, Vector2> { } [Serializable] public class SteamVR_Behaviour_Vector3Event : UnityEvent<SteamVR_Behaviour_Vector3, SteamVR_Input_Sources, Vector3, Vector3> { } [Serializable] public abstract class SteamVR_Action<SourceMap, SourceElement> : SteamVR_Action, ISteamVR_Action, ISteamVR_Action_Source where SourceMap : SteamVR_Action_Source_Map<SourceElement>, new() where SourceElement : SteamVR_Action_Source, new() { [NonSerialized] protected SourceMap sourceMap; [NonSerialized] protected bool initialized; public virtual SourceElement this[SteamVR_Input_Sources inputSource] => sourceMap[inputSource]; public override string fullPath => sourceMap.fullPath; public override ulong handle => sourceMap.handle; public override SteamVR_ActionSet actionSet => sourceMap.actionSet; public override SteamVR_ActionDirections direction => sourceMap.direction; public override bool active => sourceMap[SteamVR_Input_Sources.Any].active; public override bool lastActive => sourceMap[SteamVR_Input_Sources.Any].lastActive; public override bool activeBinding => sourceMap[SteamVR_Input_Sources.Any].activeBinding; public override bool lastActiveBinding => sourceMap[SteamVR_Input_Sources.Any].lastActiveBinding; public override void PreInitialize(string newActionPath) { actionPath = newActionPath; sourceMap = new SourceMap(); sourceMap.PreInitialize(this, actionPath); initialized = true; } protected override void CreateUninitialized(string newActionPath, bool caseSensitive) { actionPath = newActionPath; sourceMap = new SourceMap(); sourceMap.PreInitialize(this, actionPath, throwErrors: false); needsReinit = true; initialized = false; } protected override void CreateUninitialized(string newActionSet, SteamVR_ActionDirections direction, string newAction, bool caseSensitive) { actionPath = SteamVR_Input_ActionFile_Action.CreateNewName(newActionSet, direction, newAction); sourceMap = new SourceMap(); sourceMap.PreInitialize(this, actionPath, throwErrors: false); needsReinit = true; initialized = false; } public override string TryNeedsInitData() { if (needsReinit && actionPath != null) { SteamVR_Action steamVR_Action = SteamVR_Action.FindExistingActionForPartialPath(actionPath); if (!(steamVR_Action == null)) { actionPath = steamVR_Action.fullPath; sourceMap = (SourceMap)steamVR_Action.GetSourceMap(); initialized = true; needsReinit = false; return actionPath; } sourceMap = null; } return null; } public override void Initialize(bool createNew = false, bool throwErrors = true) { if (needsReinit) { TryNeedsInitData(); } if (createNew) { sourceMap.Initialize(); } else { sourceMap = SteamVR_Input.GetActionDataFromPath<SourceMap>(actionPath); _ = sourceMap; } initialized = true; } public override SteamVR_Action_Source_Map GetSourceMap() { return sourceMap; } protected override void InitializeCopy(string newActionPath, SteamVR_Action_Source_Map newData) { actionPath = newActionPath; sourceMap = (SourceMap)newData; initialized = true; } protected void InitAfterDeserialize() { if (sourceMap != null) { if (sourceMap.fullPath != actionPath) { needsReinit = true; TryNeedsInitData(); } if (string.IsNullOrEmpty(actionPath)) { sourceMap = null; } } if (!initialized) { Initialize(createNew: false, throwErrors: false); } } public override bool GetActive(SteamVR_Input_Sources inputSource) { return sourceMap[inputSource].active; } public override bool GetActiveBinding(SteamVR_Input_Sources inputSource) { return sourceMap[inputSource].activeBinding; } public override bool GetLastActive(SteamVR_Input_Sources inputSource) { return sourceMap[inputSource].lastActive; } public override bool GetLastActiveBinding(SteamVR_Input_Sources inputSource) { return sourceMap[inputSource].lastActiveBinding; } } [Serializable] public abstract class SteamVR_Action : IEquatable<SteamVR_Action>, ISteamVR_Action, ISteamVR_Action_Source { [SerializeField] protected string actionPath; [SerializeField] protected bool needsReinit; public static bool startUpdatingSourceOnAccess = true; [NonSerialized] private string cachedShortName; public abstract string fullPath { get; } public abstract ulong handle { get; } public abstract SteamVR_ActionSet actionSet { get; } public abstract SteamVR_ActionDirections direction { get; } public bool setActive => actionSet.IsActive(); public abstract bool active { get; } public abstract bool activeBinding { get; } public abstract bool lastActive { get; } public abstract bool lastActiveBinding { get; } public SteamVR_Action() { } public static CreateType Create<CreateType>(string newActionPath) where CreateType : SteamVR_Action, new() { CreateType val = new CreateType(); val.PreInitialize(newActionPath); return val; } public static CreateType CreateUninitialized<CreateType>(string setName, SteamVR_ActionDirections direction, string newActionName, bool caseSensitive) where CreateType : SteamVR_Action, new() { CreateType val = new CreateType(); val.CreateUninitialized(setName, direction, newActionName, caseSensitive); return val; } public static CreateType CreateUninitialized<CreateType>(string actionPath, bool caseSensitive) where CreateType : SteamVR_Action, new() { CreateType val = new CreateType(); val.CreateUninitialized(actionPath, caseSensitive); return val; } public CreateType GetCopy<CreateType>() where CreateType : SteamVR_Action, new() { if (SteamVR_Input.ShouldMakeCopy()) { CreateType val = new CreateType(); val.InitializeCopy(actionPath, GetSourceMap()); return val; } return (CreateType)this; } public abstract string TryNeedsInitData(); protected abstract void InitializeCopy(string newActionPath, SteamVR_Action_Source_Map newData); public abstract void PreInitialize(string newActionPath); protected abstract void CreateUninitialized(string newActionPath, bool caseSensitive); protected abstract void CreateUninitialized(string newActionSet, SteamVR_ActionDirections direction, string newAction, bool caseSensitive); public abstract void Initialize(bool createNew = false, bool throwNotSetError = true); public abstract float GetTimeLastChanged(SteamVR_Input_Sources inputSource); public abstract SteamVR_Action_Source_Map GetSourceMap(); public abstract bool GetActive(SteamVR_Input_Sources inputSource); public bool GetSetActive(SteamVR_Input_Sources inputSource) { return actionSet.IsActive(inputSource); } public abstract bool GetActiveBinding(SteamVR_Input_Sources inputSource); public abstract bool GetLastActive(SteamVR_Input_Sources inputSource); public abstract bool GetLastActiveBinding(SteamVR_Input_Sources inputSource); public string GetPath() { return actionPath; } public abstract bool IsUpdating(SteamVR_Input_Sources inputSource); public override int GetHashCode() { if (actionPath == null) { return 0; } return actionPath.GetHashCode(); } public bool Equals(SteamVR_Action other) { if ((object)other == null) { return false; } return actionPath == other.actionPath; } public override bool Equals(object other) { if (other == null) { if (string.IsNullOrEmpty(actionPath)) { return true; } if (GetSourceMap() == null) { return true; } return false; } if (this == other) { return true; } if (other is SteamVR_Action) { return Equals((SteamVR_Action)other); } return false; } public static bool operator !=(SteamVR_Action action1, SteamVR_Action action2) { return !(action1 == action2); } public static bool operator ==(SteamVR_Action action1, SteamVR_Action action2) { bool flag = (object)action1 == null || string.IsNullOrEmpty(action1.actionPath) || action1.GetSourceMap() == null; bool flag2 = (object)action2 == null || string.IsNullOrEmpty(action2.actionPath) || action2.GetSourceMap() == null; if (flag && flag2) { return true; } if (flag != flag2) { return false; } return action1.Equals(action2); } public static SteamVR_Action FindExistingActionForPartialPath(string path) { if (string.IsNullOrEmpty(path) || path.IndexOf('/') == -1) { return null; } string[] array = path.Split(new char[1] { '/' }); if (array.Length >= 5 && string.IsNullOrEmpty(array[2])) { string actionSetName = array[2]; string actionName = array[4]; return SteamVR_Input.GetBaseAction(actionSetName, actionName); } return SteamVR_Input.GetBaseActionFromPath(path); } public string GetShortName() { if (cachedShortName == null) { cachedShortName = SteamVR_Input_ActionFile.GetShortName(fullPath); } return cachedShortName; } public void ShowOrigins() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) OpenVR.Input.ShowActionOrigins(actionSet.handle, handle); } public void HideOrigins() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) OpenVR.Input.ShowActionOrigins(0uL, 0uL); } } public abstract class SteamVR_Action_Source_Map<SourceElement> : SteamVR_Action_Source_Map where SourceElement : SteamVR_Action_Source, new() { protected SourceElement[] sources = new SourceElement[SteamVR_Input_Source.numSources]; public SourceElement this[SteamVR_Input_Sources inputSource] => GetSourceElementForIndexer(inputSource); protected virtual void OnAccessSource(SteamVR_Input_Sources inputSource) { } public override void Initialize() { base.Initialize(); for (int i = 0; i < sources.Length; i++) { if (sources[i] != null) { sources[i].Initialize(); } } } protected override void PreinitializeMap(SteamVR_Input_Sources inputSource, SteamVR_Action wrappingAction) { sources[(int)inputSource] = new SourceElement(); sources[(int)inputSource].Preinitialize(wrappingAction, inputSource); } protected virtual SourceElement GetSourceElementForIndexer(SteamVR_Input_Sources inputSource) { OnAccessSource(inputSource); return sources[(int)inputSource]; } } public abstract class SteamVR_Action_Source_Map { public SteamVR_Action action; private static string inLowered = "IN".ToLower(CultureInfo.CurrentCulture); private static string outLowered = "OUT".ToLower(CultureInfo.CurrentCulture); public string fullPath { get; protected set; } public ulong handle { get; protected set; } public SteamVR_ActionSet actionSet { get; protected set; } public SteamVR_ActionDirections direction { get; protected set; } public virtual void PreInitialize(SteamVR_Action wrappingAction, string actionPath, bool throwErrors = true) { fullPath = actionPath; action = wrappingAction; actionSet = SteamVR_Input.GetActionSetFromPath(GetActionSetPath()); direction = GetActionDirection(); SteamVR_Input_Sources[] allSources = SteamVR_Input_Source.GetAllSources(); for (int i = 0; i < allSources.Length; i++) { PreinitializeMap(allSources[i], wrappingAction); } } protected abstract void PreinitializeMap(SteamVR_Input_Sources inputSource, SteamVR_Action wrappingAction); public virtual void Initialize() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) ulong num = 0uL; EVRInputError actionHandle = OpenVR.Input.GetActionHandle(fullPath.ToLowerInvariant(), ref num); handle = num; if ((int)actionHandle != 0) { Debug.LogError((object)("<b>[SteamVR]</b> GetActionHandle (" + fullPath.ToLowerInvariant() + ") error: " + ((object)(EVRInputError)(ref actionHandle)).ToString())); } } private string GetActionSetPath() { int startIndex = fullPath.IndexOf('/', 1) + 1; int length = fullPath.IndexOf('/', startIndex); return fullPath.Substring(0, length); } private SteamVR_ActionDirections GetActionDirection() { int startIndex = fullPath.IndexOf('/', 1) + 1; int num = fullPath.IndexOf('/', startIndex); int length = fullPath.IndexOf('/', num + 1) - num - 1; string text = fullPath.Substring(num + 1, length); if (text == inLowered) { return SteamVR_ActionDirections.In; } if (text == outLowered) { return SteamVR_ActionDirections.Out; } Debug.LogError((object)("Could not find match for direction: " + text)); return SteamVR_ActionDirections.In; } } public abstract class SteamVR_Action_Source : ISteamVR_Action_Source { protected ulong inputSourceHandle; protected SteamVR_Action action; public string fullPath => action.fullPath; public ulong handle => action.handle; public SteamVR_ActionSet actionSet => action.actionSet; public SteamVR_ActionDirections direction => action.direction; public SteamVR_Input_Sources inputSource { get; protected set; } public bool setActive => actionSet.IsActive(inputSource); public abstract bool active { get; } public abstract bool activeBinding { get; } public abstract bool lastActive { get; protected set; } public abstract bool lastActiveBinding { get; } public virtual void Preinitialize(SteamVR_Action wrappingAction, SteamVR_Input_Sources forInputSource) { action = wrappingAction; inputSource = forInputSource; } public SteamVR_Action_Source() { } public virtual void Initialize() { inputSourceHandle = SteamVR_Input_Source.GetHandle(inputSource); } } public interface ISteamVR_Action : ISteamVR_Action_Source { bool GetActive(SteamVR_Input_Sources inputSource); string GetShortName(); } public interface ISteamVR_Action_Source { bool active { get; } bool activeBinding { get; } bool lastActive { get; } bool lastActiveBinding { get; } string fullPath { get; } ulong handle { get; } SteamVR_ActionSet actionSet { get; } SteamVR_ActionDirections direction { get; } } public enum SteamVR_ActionDirections { In, Out } [Serializable] public class SteamVR_ActionSet : IEquatable<SteamVR_ActionSet>, ISteamVR_ActionSet, ISerializationCallbackReceiver { [SerializeField] private string actionSetPath; [NonSerialized] protected SteamVR_ActionSet_Data setData; [NonSerialized] protected bool initialized; public SteamVR_Action[] allActions { get { if (!initialized) { Initialize(); } return setData.allActions; } } public ISteamVR_Action_In[] nonVisualInActions { get { if (!initialized) { Initialize(); } return setData.nonVisualInActions; } } public ISteamVR_Action_In[] visualActions { get { if (!initialized) { Initialize(); } return setData.visualActions; } } public SteamVR_Action_Pose[] poseActions { get { if (!initialized) { Initialize(); } return setData.poseActions; } } public SteamVR_Action_Skeleton[] skeletonActions { get { if (!initialized) { Initialize(); } return setData.skeletonActions; } } public ISteamVR_Action_Out[] outActionArray { get { if (!initialized) { Initialize(); } return setData.outActionArray; } } public string fullPath { get { if (!initialized) { Initialize(); } return setData.fullPath; } } public string usage { get { if (!initialized) { Initialize(); } return setData.usage; } } public ulong handle { get { if (!initialized) { Initialize(); } return setData.handle; } } public static CreateType Create<CreateType>(string newSetPath) where CreateType : SteamVR_ActionSet, new() { CreateType val = new CreateType(); val.PreInitialize(newSetPath); return val; } public static CreateType CreateFromName<CreateType>(string newSetName) where CreateType : SteamVR_ActionSet, new() { CreateType val = new CreateType(); val.PreInitialize(SteamVR_Input_ActionFile_ActionSet.GetPathFromName(newSetName)); return val; } public void PreInitialize(string newActionPath) { actionSetPath = newActionPath; setData = new SteamVR_ActionSet_Data(); setData.fullPath = actionSetPath; setData.PreInitialize(); initialized = true; } public virtual void FinishPreInitialize() { setData.FinishPreInitialize(); } public virtual void Initialize(bool createNew = false, bool throwErrors = true) { if (createNew) { setData.Initialize(); } else { setData = SteamVR_Input.GetActionSetDataFromPath(actionSetPath); _ = setData; } initialized = true; } public string GetPath() { return actionSetPath; } public bool IsActive(SteamVR_Input_Sources source = SteamVR_Input_Sources.Any) { return setData.IsActive(source); } public float GetTimeLastChanged(SteamVR_Input_Sources source = SteamVR_Input_Sources.Any) { return setData.GetTimeLastChanged(source); } public void Activate(SteamVR_Input_Sources activateForSource = SteamVR_Input_Sources.Any, int priority = 0, bool disableAllOtherActionSets = false) { setData.Activate(activateForSource, priority, disableAllOtherActionSets); } public void Deactivate(SteamVR_Input_Sources forSource = SteamVR_Input_Sources.Any) { setData.Deactivate(forSource); } public string GetShortName() { return setData.GetShortName(); } public bool ShowBindingHints(ISteamVR_Action_In originToHighlight = null) { if (originToHighlight == null) { return SteamVR_Input.ShowBindingHints(this); } return SteamVR_Input.ShowBindingHints(originToHighlight); } public bool ReadRawSetActive(SteamVR_Input_Sources inputSource) { return setData.ReadRawSetActive(inputSource); } public float ReadRawSetLastChanged(SteamVR_Input_Sources inputSource) { return setData.ReadRawSetLastChanged(inputSource); } public int ReadRawSetPriority(SteamVR_Input_Sources inputSource) { return setData.ReadRawSetPriority(inputSource); } public SteamVR_ActionSet_Data GetActionSetData() { return setData; } public CreateType GetCopy<CreateType>() where CreateType : SteamVR_ActionSet, new() { if (SteamVR_Input.ShouldMakeCopy()) { return new CreateType { actionSetPath = actionSetPath, setData = setData, initialized = true }; } return (CreateType)this; } public bool Equals(SteamVR_ActionSet other) { if ((object)other == null) { return false; } return actionSetPath == other.actionSetPath; } public override bool Equals(object other) { if (other == null) { if (string.IsNullOrEmpty(actionSetPath)) { return true; } return false; } if (this == other) { return true; } if (other is SteamVR_ActionSet) { return Equals((SteamVR_ActionSet)other); } return false; } public override int GetHashCode() { if (actionSetPath == null) { return 0; } return actionSetPath.GetHashCode(); } public static bool operator !=(SteamVR_ActionSet set1, SteamVR_ActionSet set2) { return !(set1 == set2); } public static bool operator ==(SteamVR_ActionSet set1, SteamVR_ActionSet set2) { bool flag = (object)set1 == null || string.IsNullOrEmpty(set1.actionSetPath) || set1.GetActionSetData() == null; bool flag2 = (object)set2 == null || string.IsNullOrEmpty(set2.actionSetPath) || set2.GetActionSetData() == null; if (flag && flag2) { return true; } if (flag != flag2) { return false; } return set1.Equals(set2); } void ISerializationCallbackReceiver.OnBeforeSerialize() { } void ISerializationCallbackReceiver.OnAfterDeserialize() { if (setData != null && setData.fullPath != actionSetPath) { setData = SteamVR_Input.GetActionSetDataFromPath(actionSetPath); } if (!initialized) { Initialize(createNew: false, throwErrors: false); } } } public class SteamVR_ActionSet_Data : ISteamVR_ActionSet { protected bool[] rawSetActive = new bool[SteamVR_Input_Source.numSources]; protected float[] rawSetLastChanged = new float[SteamVR_Input_Source.numSources]; protected int[] rawSetPriority = new int[SteamVR_Input_Source.numSources]; protected bool initialized; private string cachedShortName; public SteamVR_Action[] allActions { get; set; } public ISteamVR_Action_In[] nonVisualInActions { get; set; } public ISteamVR_Action_In[] visualActions { get; set; } public SteamVR_Action_Pose[] poseActions { get; set; } public SteamVR_Action_Skeleton[] skeletonActions { get; set; } public ISteamVR_Action_Out[] outActionArray { get; set; } public string fullPath { get; set; } public string usage { get; set; } public ulong handle { get; set; } public void PreInitialize() { } public void FinishPreInitialize() { List<SteamVR_Action> list = new List<SteamVR_Action>(); List<ISteamVR_Action_In> list2 = new List<ISteamVR_Action_In>(); List<ISteamVR_Action_In> list3 = new List<ISteamVR_Action_In>(); List<SteamVR_Action_Pose> list4 = new List<SteamVR_Action_Pose>(); List<SteamVR_Action_Skeleton> list5 = new List<SteamVR_Action_Skeleton>(); List<ISteamVR_Action_Out> list6 = new List<ISteamVR_Action_Out>(); if (SteamVR_Input.actions == null) { Debug.LogError((object)"<b>[SteamVR Input]</b> Actions not initialized!"); return; } for (int i = 0; i < SteamVR_Input.actions.Length; i++) { SteamVR_Action steamVR_Action = SteamVR_Input.actions[i]; if (steamVR_Action.actionSet.GetActionSetData() == this) { list.Add(steamVR_Action); if (steamVR_Action is ISteamVR_Action_Boolean || steamVR_Action is ISteamVR_Action_Single || steamVR_Action is ISteamVR_Action_Vector2 || steamVR_Action is ISteamVR_Action_Vector3) { list2.Add((ISteamVR_Action_In)steamVR_Action); } else if (steamVR_Action is SteamVR_Action_Pose) { list3.Add((ISteamVR_Action_In)steamVR_Action); list4.Add((SteamVR_Action_Pose)steamVR_Action); } else if (steamVR_Action is SteamVR_Action_Skeleton) { list3.Ad
plugins/Valheim_Data/Managed/SteamVR_Actions.dll
Decompiled 5 months agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] namespace Valve.VR; public class SteamVR_Input_ActionSet_LaserPointers : SteamVR_ActionSet { public virtual SteamVR_Action_Boolean LeftClick => SteamVR_Actions.laserPointers_LeftClick; public virtual SteamVR_Action_Boolean RightClick => SteamVR_Actions.laserPointers_RightClick; public virtual SteamVR_Action_Boolean ClickModifier => SteamVR_Actions.laserPointers_ClickModifier; public virtual SteamVR_Action_Boolean Jump => SteamVR_Actions.laserPointers_Jump; public virtual SteamVR_Action_Vector2 PitchAndYaw => SteamVR_Actions.laserPointers_PitchAndYaw; } public class SteamVR_Input_ActionSet_Valheim : SteamVR_ActionSet { public virtual SteamVR_Action_Boolean ToggleInventory => SteamVR_Actions.valheim_ToggleInventory; public virtual SteamVR_Action_Boolean ToggleMenu => SteamVR_Actions.valheim_ToggleMenu; public virtual SteamVR_Action_Boolean Jump => SteamVR_Actions.valheim_Jump; public virtual SteamVR_Action_Boolean Use => SteamVR_Actions.valheim_Use; public virtual SteamVR_Action_Boolean Sit => SteamVR_Actions.valheim_Sit; public virtual SteamVR_Action_Vector2 PitchAndYaw => SteamVR_Actions.valheim_PitchAndYaw; public virtual SteamVR_Action_Pose PoseL => SteamVR_Actions.valheim_PoseL; public virtual SteamVR_Action_Pose PoseR => SteamVR_Actions.valheim_PoseR; public virtual SteamVR_Action_Boolean HotbarUp => SteamVR_Actions.valheim_HotbarUp; public virtual SteamVR_Action_Boolean HotbarDown => SteamVR_Actions.valheim_HotbarDown; public virtual SteamVR_Action_Vector2 HotbarScroll => SteamVR_Actions.valheim_HotbarScroll; public virtual SteamVR_Action_Boolean ToggleMap => SteamVR_Actions.valheim_ToggleMap; public virtual SteamVR_Action_Boolean HotbarUse => SteamVR_Actions.valheim_HotbarUse; public virtual SteamVR_Action_Vector2 ContextScroll => SteamVR_Actions.valheim_ContextScroll; public virtual SteamVR_Action_Boolean Grab => SteamVR_Actions.valheim_Grab; public virtual SteamVR_Action_Boolean QuickSwitch => SteamVR_Actions.valheim_QuickSwitch; public virtual SteamVR_Action_Vector2 Walk => SteamVR_Actions.valheim_Walk; public virtual SteamVR_Action_Boolean UseLeft => SteamVR_Actions.valheim_UseLeft; public virtual SteamVR_Action_Boolean QuickActions => SteamVR_Actions.valheim_QuickActions; public virtual SteamVR_Action_Vibration Haptic => SteamVR_Actions.valheim_Haptic; } public class SteamVR_Input_ActionSet_default : SteamVR_ActionSet { public virtual SteamVR_Action_Boolean InteractUI => SteamVR_Actions.default_InteractUI; public virtual SteamVR_Action_Boolean Teleport => SteamVR_Actions.default_Teleport; public virtual SteamVR_Action_Boolean GrabPinch => SteamVR_Actions.default_GrabPinch; public virtual SteamVR_Action_Boolean GrabGrip => SteamVR_Actions.default_GrabGrip; public virtual SteamVR_Action_Pose Pose => SteamVR_Actions.default_Pose; public virtual SteamVR_Action_Skeleton SkeletonLeftHand => SteamVR_Actions.default_SkeletonLeftHand; public virtual SteamVR_Action_Skeleton SkeletonRightHand => SteamVR_Actions.default_SkeletonRightHand; public virtual SteamVR_Action_Single Squeeze => SteamVR_Actions.default_Squeeze; public virtual SteamVR_Action_Boolean HeadsetOnHead => SteamVR_Actions.default_HeadsetOnHead; public virtual SteamVR_Action_Vibration Haptic => SteamVR_Actions.default_Haptic; } public class SteamVR_Actions { private static SteamVR_Input_ActionSet_default p__default; private static SteamVR_Input_ActionSet_Valheim p_Valheim; private static SteamVR_Input_ActionSet_LaserPointers p_LaserPointers; private static SteamVR_Action_Boolean p_default_InteractUI; private static SteamVR_Action_Boolean p_default_Teleport; private static SteamVR_Action_Boolean p_default_GrabPinch; private static SteamVR_Action_Boolean p_default_GrabGrip; private static SteamVR_Action_Pose p_default_Pose; private static SteamVR_Action_Skeleton p_default_SkeletonLeftHand; private static SteamVR_Action_Skeleton p_default_SkeletonRightHand; private static SteamVR_Action_Single p_default_Squeeze; private static SteamVR_Action_Boolean p_default_HeadsetOnHead; private static SteamVR_Action_Vibration p_default_Haptic; private static SteamVR_Action_Boolean p_valheim_ToggleInventory; private static SteamVR_Action_Boolean p_valheim_ToggleMenu; private static SteamVR_Action_Boolean p_valheim_Jump; private static SteamVR_Action_Boolean p_valheim_Use; private static SteamVR_Action_Boolean p_valheim_Sit; private static SteamVR_Action_Vector2 p_valheim_PitchAndYaw; private static SteamVR_Action_Pose p_valheim_PoseL; private static SteamVR_Action_Pose p_valheim_PoseR; private static SteamVR_Action_Boolean p_valheim_HotbarUp; private static SteamVR_Action_Boolean p_valheim_HotbarDown; private static SteamVR_Action_Vector2 p_valheim_HotbarScroll; private static SteamVR_Action_Boolean p_valheim_ToggleMap; private static SteamVR_Action_Boolean p_valheim_HotbarUse; private static SteamVR_Action_Vector2 p_valheim_ContextScroll; private static SteamVR_Action_Boolean p_valheim_Grab; private static SteamVR_Action_Boolean p_valheim_QuickSwitch; private static SteamVR_Action_Vector2 p_valheim_Walk; private static SteamVR_Action_Boolean p_valheim_UseLeft; private static SteamVR_Action_Boolean p_valheim_QuickActions; private static SteamVR_Action_Boolean p_valheim_StopGesturedLocomotion; private static SteamVR_Action_Vibration p_valheim_Haptic; private static SteamVR_Action_Boolean p_laserPointers_LeftClick; private static SteamVR_Action_Boolean p_laserPointers_RightClick; private static SteamVR_Action_Boolean p_laserPointers_ClickModifier; private static SteamVR_Action_Boolean p_laserPointers_Jump; private static SteamVR_Action_Vector2 p_laserPointers_PitchAndYaw; public static SteamVR_Input_ActionSet_default _default => ((SteamVR_ActionSet)p__default).GetCopy<SteamVR_Input_ActionSet_default>(); public static SteamVR_Input_ActionSet_Valheim Valheim => ((SteamVR_ActionSet)p_Valheim).GetCopy<SteamVR_Input_ActionSet_Valheim>(); public static SteamVR_Input_ActionSet_LaserPointers LaserPointers => ((SteamVR_ActionSet)p_LaserPointers).GetCopy<SteamVR_Input_ActionSet_LaserPointers>(); public static SteamVR_Action_Boolean default_InteractUI => ((SteamVR_Action)p_default_InteractUI).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean default_Teleport => ((SteamVR_Action)p_default_Teleport).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean default_GrabPinch => ((SteamVR_Action)p_default_GrabPinch).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean default_GrabGrip => ((SteamVR_Action)p_default_GrabGrip).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Pose default_Pose => ((SteamVR_Action)p_default_Pose).GetCopy<SteamVR_Action_Pose>(); public static SteamVR_Action_Skeleton default_SkeletonLeftHand => ((SteamVR_Action)p_default_SkeletonLeftHand).GetCopy<SteamVR_Action_Skeleton>(); public static SteamVR_Action_Skeleton default_SkeletonRightHand => ((SteamVR_Action)p_default_SkeletonRightHand).GetCopy<SteamVR_Action_Skeleton>(); public static SteamVR_Action_Single default_Squeeze => ((SteamVR_Action)p_default_Squeeze).GetCopy<SteamVR_Action_Single>(); public static SteamVR_Action_Boolean default_HeadsetOnHead => ((SteamVR_Action)p_default_HeadsetOnHead).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vibration default_Haptic => ((SteamVR_Action)p_default_Haptic).GetCopy<SteamVR_Action_Vibration>(); public static SteamVR_Action_Boolean valheim_ToggleInventory => ((SteamVR_Action)p_valheim_ToggleInventory).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_ToggleMenu => ((SteamVR_Action)p_valheim_ToggleMenu).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_Jump => ((SteamVR_Action)p_valheim_Jump).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_Use => ((SteamVR_Action)p_valheim_Use).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_Sit => ((SteamVR_Action)p_valheim_Sit).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vector2 valheim_PitchAndYaw => ((SteamVR_Action)p_valheim_PitchAndYaw).GetCopy<SteamVR_Action_Vector2>(); public static SteamVR_Action_Pose valheim_PoseL => ((SteamVR_Action)p_valheim_PoseL).GetCopy<SteamVR_Action_Pose>(); public static SteamVR_Action_Pose valheim_PoseR => ((SteamVR_Action)p_valheim_PoseR).GetCopy<SteamVR_Action_Pose>(); public static SteamVR_Action_Boolean valheim_HotbarUp => ((SteamVR_Action)p_valheim_HotbarUp).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_HotbarDown => ((SteamVR_Action)p_valheim_HotbarDown).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vector2 valheim_HotbarScroll => ((SteamVR_Action)p_valheim_HotbarScroll).GetCopy<SteamVR_Action_Vector2>(); public static SteamVR_Action_Boolean valheim_ToggleMap => ((SteamVR_Action)p_valheim_ToggleMap).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_HotbarUse => ((SteamVR_Action)p_valheim_HotbarUse).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vector2 valheim_ContextScroll => ((SteamVR_Action)p_valheim_ContextScroll).GetCopy<SteamVR_Action_Vector2>(); public static SteamVR_Action_Boolean valheim_Grab => ((SteamVR_Action)p_valheim_Grab).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_QuickSwitch => ((SteamVR_Action)p_valheim_QuickSwitch).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vector2 valheim_Walk => ((SteamVR_Action)p_valheim_Walk).GetCopy<SteamVR_Action_Vector2>(); public static SteamVR_Action_Boolean valheim_UseLeft => ((SteamVR_Action)p_valheim_UseLeft).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_QuickActions => ((SteamVR_Action)p_valheim_QuickActions).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean valheim_StopGesturedLocomotion => ((SteamVR_Action)p_valheim_StopGesturedLocomotion).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vibration valheim_Haptic => ((SteamVR_Action)p_valheim_Haptic).GetCopy<SteamVR_Action_Vibration>(); public static SteamVR_Action_Boolean laserPointers_LeftClick => ((SteamVR_Action)p_laserPointers_LeftClick).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean laserPointers_RightClick => ((SteamVR_Action)p_laserPointers_RightClick).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean laserPointers_ClickModifier => ((SteamVR_Action)p_laserPointers_ClickModifier).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Boolean laserPointers_Jump => ((SteamVR_Action)p_laserPointers_Jump).GetCopy<SteamVR_Action_Boolean>(); public static SteamVR_Action_Vector2 laserPointers_PitchAndYaw => ((SteamVR_Action)p_laserPointers_PitchAndYaw).GetCopy<SteamVR_Action_Vector2>(); private static void StartPreInitActionSets() { p__default = SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_default>("/actions/default"); p_Valheim = SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_Valheim>("/actions/Valheim"); p_LaserPointers = SteamVR_ActionSet.Create<SteamVR_Input_ActionSet_LaserPointers>("/actions/LaserPointers"); SteamVR_Input.actionSets = (SteamVR_ActionSet[])(object)new SteamVR_ActionSet[3] { _default, Valheim, LaserPointers }; } private static void InitializeActionArrays() { SteamVR_Input.actions = (SteamVR_Action[])(object)new SteamVR_Action[36] { (SteamVR_Action)default_InteractUI, (SteamVR_Action)default_Teleport, (SteamVR_Action)default_GrabPinch, (SteamVR_Action)default_GrabGrip, (SteamVR_Action)default_Pose, (SteamVR_Action)default_SkeletonLeftHand, (SteamVR_Action)default_SkeletonRightHand, (SteamVR_Action)default_Squeeze, (SteamVR_Action)default_HeadsetOnHead, (SteamVR_Action)default_Haptic, (SteamVR_Action)valheim_ToggleInventory, (SteamVR_Action)valheim_ToggleMenu, (SteamVR_Action)valheim_Jump, (SteamVR_Action)valheim_Use, (SteamVR_Action)valheim_Sit, (SteamVR_Action)valheim_PitchAndYaw, (SteamVR_Action)valheim_PoseL, (SteamVR_Action)valheim_PoseR, (SteamVR_Action)valheim_HotbarUp, (SteamVR_Action)valheim_HotbarDown, (SteamVR_Action)valheim_HotbarScroll, (SteamVR_Action)valheim_ToggleMap, (SteamVR_Action)valheim_HotbarUse, (SteamVR_Action)valheim_ContextScroll, (SteamVR_Action)valheim_Grab, (SteamVR_Action)valheim_QuickSwitch, (SteamVR_Action)valheim_Walk, (SteamVR_Action)valheim_UseLeft, (SteamVR_Action)valheim_QuickActions, (SteamVR_Action)valheim_StopGesturedLocomotion, (SteamVR_Action)valheim_Haptic, (SteamVR_Action)laserPointers_LeftClick, (SteamVR_Action)laserPointers_RightClick, (SteamVR_Action)laserPointers_ClickModifier, (SteamVR_Action)laserPointers_Jump, (SteamVR_Action)laserPointers_PitchAndYaw }; SteamVR_Input.actionsIn = (ISteamVR_Action_In[])(object)new ISteamVR_Action_In[34] { (ISteamVR_Action_In)default_InteractUI, (ISteamVR_Action_In)default_Teleport, (ISteamVR_Action_In)default_GrabPinch, (ISteamVR_Action_In)default_GrabGrip, (ISteamVR_Action_In)default_Pose, (ISteamVR_Action_In)default_SkeletonLeftHand, (ISteamVR_Action_In)default_SkeletonRightHand, (ISteamVR_Action_In)default_Squeeze, (ISteamVR_Action_In)default_HeadsetOnHead, (ISteamVR_Action_In)valheim_ToggleInventory, (ISteamVR_Action_In)valheim_ToggleMenu, (ISteamVR_Action_In)valheim_Jump, (ISteamVR_Action_In)valheim_Use, (ISteamVR_Action_In)valheim_Sit, (ISteamVR_Action_In)valheim_PitchAndYaw, (ISteamVR_Action_In)valheim_PoseL, (ISteamVR_Action_In)valheim_PoseR, (ISteamVR_Action_In)valheim_HotbarUp, (ISteamVR_Action_In)valheim_HotbarDown, (ISteamVR_Action_In)valheim_HotbarScroll, (ISteamVR_Action_In)valheim_ToggleMap, (ISteamVR_Action_In)valheim_HotbarUse, (ISteamVR_Action_In)valheim_ContextScroll, (ISteamVR_Action_In)valheim_Grab, (ISteamVR_Action_In)valheim_QuickSwitch, (ISteamVR_Action_In)valheim_Walk, (ISteamVR_Action_In)valheim_UseLeft, (ISteamVR_Action_In)valheim_QuickActions, (ISteamVR_Action_In)valheim_StopGesturedLocomotion, (ISteamVR_Action_In)laserPointers_LeftClick, (ISteamVR_Action_In)laserPointers_RightClick, (ISteamVR_Action_In)laserPointers_ClickModifier, (ISteamVR_Action_In)laserPointers_Jump, (ISteamVR_Action_In)laserPointers_PitchAndYaw }; SteamVR_Input.actionsOut = (ISteamVR_Action_Out[])(object)new ISteamVR_Action_Out[2] { (ISteamVR_Action_Out)default_Haptic, (ISteamVR_Action_Out)valheim_Haptic }; SteamVR_Input.actionsVibration = (SteamVR_Action_Vibration[])(object)new SteamVR_Action_Vibration[2] { default_Haptic, valheim_Haptic }; SteamVR_Input.actionsPose = (SteamVR_Action_Pose[])(object)new SteamVR_Action_Pose[3] { default_Pose, valheim_PoseL, valheim_PoseR }; SteamVR_Input.actionsBoolean = (SteamVR_Action_Boolean[])(object)new SteamVR_Action_Boolean[23] { default_InteractUI, default_Teleport, default_GrabPinch, default_GrabGrip, default_HeadsetOnHead, valheim_ToggleInventory, valheim_ToggleMenu, valheim_Jump, valheim_Use, valheim_Sit, valheim_HotbarUp, valheim_HotbarDown, valheim_ToggleMap, valheim_HotbarUse, valheim_Grab, valheim_QuickSwitch, valheim_UseLeft, valheim_QuickActions, valheim_StopGesturedLocomotion, laserPointers_LeftClick, laserPointers_RightClick, laserPointers_ClickModifier, laserPointers_Jump }; SteamVR_Input.actionsSingle = (SteamVR_Action_Single[])(object)new SteamVR_Action_Single[1] { default_Squeeze }; SteamVR_Input.actionsVector2 = (SteamVR_Action_Vector2[])(object)new SteamVR_Action_Vector2[5] { valheim_PitchAndYaw, valheim_HotbarScroll, valheim_ContextScroll, valheim_Walk, laserPointers_PitchAndYaw }; SteamVR_Input.actionsVector3 = (SteamVR_Action_Vector3[])(object)new SteamVR_Action_Vector3[0]; SteamVR_Input.actionsSkeleton = (SteamVR_Action_Skeleton[])(object)new SteamVR_Action_Skeleton[2] { default_SkeletonLeftHand, default_SkeletonRightHand }; SteamVR_Input.actionsNonPoseNonSkeletonIn = (ISteamVR_Action_In[])(object)new ISteamVR_Action_In[29] { (ISteamVR_Action_In)default_InteractUI, (ISteamVR_Action_In)default_Teleport, (ISteamVR_Action_In)default_GrabPinch, (ISteamVR_Action_In)default_GrabGrip, (ISteamVR_Action_In)default_Squeeze, (ISteamVR_Action_In)default_HeadsetOnHead, (ISteamVR_Action_In)valheim_ToggleInventory, (ISteamVR_Action_In)valheim_ToggleMenu, (ISteamVR_Action_In)valheim_Jump, (ISteamVR_Action_In)valheim_Use, (ISteamVR_Action_In)valheim_Sit, (ISteamVR_Action_In)valheim_PitchAndYaw, (ISteamVR_Action_In)valheim_HotbarUp, (ISteamVR_Action_In)valheim_HotbarDown, (ISteamVR_Action_In)valheim_HotbarScroll, (ISteamVR_Action_In)valheim_ToggleMap, (ISteamVR_Action_In)valheim_HotbarUse, (ISteamVR_Action_In)valheim_ContextScroll, (ISteamVR_Action_In)valheim_Grab, (ISteamVR_Action_In)valheim_QuickSwitch, (ISteamVR_Action_In)valheim_Walk, (ISteamVR_Action_In)valheim_UseLeft, (ISteamVR_Action_In)valheim_QuickActions, (ISteamVR_Action_In)valheim_StopGesturedLocomotion, (ISteamVR_Action_In)laserPointers_LeftClick, (ISteamVR_Action_In)laserPointers_RightClick, (ISteamVR_Action_In)laserPointers_ClickModifier, (ISteamVR_Action_In)laserPointers_Jump, (ISteamVR_Action_In)laserPointers_PitchAndYaw }; } private static void PreInitActions() { p_default_InteractUI = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/default/in/InteractUI"); p_default_Teleport = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/default/in/Teleport"); p_default_GrabPinch = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/default/in/GrabPinch"); p_default_GrabGrip = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/default/in/GrabGrip"); p_default_Pose = SteamVR_Action.Create<SteamVR_Action_Pose>("/actions/default/in/Pose"); p_default_SkeletonLeftHand = SteamVR_Action.Create<SteamVR_Action_Skeleton>("/actions/default/in/SkeletonLeftHand"); p_default_SkeletonRightHand = SteamVR_Action.Create<SteamVR_Action_Skeleton>("/actions/default/in/SkeletonRightHand"); p_default_Squeeze = SteamVR_Action.Create<SteamVR_Action_Single>("/actions/default/in/Squeeze"); p_default_HeadsetOnHead = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/default/in/HeadsetOnHead"); p_default_Haptic = SteamVR_Action.Create<SteamVR_Action_Vibration>("/actions/default/out/Haptic"); p_valheim_ToggleInventory = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/ToggleInventory"); p_valheim_ToggleMenu = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/ToggleMenu"); p_valheim_Jump = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/Jump"); p_valheim_Use = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/Use"); p_valheim_Sit = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/Sit"); p_valheim_PitchAndYaw = SteamVR_Action.Create<SteamVR_Action_Vector2>("/actions/Valheim/in/PitchAndYaw"); p_valheim_PoseL = SteamVR_Action.Create<SteamVR_Action_Pose>("/actions/Valheim/in/PoseL"); p_valheim_PoseR = SteamVR_Action.Create<SteamVR_Action_Pose>("/actions/Valheim/in/PoseR"); p_valheim_HotbarUp = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/HotbarUp"); p_valheim_HotbarDown = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/HotbarDown"); p_valheim_HotbarScroll = SteamVR_Action.Create<SteamVR_Action_Vector2>("/actions/Valheim/in/HotbarScroll"); p_valheim_ToggleMap = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/ToggleMap"); p_valheim_HotbarUse = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/HotbarUse"); p_valheim_ContextScroll = SteamVR_Action.Create<SteamVR_Action_Vector2>("/actions/Valheim/in/ContextScroll"); p_valheim_Grab = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/Grab"); p_valheim_QuickSwitch = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/QuickSwitch"); p_valheim_Walk = SteamVR_Action.Create<SteamVR_Action_Vector2>("/actions/Valheim/in/Walk"); p_valheim_UseLeft = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/UseLeft"); p_valheim_QuickActions = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/QuickActions"); p_valheim_StopGesturedLocomotion = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/Valheim/in/StopGesturedLocomotion"); p_valheim_Haptic = SteamVR_Action.Create<SteamVR_Action_Vibration>("/actions/Valheim/out/Haptic"); p_laserPointers_LeftClick = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/LaserPointers/in/LeftClick"); p_laserPointers_RightClick = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/LaserPointers/in/RightClick"); p_laserPointers_ClickModifier = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/LaserPointers/in/ClickModifier"); p_laserPointers_Jump = SteamVR_Action.Create<SteamVR_Action_Boolean>("/actions/LaserPointers/in/Jump"); p_laserPointers_PitchAndYaw = SteamVR_Action.Create<SteamVR_Action_Vector2>("/actions/LaserPointers/in/PitchAndYaw"); } public static void PreInitialize() { StartPreInitActionSets(); SteamVR_Input.PreinitializeActionSetDictionaries(); PreInitActions(); InitializeActionArrays(); SteamVR_Input.PreinitializeActionDictionaries(); SteamVR_Input.PreinitializeFinishActionSets(); } }
plugins/Valheim_Data/Managed/Unity.XR.Management.dll
Decompiled 5 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine.Rendering; using UnityEngine.Serialization; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Unity.XR.Management.Tests")] [assembly: InternalsVisibleTo("Unity.XR.Management.EditorTests")] [assembly: AssemblyVersion("0.0.0.0")] namespace UnityEngine.XR.Management; [AttributeUsage(AttributeTargets.Class)] public sealed class XRConfigurationDataAttribute : Attribute { public string displayName { get; set; } public string buildSettingsKey { get; set; } private XRConfigurationDataAttribute() { } public XRConfigurationDataAttribute(string displayName, string buildSettingsKey) { this.displayName = displayName; this.buildSettingsKey = buildSettingsKey; } } public class XRGeneralSettings : ScriptableObject { public static string k_SettingsKey = "com.unity.xr.management.loader_settings"; internal static XRGeneralSettings s_RuntimeSettingsInstance = null; [SerializeField] internal XRManagerSettings m_LoaderManagerInstance; [SerializeField] [Tooltip("Toggling this on/off will enable/disable the automatic startup of XR at run time.")] internal bool m_InitManagerOnStart = true; private XRManagerSettings m_XRManager; private bool m_ProviderIntialized; private bool m_ProviderStarted; public XRManagerSettings Manager { get { return m_LoaderManagerInstance; } set { m_LoaderManagerInstance = value; } } public static XRGeneralSettings Instance => s_RuntimeSettingsInstance; public XRManagerSettings AssignedSettings => m_LoaderManagerInstance; public bool InitManagerOnStart => m_InitManagerOnStart; private void Awake() { Debug.Log((object)"XRGeneral Settings awakening..."); s_RuntimeSettingsInstance = this; Application.quitting += Quit; Object.DontDestroyOnLoad((Object)(object)s_RuntimeSettingsInstance); } private static void Quit() { XRGeneralSettings instance = Instance; if (!((Object)(object)instance == (Object)null)) { instance.DeInitXRSDK(); } } private void Start() { StartXRSDK(); } private void OnDestroy() { DeInitXRSDK(); } [RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)] internal static void AttemptInitializeXRSDKOnLoad() { XRGeneralSettings instance = Instance; if (!((Object)(object)instance == (Object)null) && instance.InitManagerOnStart) { instance.InitXRSDK(); } } [RuntimeInitializeOnLoadMethod(/*Could not decode attribute arguments.*/)] internal static void AttemptStartXRSDKOnBeforeSplashScreen() { XRGeneralSettings instance = Instance; if (!((Object)(object)instance == (Object)null) && instance.InitManagerOnStart) { instance.StartXRSDK(); } } private void InitXRSDK() { if (!((Object)(object)Instance == (Object)null) && !((Object)(object)Instance.m_LoaderManagerInstance == (Object)null) && Instance.m_InitManagerOnStart) { m_XRManager = Instance.m_LoaderManagerInstance; if ((Object)(object)m_XRManager == (Object)null) { Debug.LogError((object)"Assigned GameObject for XR Management loading is invalid. No XR Providers will be automatically loaded."); return; } m_XRManager.automaticLoading = false; m_XRManager.automaticRunning = false; m_XRManager.InitializeLoaderSync(); m_ProviderIntialized = true; } } private void StartXRSDK() { if ((Object)(object)m_XRManager != (Object)null && (Object)(object)m_XRManager.activeLoader != (Object)null) { m_XRManager.StartSubsystems(); m_ProviderStarted = true; } } private void StopXRSDK() { if ((Object)(object)m_XRManager != (Object)null && (Object)(object)m_XRManager.activeLoader != (Object)null) { m_XRManager.StopSubsystems(); m_ProviderStarted = false; } } private void DeInitXRSDK() { if ((Object)(object)m_XRManager != (Object)null && (Object)(object)m_XRManager.activeLoader != (Object)null) { m_XRManager.DeinitializeLoader(); m_XRManager = null; m_ProviderIntialized = false; } } } public abstract class XRLoader : ScriptableObject { public virtual bool Initialize() { return true; } public virtual bool Start() { return true; } public virtual bool Stop() { return true; } public virtual bool Deinitialize() { return true; } public abstract T GetLoadedSubsystem<T>() where T : class, ISubsystem; public virtual List<GraphicsDeviceType> GetSupportedGraphicsDeviceTypes(bool buildingPlayer) { return new List<GraphicsDeviceType>(); } } public abstract class XRLoaderHelper : XRLoader { protected Dictionary<Type, ISubsystem> m_SubsystemInstanceMap = new Dictionary<Type, ISubsystem>(); public override T GetLoadedSubsystem<T>() { Type typeFromHandle = typeof(T); m_SubsystemInstanceMap.TryGetValue(typeFromHandle, out var value); return value as T; } protected void StartSubsystem<T>() where T : class, ISubsystem { T loadedSubsystem = GetLoadedSubsystem<T>(); if (loadedSubsystem != null) { ((ISubsystem)loadedSubsystem).Start(); } } protected void StopSubsystem<T>() where T : class, ISubsystem { T loadedSubsystem = GetLoadedSubsystem<T>(); if (loadedSubsystem != null) { ((ISubsystem)loadedSubsystem).Stop(); } } protected void DestroySubsystem<T>() where T : class, ISubsystem { T loadedSubsystem = GetLoadedSubsystem<T>(); if (loadedSubsystem != null) { ((ISubsystem)loadedSubsystem).Destroy(); } } protected void CreateSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id) where TDescriptor : ISubsystemDescriptor where TSubsystem : ISubsystem { if (descriptors == null) { throw new ArgumentNullException("descriptors"); } SubsystemManager.GetSubsystemDescriptors<TDescriptor>(descriptors); if (descriptors.Count <= 0) { return; } foreach (TDescriptor descriptor in descriptors) { ISubsystem val = null; if (string.Compare(((ISubsystemDescriptor)descriptor).id, id, ignoreCase: true) == 0) { val = ((ISubsystemDescriptor)descriptor).Create(); } if (val != null) { m_SubsystemInstanceMap[typeof(TSubsystem)] = val; break; } } } [Obsolete("This method is obsolete. Please use the geenric CreateSubsystem method.", false)] protected void CreateIntegratedSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id) where TDescriptor : IntegratedSubsystemDescriptor where TSubsystem : IntegratedSubsystem { CreateSubsystem<TDescriptor, TSubsystem>(descriptors, id); } [Obsolete("This method is obsolete. Please use the generic CreateSubsystem method.", false)] protected void CreateStandaloneSubsystem<TDescriptor, TSubsystem>(List<TDescriptor> descriptors, string id) where TDescriptor : SubsystemDescriptor where TSubsystem : Subsystem { CreateSubsystem<TDescriptor, TSubsystem>(descriptors, id); } public override bool Deinitialize() { m_SubsystemInstanceMap.Clear(); return base.Deinitialize(); } } public sealed class XRManagerSettings : ScriptableObject { [HideInInspector] private bool m_InitializationComplete; [HideInInspector] [SerializeField] private bool m_RequiresSettingsUpdate; [SerializeField] [Tooltip("Determines if the XR Manager instance is responsible for creating and destroying the appropriate loader instance.")] [FormerlySerializedAs("AutomaticLoading")] private bool m_AutomaticLoading; [SerializeField] [Tooltip("Determines if the XR Manager instance is responsible for starting and stopping subsystems for the active loader instance.")] [FormerlySerializedAs("AutomaticRunning")] private bool m_AutomaticRunning; [SerializeField] [Tooltip("List of XR Loader instances arranged in desired load order.")] [FormerlySerializedAs("Loaders")] private List<XRLoader> m_Loaders = new List<XRLoader>(); [SerializeField] [HideInInspector] private HashSet<XRLoader> m_RegisteredLoaders = new HashSet<XRLoader>(); public bool automaticLoading { get { return m_AutomaticLoading; } set { m_AutomaticLoading = value; } } public bool automaticRunning { get { return m_AutomaticRunning; } set { m_AutomaticRunning = value; } } [Obsolete("'XRManagerSettings.loaders' property is obsolete. Use 'XRManagerSettings.activeLoaders' instead to get a list of the current loaders.")] public List<XRLoader> loaders => m_Loaders; public IReadOnlyList<XRLoader> activeLoaders => m_Loaders; public bool isInitializationComplete => m_InitializationComplete; [HideInInspector] public XRLoader activeLoader { get; private set; } internal List<XRLoader> currentLoaders { get { return m_Loaders; } set { m_Loaders = value; } } internal HashSet<XRLoader> registeredLoaders => m_RegisteredLoaders; public T ActiveLoaderAs<T>() where T : XRLoader { return activeLoader as T; } public void InitializeLoaderSync() { if ((Object)(object)activeLoader != (Object)null) { Debug.LogWarning((object)"XR Management has already initialized an active loader in this scene.Please make sure to stop all subsystems and deinitialize the active loader before initializing a new one."); return; } foreach (XRLoader currentLoader in currentLoaders) { if ((Object)(object)currentLoader != (Object)null && CheckGraphicsAPICompatibility(currentLoader) && currentLoader.Initialize()) { activeLoader = currentLoader; m_InitializationComplete = true; return; } } activeLoader = null; } public IEnumerator InitializeLoader() { if ((Object)(object)activeLoader != (Object)null) { Debug.LogWarning((object)"XR Management has already initialized an active loader in this scene.Please make sure to stop all subsystems and deinitialize the active loader before initializing a new one."); yield break; } foreach (XRLoader currentLoader in currentLoaders) { if ((Object)(object)currentLoader != (Object)null && CheckGraphicsAPICompatibility(currentLoader) && currentLoader.Initialize()) { activeLoader = currentLoader; m_InitializationComplete = true; yield break; } yield return null; } activeLoader = null; } private bool CheckLoaderRegistration(XRLoader loader) { if (m_RegisteredLoaders.Contains(loader)) { return !currentLoaders.Contains(loader); } return false; } public bool TryAddLoader(XRLoader loader, int index = -1) { if ((Object)(object)loader == (Object)null || !CheckLoaderRegistration(loader)) { return false; } if (index < 0 || index >= currentLoaders.Count) { currentLoaders.Add(loader); } else { currentLoaders.Insert(index, loader); } return true; } public bool TryRemoveLoader(XRLoader loader) { if (currentLoaders.Contains(loader)) { return currentLoaders.Remove(loader); } return true; } public bool TrySetLoaders(List<XRLoader> reorderedLoaders) { List<XRLoader> list = new List<XRLoader>(activeLoaders); currentLoaders.Clear(); foreach (XRLoader reorderedLoader in reorderedLoaders) { if (!TryAddLoader(reorderedLoader)) { currentLoaders = list; return false; } } return true; } private bool CheckGraphicsAPICompatibility(XRLoader loader) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: 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) GraphicsDeviceType graphicsDeviceType = SystemInfo.graphicsDeviceType; List<GraphicsDeviceType> supportedGraphicsDeviceTypes = loader.GetSupportedGraphicsDeviceTypes(buildingPlayer: false); if (supportedGraphicsDeviceTypes.Count > 0 && !supportedGraphicsDeviceTypes.Contains(graphicsDeviceType)) { Debug.LogWarning((object)$"The {((Object)loader).name} does not support the initialized graphics device, {((object)(GraphicsDeviceType)(ref graphicsDeviceType)).ToString()}. Please change the preffered Graphics API in PlayerSettings. Attempting to start the next XR loader."); return false; } return true; } public void StartSubsystems() { if (!m_InitializationComplete) { Debug.LogWarning((object)"Call to StartSubsystems without an initialized manager.Please make sure wait for initialization to complete before calling this API."); } else if ((Object)(object)activeLoader != (Object)null) { activeLoader.Start(); } } public void StopSubsystems() { if (!m_InitializationComplete) { Debug.LogWarning((object)"Call to StopSubsystems without an initialized manager.Please make sure wait for initialization to complete before calling this API."); } else if ((Object)(object)activeLoader != (Object)null) { activeLoader.Stop(); } } public void DeinitializeLoader() { if (!m_InitializationComplete) { Debug.LogWarning((object)"Call to DeinitializeLoader without an initialized manager.Please make sure wait for initialization to complete before calling this API."); return; } StopSubsystems(); if ((Object)(object)activeLoader != (Object)null) { activeLoader.Deinitialize(); activeLoader = null; } m_InitializationComplete = false; } private void Start() { if (automaticLoading && automaticRunning) { StartSubsystems(); } } private void OnDisable() { if (automaticLoading && automaticRunning) { StopSubsystems(); } } private void OnDestroy() { if (automaticLoading) { DeinitializeLoader(); } } }
plugins/Valheim_Data/Managed/Unity.XR.OpenVR.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; 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.Text; using System.Text.RegularExpressions; using AOT; using UnityEngine; using UnityEngine.Events; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.XR; using UnityEngine.XR; using UnityEngine.XR.Management; using Valve.VR; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyVersion("0.0.0.0")] namespace Valve.VR { public struct IVRSystem { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetRecommendedRenderTargetSize(ref uint pnWidth, ref uint pnHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdMatrix44_t _GetProjectionMatrix(EVREye eEye, float fNearZ, float fFarZ); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetProjectionRaw(EVREye eEye, ref float pfLeft, ref float pfRight, ref float pfTop, ref float pfBottom); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ComputeDistortion(EVREye eEye, float fU, float fV, ref DistortionCoordinates_t pDistortionCoordinates); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdMatrix34_t _GetEyeToHeadTransform(EVREye eEye); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetTimeSinceLastVsync(ref float pfSecondsSinceLastVsync, ref ulong pulFrameCounter); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate int _GetD3D9AdapterIndex(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetDXGIOutputInfo(ref int pnAdapterIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetOutputDevice(ref ulong pnDevice, ETextureType textureType, IntPtr pInstance); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsDisplayOnDesktop(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _SetDisplayVisibility(bool bIsVisibleOnDesktop); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin eOrigin, float fPredictedSecondsToPhotonsFromNow, [In][Out] TrackedDevicePose_t[] pTrackedDevicePoseArray, uint unTrackedDevicePoseArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdMatrix34_t _GetSeatedZeroPoseToStandingAbsoluteTrackingPose(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdMatrix34_t _GetRawZeroPoseToStandingAbsoluteTrackingPose(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetSortedTrackedDeviceIndicesOfClass(ETrackedDeviceClass eTrackedDeviceClass, [In][Out] uint[] punTrackedDeviceIndexArray, uint unTrackedDeviceIndexArrayCount, uint unRelativeToTrackedDeviceIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EDeviceActivityLevel _GetTrackedDeviceActivityLevel(uint unDeviceId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ApplyTransform(ref TrackedDevicePose_t pOutputPose, ref TrackedDevicePose_t pTrackedDevicePose, ref HmdMatrix34_t pTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedControllerRole _GetControllerRoleForTrackedDeviceIndex(uint unDeviceIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedDeviceClass _GetTrackedDeviceClass(uint unDeviceIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsTrackedDeviceConnected(uint unDeviceIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetBoolTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate float _GetFloatTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate int _GetInt32TrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _GetUint64TrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdMatrix34_t _GetMatrix34TrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetArrayTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, uint propType, IntPtr pBuffer, uint unBufferSize, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetStringTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, StringBuilder pchValue, uint unBufferSize, ref ETrackedPropertyError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetPropErrorNameFromEnum(ETrackedPropertyError error); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _PollNextEvent(ref VREvent_t pEvent, uint uncbVREvent); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _PollNextEventWithPose(ETrackingUniverseOrigin eOrigin, ref VREvent_t pEvent, uint uncbVREvent, ref TrackedDevicePose_t pTrackedDevicePose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetEventTypeNameFromEnum(EVREventType eType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HiddenAreaMesh_t _GetHiddenAreaMesh(EVREye eEye, EHiddenAreaMeshType type); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetControllerState(uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin, uint unControllerDeviceIndex, ref VRControllerState_t pControllerState, uint unControllerStateSize, ref TrackedDevicePose_t pTrackedDevicePose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _TriggerHapticPulse(uint unControllerDeviceIndex, uint unAxisId, ushort usDurationMicroSec); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetButtonIdNameFromEnum(EVRButtonId eButtonId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetControllerAxisTypeNameFromEnum(EVRControllerAxisType eAxisType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsInputAvailable(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsSteamVRDrawingControllers(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ShouldApplicationPause(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ShouldApplicationReduceRenderingWork(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRFirmwareError _PerformFirmwareUpdate(uint unDeviceIndex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _AcknowledgeQuit_Exiting(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetAppContainerFilePaths(StringBuilder pchBuffer, uint unBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetRuntimeVersion(); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRecommendedRenderTargetSize GetRecommendedRenderTargetSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetProjectionMatrix GetProjectionMatrix; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetProjectionRaw GetProjectionRaw; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ComputeDistortion ComputeDistortion; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetEyeToHeadTransform GetEyeToHeadTransform; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTimeSinceLastVsync GetTimeSinceLastVsync; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetD3D9AdapterIndex GetD3D9AdapterIndex; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDXGIOutputInfo GetDXGIOutputInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOutputDevice GetOutputDevice; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsDisplayOnDesktop IsDisplayOnDesktop; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetDisplayVisibility SetDisplayVisibility; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDeviceToAbsoluteTrackingPose GetDeviceToAbsoluteTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSeatedZeroPoseToStandingAbsoluteTrackingPose GetSeatedZeroPoseToStandingAbsoluteTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRawZeroPoseToStandingAbsoluteTrackingPose GetRawZeroPoseToStandingAbsoluteTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSortedTrackedDeviceIndicesOfClass GetSortedTrackedDeviceIndicesOfClass; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTrackedDeviceActivityLevel GetTrackedDeviceActivityLevel; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ApplyTransform ApplyTransform; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTrackedDeviceIndexForControllerRole GetTrackedDeviceIndexForControllerRole; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetControllerRoleForTrackedDeviceIndex GetControllerRoleForTrackedDeviceIndex; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTrackedDeviceClass GetTrackedDeviceClass; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsTrackedDeviceConnected IsTrackedDeviceConnected; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBoolTrackedDeviceProperty GetBoolTrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFloatTrackedDeviceProperty GetFloatTrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetInt32TrackedDeviceProperty GetInt32TrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetUint64TrackedDeviceProperty GetUint64TrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetMatrix34TrackedDeviceProperty GetMatrix34TrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetArrayTrackedDeviceProperty GetArrayTrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetStringTrackedDeviceProperty GetStringTrackedDeviceProperty; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPropErrorNameFromEnum GetPropErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PollNextEvent PollNextEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PollNextEventWithPose PollNextEventWithPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetEventTypeNameFromEnum GetEventTypeNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHiddenAreaMesh GetHiddenAreaMesh; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetControllerState GetControllerState; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetControllerStateWithPose GetControllerStateWithPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _TriggerHapticPulse TriggerHapticPulse; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetButtonIdNameFromEnum GetButtonIdNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetControllerAxisTypeNameFromEnum GetControllerAxisTypeNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsInputAvailable IsInputAvailable; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsSteamVRDrawingControllers IsSteamVRDrawingControllers; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShouldApplicationPause ShouldApplicationPause; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShouldApplicationReduceRenderingWork ShouldApplicationReduceRenderingWork; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PerformFirmwareUpdate PerformFirmwareUpdate; [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcknowledgeQuit_Exiting AcknowledgeQuit_Exiting; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetAppContainerFilePaths GetAppContainerFilePaths; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRuntimeVersion GetRuntimeVersion; } public struct IVRExtendedDisplay { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetWindowBounds(ref int pnX, ref int pnY, ref uint pnWidth, ref uint pnHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetEyeOutputViewport(EVREye eEye, ref uint pnX, ref uint pnY, ref uint pnWidth, ref uint pnHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetDXGIOutputInfo(ref int pnAdapterIndex, ref int pnAdapterOutputIndex); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWindowBounds GetWindowBounds; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetEyeOutputViewport GetEyeOutputViewport; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDXGIOutputInfo GetDXGIOutputInfo; } public struct IVRTrackedCamera { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetCameraErrorNameFromEnum(EVRTrackedCameraError eCameraError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _HasCamera(uint nDeviceIndex, ref bool pHasCamera); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetCameraFrameSize(uint nDeviceIndex, EVRTrackedCameraFrameType eFrameType, ref uint pnWidth, ref uint pnHeight, ref uint pnFrameBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetCameraIntrinsics(uint nDeviceIndex, uint nCameraIndex, EVRTrackedCameraFrameType eFrameType, ref HmdVector2_t pFocalLength, ref HmdVector2_t pCenter); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetCameraProjection(uint nDeviceIndex, uint nCameraIndex, EVRTrackedCameraFrameType eFrameType, float flZNear, float flZFar, ref HmdMatrix44_t pProjection); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _AcquireVideoStreamingService(uint nDeviceIndex, ref ulong pHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _ReleaseVideoStreamingService(ulong hTrackedCamera); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetVideoStreamFrameBuffer(ulong hTrackedCamera, EVRTrackedCameraFrameType eFrameType, IntPtr pFrameBuffer, uint nFrameBufferSize, ref CameraVideoStreamFrameHeader_t pFrameHeader, uint nFrameHeaderSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetVideoStreamTextureSize(uint nDeviceIndex, EVRTrackedCameraFrameType eFrameType, ref VRTextureBounds_t pTextureBounds, ref uint pnWidth, ref uint pnHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetVideoStreamTextureD3D11(ulong hTrackedCamera, EVRTrackedCameraFrameType eFrameType, IntPtr pD3D11DeviceOrResource, ref IntPtr ppD3D11ShaderResourceView, ref CameraVideoStreamFrameHeader_t pFrameHeader, uint nFrameHeaderSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _GetVideoStreamTextureGL(ulong hTrackedCamera, EVRTrackedCameraFrameType eFrameType, ref uint pglTextureId, ref CameraVideoStreamFrameHeader_t pFrameHeader, uint nFrameHeaderSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRTrackedCameraError _ReleaseVideoStreamTextureGL(ulong hTrackedCamera, uint glTextureId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetCameraTrackingSpace(ETrackingUniverseOrigin eUniverse); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackingUniverseOrigin _GetCameraTrackingSpace(); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraErrorNameFromEnum GetCameraErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HasCamera HasCamera; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraFrameSize GetCameraFrameSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraIntrinsics GetCameraIntrinsics; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraProjection GetCameraProjection; [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcquireVideoStreamingService AcquireVideoStreamingService; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseVideoStreamingService ReleaseVideoStreamingService; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVideoStreamFrameBuffer GetVideoStreamFrameBuffer; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVideoStreamTextureSize GetVideoStreamTextureSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVideoStreamTextureD3D11 GetVideoStreamTextureD3D11; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVideoStreamTextureGL GetVideoStreamTextureGL; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseVideoStreamTextureGL ReleaseVideoStreamTextureGL; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetCameraTrackingSpace SetCameraTrackingSpace; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraTrackingSpace GetCameraTrackingSpace; } public struct IVRApplications { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _AddApplicationManifest(IntPtr pchApplicationManifestFullPath, bool bTemporary); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _RemoveApplicationManifest(IntPtr pchApplicationManifestFullPath); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsApplicationInstalled(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetApplicationCount(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _GetApplicationKeyByIndex(uint unApplicationIndex, StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _GetApplicationKeyByProcessId(uint unProcessId, StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchApplication(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchTemplateApplication(IntPtr pchTemplateAppKey, IntPtr pchNewAppKey, [In][Out] AppOverrideKeys_t[] pKeys, uint unKeys); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchApplicationFromMimeType(IntPtr pchMimeType, IntPtr pchArgs); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchDashboardOverlay(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _CancelApplicationLaunch(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _IdentifyApplication(uint unProcessId, IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetApplicationProcessId(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetApplicationsErrorNameFromEnum(EVRApplicationError error); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetApplicationPropertyString(IntPtr pchAppKey, EVRApplicationProperty eProperty, StringBuilder pchPropertyValueBuffer, uint unPropertyValueBufferLen, ref EVRApplicationError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetApplicationPropertyBool(IntPtr pchAppKey, EVRApplicationProperty eProperty, ref EVRApplicationError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _GetApplicationPropertyUint64(IntPtr pchAppKey, EVRApplicationProperty eProperty, ref EVRApplicationError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _SetApplicationAutoLaunch(IntPtr pchAppKey, bool bAutoLaunch); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetApplicationAutoLaunch(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _SetDefaultApplicationForMimeType(IntPtr pchAppKey, IntPtr pchMimeType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetDefaultApplicationForMimeType(IntPtr pchMimeType, StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetApplicationSupportedMimeTypes(IntPtr pchAppKey, StringBuilder pchMimeTypesBuffer, uint unMimeTypesBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetApplicationsThatSupportMimeType(IntPtr pchMimeType, StringBuilder pchAppKeysThatSupportBuffer, uint unAppKeysThatSupportBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetApplicationLaunchArguments(uint unHandle, StringBuilder pchArgs, uint unArgs); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _GetStartingApplication(StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRSceneApplicationState _GetSceneApplicationState(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _PerformApplicationPrelaunchCheck(IntPtr pchAppKey); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetSceneApplicationStateNameFromEnum(EVRSceneApplicationState state); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchInternalProcess(IntPtr pchBinaryPath, IntPtr pchArguments, IntPtr pchWorkingDirectory); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetCurrentSceneProcessId(); [MarshalAs(UnmanagedType.FunctionPtr)] internal _AddApplicationManifest AddApplicationManifest; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RemoveApplicationManifest RemoveApplicationManifest; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsApplicationInstalled IsApplicationInstalled; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationCount GetApplicationCount; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationKeyByIndex GetApplicationKeyByIndex; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationKeyByProcessId GetApplicationKeyByProcessId; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchApplication LaunchApplication; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchTemplateApplication LaunchTemplateApplication; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchApplicationFromMimeType LaunchApplicationFromMimeType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchDashboardOverlay LaunchDashboardOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CancelApplicationLaunch CancelApplicationLaunch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IdentifyApplication IdentifyApplication; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationProcessId GetApplicationProcessId; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationsErrorNameFromEnum GetApplicationsErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationPropertyString GetApplicationPropertyString; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationPropertyBool GetApplicationPropertyBool; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationPropertyUint64 GetApplicationPropertyUint64; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetApplicationAutoLaunch SetApplicationAutoLaunch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationAutoLaunch GetApplicationAutoLaunch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetDefaultApplicationForMimeType SetDefaultApplicationForMimeType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDefaultApplicationForMimeType GetDefaultApplicationForMimeType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationSupportedMimeTypes GetApplicationSupportedMimeTypes; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationsThatSupportMimeType GetApplicationsThatSupportMimeType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationLaunchArguments GetApplicationLaunchArguments; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetStartingApplication GetStartingApplication; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSceneApplicationState GetSceneApplicationState; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PerformApplicationPrelaunchCheck PerformApplicationPrelaunchCheck; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSceneApplicationStateNameFromEnum GetSceneApplicationStateNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchInternalProcess LaunchInternalProcess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCurrentSceneProcessId GetCurrentSceneProcessId; } public struct IVRChaperone { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ChaperoneCalibrationState _GetCalibrationState(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetPlayAreaSize(ref float pSizeX, ref float pSizeZ); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetPlayAreaRect(ref HmdQuad_t rect); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ReloadInfo(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetSceneColor(HmdColor_t color); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetBoundsColor(ref HmdColor_t pOutputColorArray, int nNumOutputColors, float flCollisionBoundsFadeDistance, ref HmdColor_t pOutputCameraColor); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _AreBoundsVisible(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ForceBoundsVisible(bool bForce); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ResetZeroPose(ETrackingUniverseOrigin eTrackingUniverseOrigin); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCalibrationState GetCalibrationState; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPlayAreaSize GetPlayAreaSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPlayAreaRect GetPlayAreaRect; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReloadInfo ReloadInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetSceneColor SetSceneColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBoundsColor GetBoundsColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _AreBoundsVisible AreBoundsVisible; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ForceBoundsVisible ForceBoundsVisible; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ResetZeroPose ResetZeroPose; } public struct IVRChaperoneSetup { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _CommitWorkingCopy(EChaperoneConfigFile configFile); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _RevertWorkingCopy(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetWorkingPlayAreaSize(ref float pSizeX, ref float pSizeZ); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetWorkingPlayAreaRect(ref HmdQuad_t rect); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetWorkingCollisionBoundsInfo([In][Out] HmdQuad_t[] pQuadsBuffer, ref uint punQuadsCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetLiveCollisionBoundsInfo([In][Out] HmdQuad_t[] pQuadsBuffer, ref uint punQuadsCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatStandingZeroPoseToRawTrackingPose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingPlayAreaSize(float sizeX, float sizeZ); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingCollisionBoundsInfo([In][Out] HmdQuad_t[] pQuadsBuffer, uint unQuadsCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingPerimeter([In][Out] HmdVector2_t[] pPointBuffer, uint unPointCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatSeatedZeroPoseToRawTrackingPose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatStandingZeroPoseToRawTrackingPose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ReloadFromDisk(EChaperoneConfigFile configFile); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetLiveSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ExportLiveToBuffer(StringBuilder pBuffer, ref uint pnBufferLength); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ImportFromBufferToWorking(IntPtr pBuffer, uint nImportFlags); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ShowWorkingSetPreview(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _HideWorkingSetPreview(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _RoomSetupStarting(); [MarshalAs(UnmanagedType.FunctionPtr)] internal _CommitWorkingCopy CommitWorkingCopy; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RevertWorkingCopy RevertWorkingCopy; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWorkingPlayAreaSize GetWorkingPlayAreaSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWorkingPlayAreaRect GetWorkingPlayAreaRect; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWorkingCollisionBoundsInfo GetWorkingCollisionBoundsInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLiveCollisionBoundsInfo GetLiveCollisionBoundsInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWorkingSeatedZeroPoseToRawTrackingPose GetWorkingSeatedZeroPoseToRawTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetWorkingStandingZeroPoseToRawTrackingPose GetWorkingStandingZeroPoseToRawTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingPlayAreaSize SetWorkingPlayAreaSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingCollisionBoundsInfo SetWorkingCollisionBoundsInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingPerimeter SetWorkingPerimeter; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingSeatedZeroPoseToRawTrackingPose SetWorkingSeatedZeroPoseToRawTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingStandingZeroPoseToRawTrackingPose SetWorkingStandingZeroPoseToRawTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReloadFromDisk ReloadFromDisk; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLiveSeatedZeroPoseToRawTrackingPose GetLiveSeatedZeroPoseToRawTrackingPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ExportLiveToBuffer ExportLiveToBuffer; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ImportFromBufferToWorking ImportFromBufferToWorking; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowWorkingSetPreview ShowWorkingSetPreview; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HideWorkingSetPreview HideWorkingSetPreview; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RoomSetupStarting RoomSetupStarting; } public struct IVRCompositor { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetTrackingSpace(ETrackingUniverseOrigin eOrigin); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackingUniverseOrigin _GetTrackingSpace(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _WaitGetPoses([In][Out] TrackedDevicePose_t[] pRenderPoseArray, uint unRenderPoseArrayCount, [In][Out] TrackedDevicePose_t[] pGamePoseArray, uint unGamePoseArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetLastPoses([In][Out] TrackedDevicePose_t[] pRenderPoseArray, uint unRenderPoseArrayCount, [In][Out] TrackedDevicePose_t[] pGamePoseArray, uint unGamePoseArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetLastPoseForTrackedDeviceIndex(uint unDeviceIndex, ref TrackedDevicePose_t pOutputPose, ref TrackedDevicePose_t pOutputGamePose); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _Submit(EVREye eEye, ref Texture_t pTexture, ref VRTextureBounds_t pBounds, EVRSubmitFlags nSubmitFlags); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ClearLastSubmittedFrame(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _PostPresentHandoff(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetFrameTiming(ref Compositor_FrameTiming pTiming, uint unFramesAgo); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetFrameTimings([In][Out] Compositor_FrameTiming[] pTiming, uint nFrames); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate float _GetFrameTimeRemaining(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetCumulativeStats(ref Compositor_CumulativeStats pStats, uint nStatsSizeInBytes); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _FadeToColor(float fSeconds, float fRed, float fGreen, float fBlue, float fAlpha, bool bBackground); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate HmdColor_t _GetCurrentFadeColor(bool bBackground); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _FadeGrid(float fSeconds, bool bFadeIn); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate float _GetCurrentGridAlpha(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _SetSkyboxOverride([In][Out] Texture_t[] pTextures, uint unTextureCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ClearSkyboxOverride(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _CompositorBringToFront(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _CompositorGoToBack(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _CompositorQuit(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsFullscreen(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetCurrentSceneFocusProcess(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetLastFrameRenderer(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _CanRenderScene(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ShowMirrorWindow(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _HideMirrorWindow(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsMirrorWindowVisible(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _CompositorDumpImages(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ShouldAppRenderWithLowResources(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ForceInterleavedReprojectionOn(bool bOverride); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ForceReconnectProcess(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SuspendRendering(bool bSuspend); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetMirrorTextureD3D11(EVREye eEye, IntPtr pD3D11DeviceOrResource, ref IntPtr ppD3D11ShaderResourceView); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ReleaseMirrorTextureD3D11(IntPtr pD3D11ShaderResourceView); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetMirrorTextureGL(EVREye eEye, ref uint pglTextureId, IntPtr pglSharedTextureHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ReleaseSharedGLTexture(uint glTextureId, IntPtr glSharedTextureHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _LockGLSharedTextureForAccess(IntPtr glSharedTextureHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _UnlockGLSharedTextureForAccess(IntPtr glSharedTextureHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetVulkanInstanceExtensionsRequired(StringBuilder pchValue, uint unBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetVulkanDeviceExtensionsRequired(IntPtr pPhysicalDevice, StringBuilder pchValue, uint unBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetExplicitTimingMode(EVRCompositorTimingMode eTimingMode); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _SubmitExplicitTimingData(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsMotionSmoothingEnabled(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsMotionSmoothingSupported(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsCurrentSceneFocusAppLoading(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _SetStageOverride_Async(IntPtr pchRenderModelPath, ref HmdMatrix34_t pTransform, ref Compositor_StageRenderSettings pRenderSettings, uint nSizeOfRenderSettings); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ClearStageOverride(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetCompositorBenchmarkResults(ref Compositor_BenchmarkResults pBenchmarkResults, uint nSizeOfBenchmarkResults); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetLastPosePredictionIDs(ref uint pRenderPosePredictionID, ref uint pGamePosePredictionID); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetPosesForFrame(uint unPosePredictionID, [In][Out] TrackedDevicePose_t[] pPoseArray, uint unPoseArrayCount); [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetTrackingSpace SetTrackingSpace; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTrackingSpace GetTrackingSpace; [MarshalAs(UnmanagedType.FunctionPtr)] internal _WaitGetPoses WaitGetPoses; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLastPoses GetLastPoses; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLastPoseForTrackedDeviceIndex GetLastPoseForTrackedDeviceIndex; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Submit Submit; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ClearLastSubmittedFrame ClearLastSubmittedFrame; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PostPresentHandoff PostPresentHandoff; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFrameTiming GetFrameTiming; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFrameTimings GetFrameTimings; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFrameTimeRemaining GetFrameTimeRemaining; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCumulativeStats GetCumulativeStats; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FadeToColor FadeToColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCurrentFadeColor GetCurrentFadeColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FadeGrid FadeGrid; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCurrentGridAlpha GetCurrentGridAlpha; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetSkyboxOverride SetSkyboxOverride; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ClearSkyboxOverride ClearSkyboxOverride; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CompositorBringToFront CompositorBringToFront; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CompositorGoToBack CompositorGoToBack; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CompositorQuit CompositorQuit; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsFullscreen IsFullscreen; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCurrentSceneFocusProcess GetCurrentSceneFocusProcess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLastFrameRenderer GetLastFrameRenderer; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CanRenderScene CanRenderScene; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowMirrorWindow ShowMirrorWindow; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HideMirrorWindow HideMirrorWindow; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsMirrorWindowVisible IsMirrorWindowVisible; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CompositorDumpImages CompositorDumpImages; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShouldAppRenderWithLowResources ShouldAppRenderWithLowResources; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ForceInterleavedReprojectionOn ForceInterleavedReprojectionOn; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ForceReconnectProcess ForceReconnectProcess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SuspendRendering SuspendRendering; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetMirrorTextureD3D11 GetMirrorTextureD3D11; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseMirrorTextureD3D11 ReleaseMirrorTextureD3D11; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetMirrorTextureGL GetMirrorTextureGL; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseSharedGLTexture ReleaseSharedGLTexture; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LockGLSharedTextureForAccess LockGLSharedTextureForAccess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _UnlockGLSharedTextureForAccess UnlockGLSharedTextureForAccess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVulkanInstanceExtensionsRequired GetVulkanInstanceExtensionsRequired; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetVulkanDeviceExtensionsRequired GetVulkanDeviceExtensionsRequired; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetExplicitTimingMode SetExplicitTimingMode; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SubmitExplicitTimingData SubmitExplicitTimingData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsMotionSmoothingEnabled IsMotionSmoothingEnabled; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsMotionSmoothingSupported IsMotionSmoothingSupported; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsCurrentSceneFocusAppLoading IsCurrentSceneFocusAppLoading; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetStageOverride_Async SetStageOverride_Async; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ClearStageOverride ClearStageOverride; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCompositorBenchmarkResults GetCompositorBenchmarkResults; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetLastPosePredictionIDs GetLastPosePredictionIDs; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPosesForFrame GetPosesForFrame; } public struct IVROverlay { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _FindOverlay(IntPtr pchOverlayKey, ref ulong pOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _CreateOverlay(IntPtr pchOverlayKey, IntPtr pchOverlayName, ref ulong pOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _DestroyOverlay(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetOverlayKey(ulong ulOverlayHandle, StringBuilder pchValue, uint unBufferSize, ref EVROverlayError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetOverlayName(ulong ulOverlayHandle, StringBuilder pchValue, uint unBufferSize, ref EVROverlayError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayName(ulong ulOverlayHandle, IntPtr pchName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayImageData(ulong ulOverlayHandle, IntPtr pvBuffer, uint unBufferSize, ref uint punWidth, ref uint punHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetOverlayErrorNameFromEnum(EVROverlayError error); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayRenderingPid(ulong ulOverlayHandle, uint unPID); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetOverlayRenderingPid(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayFlag(ulong ulOverlayHandle, VROverlayFlags eOverlayFlag, bool bEnabled); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayFlag(ulong ulOverlayHandle, VROverlayFlags eOverlayFlag, ref bool pbEnabled); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayFlags(ulong ulOverlayHandle, ref uint pFlags); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayColor(ulong ulOverlayHandle, float fRed, float fGreen, float fBlue); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayColor(ulong ulOverlayHandle, ref float pfRed, ref float pfGreen, ref float pfBlue); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayAlpha(ulong ulOverlayHandle, float fAlpha); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayAlpha(ulong ulOverlayHandle, ref float pfAlpha); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTexelAspect(ulong ulOverlayHandle, float fTexelAspect); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTexelAspect(ulong ulOverlayHandle, ref float pfTexelAspect); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlaySortOrder(ulong ulOverlayHandle, uint unSortOrder); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlaySortOrder(ulong ulOverlayHandle, ref uint punSortOrder); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayWidthInMeters(ulong ulOverlayHandle, float fWidthInMeters); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayWidthInMeters(ulong ulOverlayHandle, ref float pfWidthInMeters); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayCurvature(ulong ulOverlayHandle, float fCurvature); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayCurvature(ulong ulOverlayHandle, ref float pfCurvature); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTextureColorSpace(ulong ulOverlayHandle, EColorSpace eTextureColorSpace); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTextureColorSpace(ulong ulOverlayHandle, ref EColorSpace peTextureColorSpace); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTextureBounds(ulong ulOverlayHandle, ref VRTextureBounds_t pOverlayTextureBounds); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTextureBounds(ulong ulOverlayHandle, ref VRTextureBounds_t pOverlayTextureBounds); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformType(ulong ulOverlayHandle, ref VROverlayTransformType peTransformType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTransformAbsolute(ulong ulOverlayHandle, ETrackingUniverseOrigin eTrackingOrigin, ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformAbsolute(ulong ulOverlayHandle, ref ETrackingUniverseOrigin peTrackingOrigin, ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle, uint unTrackedDevice, ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle, ref uint punTrackedDevice, ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle, uint unDeviceIndex, IntPtr pchComponentName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle, ref uint punDeviceIndex, StringBuilder pchComponentName, uint unComponentNameSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformOverlayRelative(ulong ulOverlayHandle, ref ulong ulOverlayHandleParent, ref HmdMatrix34_t pmatParentOverlayToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTransformOverlayRelative(ulong ulOverlayHandle, ulong ulOverlayHandleParent, ref HmdMatrix34_t pmatParentOverlayToOverlayTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTransformCursor(ulong ulCursorOverlayHandle, ref HmdVector2_t pvHotspot); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformCursor(ulong ulOverlayHandle, ref HmdVector2_t pvHotspot); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ShowOverlay(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _HideOverlay(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsOverlayVisible(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetTransformForOverlayCoordinates(ulong ulOverlayHandle, ETrackingUniverseOrigin eTrackingOrigin, HmdVector2_t coordinatesInOverlay, ref HmdMatrix34_t pmatTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _PollNextOverlayEvent(ulong ulOverlayHandle, ref VREvent_t pEvent, uint uncbVREvent); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayInputMethod(ulong ulOverlayHandle, ref VROverlayInputMethod peInputMethod); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayInputMethod(ulong ulOverlayHandle, VROverlayInputMethod eInputMethod); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayMouseScale(ulong ulOverlayHandle, ref HmdVector2_t pvecMouseScale); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayMouseScale(ulong ulOverlayHandle, ref HmdVector2_t pvecMouseScale); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _ComputeOverlayIntersection(ulong ulOverlayHandle, ref VROverlayIntersectionParams_t pParams, ref VROverlayIntersectionResults_t pResults); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsHoverTargetOverlay(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayIntersectionMask(ulong ulOverlayHandle, ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives, uint unNumMaskPrimitives, uint unPrimitiveSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _TriggerLaserMouseHapticVibration(ulong ulOverlayHandle, float fDurationSeconds, float fFrequency, float fAmplitude); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayCursor(ulong ulOverlayHandle, ulong ulCursorHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayCursorPositionOverride(ulong ulOverlayHandle, ref HmdVector2_t pvCursor); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ClearOverlayCursorPositionOverride(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTexture(ulong ulOverlayHandle, ref Texture_t pTexture); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ClearOverlayTexture(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayRaw(ulong ulOverlayHandle, IntPtr pvBuffer, uint unWidth, uint unHeight, uint unBytesPerPixel); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayFromFile(ulong ulOverlayHandle, IntPtr pchFilePath); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTexture(ulong ulOverlayHandle, ref IntPtr pNativeTextureHandle, IntPtr pNativeTextureRef, ref uint pWidth, ref uint pHeight, ref uint pNativeFormat, ref ETextureType pAPIType, ref EColorSpace pColorSpace, ref VRTextureBounds_t pTextureBounds); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ReleaseNativeOverlayHandle(ulong ulOverlayHandle, IntPtr pNativeTextureHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTextureSize(ulong ulOverlayHandle, ref uint pWidth, ref uint pHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _CreateDashboardOverlay(IntPtr pchOverlayKey, IntPtr pchOverlayFriendlyName, ref ulong pMainHandle, ref ulong pThumbnailHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsDashboardVisible(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsActiveDashboardOverlay(ulong ulOverlayHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetDashboardOverlaySceneProcess(ulong ulOverlayHandle, uint unProcessId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetDashboardOverlaySceneProcess(ulong ulOverlayHandle, ref uint punProcessId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _ShowDashboard(IntPtr pchOverlayToShow); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetPrimaryDashboardDevice(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ShowKeyboard(int eInputMode, int eLineInputMode, uint unFlags, IntPtr pchDescription, uint unCharMax, IntPtr pchExistingText, ulong uUserValue); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ShowKeyboardForOverlay(ulong ulOverlayHandle, int eInputMode, int eLineInputMode, uint unFlags, IntPtr pchDescription, uint unCharMax, IntPtr pchExistingText, ulong uUserValue); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetKeyboardText(StringBuilder pchText, uint cchText); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _HideKeyboard(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetKeyboardTransformAbsolute(ETrackingUniverseOrigin eTrackingOrigin, ref HmdMatrix34_t pmatTrackingOriginToKeyboardTransform); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetKeyboardPositionForOverlay(ulong ulOverlayHandle, HmdRect2_t avoidRect); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate VRMessageOverlayResponse _ShowMessageOverlay(IntPtr pchText, IntPtr pchCaption, IntPtr pchButton0Text, IntPtr pchButton1Text, IntPtr pchButton2Text, IntPtr pchButton3Text); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _CloseMessageOverlay(); [MarshalAs(UnmanagedType.FunctionPtr)] internal _FindOverlay FindOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateOverlay CreateOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _DestroyOverlay DestroyOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayKey GetOverlayKey; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayName GetOverlayName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayName SetOverlayName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayImageData GetOverlayImageData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayErrorNameFromEnum GetOverlayErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayRenderingPid SetOverlayRenderingPid; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayRenderingPid GetOverlayRenderingPid; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayFlag SetOverlayFlag; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayFlag GetOverlayFlag; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayFlags GetOverlayFlags; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayColor SetOverlayColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayColor GetOverlayColor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayAlpha SetOverlayAlpha; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayAlpha GetOverlayAlpha; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTexelAspect SetOverlayTexelAspect; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTexelAspect GetOverlayTexelAspect; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlaySortOrder SetOverlaySortOrder; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlaySortOrder GetOverlaySortOrder; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayWidthInMeters SetOverlayWidthInMeters; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayWidthInMeters GetOverlayWidthInMeters; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayCurvature SetOverlayCurvature; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayCurvature GetOverlayCurvature; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTextureColorSpace SetOverlayTextureColorSpace; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTextureColorSpace GetOverlayTextureColorSpace; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTextureBounds SetOverlayTextureBounds; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTextureBounds GetOverlayTextureBounds; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformType GetOverlayTransformType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformAbsolute SetOverlayTransformAbsolute; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformAbsolute GetOverlayTransformAbsolute; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformTrackedDeviceRelative SetOverlayTransformTrackedDeviceRelative; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformTrackedDeviceRelative GetOverlayTransformTrackedDeviceRelative; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformTrackedDeviceComponent SetOverlayTransformTrackedDeviceComponent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformTrackedDeviceComponent GetOverlayTransformTrackedDeviceComponent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformOverlayRelative GetOverlayTransformOverlayRelative; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformOverlayRelative SetOverlayTransformOverlayRelative; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformCursor SetOverlayTransformCursor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformCursor GetOverlayTransformCursor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowOverlay ShowOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HideOverlay HideOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsOverlayVisible IsOverlayVisible; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetTransformForOverlayCoordinates GetTransformForOverlayCoordinates; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PollNextOverlayEvent PollNextOverlayEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayInputMethod GetOverlayInputMethod; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayInputMethod SetOverlayInputMethod; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayMouseScale GetOverlayMouseScale; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayMouseScale SetOverlayMouseScale; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ComputeOverlayIntersection ComputeOverlayIntersection; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsHoverTargetOverlay IsHoverTargetOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayIntersectionMask SetOverlayIntersectionMask; [MarshalAs(UnmanagedType.FunctionPtr)] internal _TriggerLaserMouseHapticVibration TriggerLaserMouseHapticVibration; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayCursor SetOverlayCursor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayCursorPositionOverride SetOverlayCursorPositionOverride; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ClearOverlayCursorPositionOverride ClearOverlayCursorPositionOverride; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTexture SetOverlayTexture; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ClearOverlayTexture ClearOverlayTexture; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayRaw SetOverlayRaw; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayFromFile SetOverlayFromFile; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTexture GetOverlayTexture; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseNativeOverlayHandle ReleaseNativeOverlayHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTextureSize GetOverlayTextureSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateDashboardOverlay CreateDashboardOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsDashboardVisible IsDashboardVisible; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsActiveDashboardOverlay IsActiveDashboardOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetDashboardOverlaySceneProcess SetDashboardOverlaySceneProcess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDashboardOverlaySceneProcess GetDashboardOverlaySceneProcess; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowDashboard ShowDashboard; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPrimaryDashboardDevice GetPrimaryDashboardDevice; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowKeyboard ShowKeyboard; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowKeyboardForOverlay ShowKeyboardForOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetKeyboardText GetKeyboardText; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HideKeyboard HideKeyboard; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetKeyboardTransformAbsolute SetKeyboardTransformAbsolute; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetKeyboardPositionForOverlay SetKeyboardPositionForOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowMessageOverlay ShowMessageOverlay; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CloseMessageOverlay CloseMessageOverlay; } public struct IVROverlayView { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _AcquireOverlayView(ulong ulOverlayHandle, ref VRNativeDevice_t pNativeDevice, ref VROverlayView_t pOverlayView, uint unOverlayViewSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ReleaseOverlayView(ref VROverlayView_t pOverlayView); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _PostOverlayEvent(ulong ulOverlayHandle, ref VREvent_t pvrEvent); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsViewingPermitted(ulong ulOverlayHandle); [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcquireOverlayView AcquireOverlayView; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseOverlayView ReleaseOverlayView; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PostOverlayEvent PostOverlayEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsViewingPermitted IsViewingPermitted; } public struct IVRHeadsetView { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetHeadsetViewSize(uint nWidth, uint nHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetHeadsetViewSize(ref uint pnWidth, ref uint pnHeight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetHeadsetViewMode(uint eHeadsetViewMode); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetHeadsetViewMode(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetHeadsetViewCropped(bool bCropped); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetHeadsetViewCropped(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate float _GetHeadsetViewAspectRatio(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetHeadsetViewBlendRange(float flStartPct, float flEndPct); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetHeadsetViewBlendRange(ref float pStartPct, ref float pEndPct); [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetHeadsetViewSize SetHeadsetViewSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHeadsetViewSize GetHeadsetViewSize; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetHeadsetViewMode SetHeadsetViewMode; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHeadsetViewMode GetHeadsetViewMode; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetHeadsetViewCropped SetHeadsetViewCropped; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHeadsetViewCropped GetHeadsetViewCropped; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHeadsetViewAspectRatio GetHeadsetViewAspectRatio; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetHeadsetViewBlendRange SetHeadsetViewBlendRange; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetHeadsetViewBlendRange GetHeadsetViewBlendRange; } public struct IVRRenderModels { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRRenderModelError _LoadRenderModel_Async(IntPtr pchRenderModelName, ref IntPtr ppRenderModel); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _FreeRenderModel(IntPtr pRenderModel); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRRenderModelError _LoadTexture_Async(int textureId, ref IntPtr ppTexture); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _FreeTexture(IntPtr pTexture); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRRenderModelError _LoadTextureD3D11_Async(int textureId, IntPtr pD3D11Device, ref IntPtr ppD3D11Texture2D); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRRenderModelError _LoadIntoTextureD3D11_Async(int textureId, IntPtr pDstTexture); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _FreeTextureD3D11(IntPtr pD3D11Texture2D); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetRenderModelName(uint unRenderModelIndex, StringBuilder pchRenderModelName, uint unRenderModelNameLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetRenderModelCount(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetComponentCount(IntPtr pchRenderModelName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetComponentName(IntPtr pchRenderModelName, uint unComponentIndex, StringBuilder pchComponentName, uint unComponentNameLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _GetComponentButtonMask(IntPtr pchRenderModelName, IntPtr pchComponentName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetComponentRenderModelName(IntPtr pchRenderModelName, IntPtr pchComponentName, StringBuilder pchComponentRenderModelName, uint unComponentRenderModelNameLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetComponentStateForDevicePath(IntPtr pchRenderModelName, IntPtr pchComponentName, ulong devicePath, ref RenderModel_ControllerMode_State_t pState, ref RenderModel_ComponentState_t pComponentState); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetComponentState(IntPtr pchRenderModelName, IntPtr pchComponentName, ref VRControllerState_t pControllerState, ref RenderModel_ControllerMode_State_t pState, ref RenderModel_ComponentState_t pComponentState); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _RenderModelHasComponent(IntPtr pchRenderModelName, IntPtr pchComponentName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetRenderModelThumbnailURL(IntPtr pchRenderModelName, StringBuilder pchThumbnailURL, uint unThumbnailURLLen, ref EVRRenderModelError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetRenderModelOriginalPath(IntPtr pchRenderModelName, StringBuilder pchOriginalPath, uint unOriginalPathLen, ref EVRRenderModelError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetRenderModelErrorNameFromEnum(EVRRenderModelError error); [MarshalAs(UnmanagedType.FunctionPtr)] internal _LoadRenderModel_Async LoadRenderModel_Async; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FreeRenderModel FreeRenderModel; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LoadTexture_Async LoadTexture_Async; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FreeTexture FreeTexture; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LoadTextureD3D11_Async LoadTextureD3D11_Async; [MarshalAs(UnmanagedType.FunctionPtr)] internal _LoadIntoTextureD3D11_Async LoadIntoTextureD3D11_Async; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FreeTextureD3D11 FreeTextureD3D11; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRenderModelName GetRenderModelName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRenderModelCount GetRenderModelCount; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentCount GetComponentCount; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentName GetComponentName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentButtonMask GetComponentButtonMask; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentRenderModelName GetComponentRenderModelName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentStateForDevicePath GetComponentStateForDevicePath; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentState GetComponentState; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RenderModelHasComponent RenderModelHasComponent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRenderModelThumbnailURL GetRenderModelThumbnailURL; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRenderModelOriginalPath GetRenderModelOriginalPath; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetRenderModelErrorNameFromEnum GetRenderModelErrorNameFromEnum; } public struct IVRNotifications { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRNotificationError _CreateNotification(ulong ulOverlayHandle, ulong ulUserValue, EVRNotificationType type, IntPtr pchText, EVRNotificationStyle style, ref NotificationBitmap_t pImage, ref uint pNotificationId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRNotificationError _RemoveNotification(uint notificationId); [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateNotification CreateNotification; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RemoveNotification RemoveNotification; } public struct IVRSettings { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetSettingsErrorNameFromEnum(EVRSettingsError eError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetBool(IntPtr pchSection, IntPtr pchSettingsKey, bool bValue, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetInt32(IntPtr pchSection, IntPtr pchSettingsKey, int nValue, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetFloat(IntPtr pchSection, IntPtr pchSettingsKey, float flValue, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetString(IntPtr pchSection, IntPtr pchSettingsKey, IntPtr pchValue, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetBool(IntPtr pchSection, IntPtr pchSettingsKey, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate int _GetInt32(IntPtr pchSection, IntPtr pchSettingsKey, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate float _GetFloat(IntPtr pchSection, IntPtr pchSettingsKey, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetString(IntPtr pchSection, IntPtr pchSettingsKey, StringBuilder pchValue, uint unValueLen, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _RemoveSection(IntPtr pchSection, ref EVRSettingsError peError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _RemoveKeyInSection(IntPtr pchSection, IntPtr pchSettingsKey, ref EVRSettingsError peError); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSettingsErrorNameFromEnum GetSettingsErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetBool SetBool; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetInt32 SetInt32; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetFloat SetFloat; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetString SetString; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBool GetBool; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetInt32 GetInt32; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFloat GetFloat; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetString GetString; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RemoveSection RemoveSection; [MarshalAs(UnmanagedType.FunctionPtr)] internal _RemoveKeyInSection RemoveKeyInSection; } public struct IVRScreenshots { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _RequestScreenshot(ref uint pOutScreenshotHandle, EVRScreenshotType type, IntPtr pchPreviewFilename, IntPtr pchVRFilename); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _HookScreenshot([In][Out] EVRScreenshotType[] pSupportedTypes, int numTypes); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotType _GetScreenshotPropertyType(uint screenshotHandle, ref EVRScreenshotError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetScreenshotPropertyFilename(uint screenshotHandle, EVRScreenshotPropertyFilenames filenameType, StringBuilder pchFilename, uint cchFilename, ref EVRScreenshotError pError); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _UpdateScreenshotProgress(uint screenshotHandle, float flProgress); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _TakeStereoScreenshot(ref uint pOutScreenshotHandle, IntPtr pchPreviewFilename, IntPtr pchVRFilename); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _SubmitScreenshot(uint screenshotHandle, EVRScreenshotType type, IntPtr pchSourcePreviewFilename, IntPtr pchSourceVRFilename); [MarshalAs(UnmanagedType.FunctionPtr)] internal _RequestScreenshot RequestScreenshot; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HookScreenshot HookScreenshot; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetScreenshotPropertyType GetScreenshotPropertyType; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetScreenshotPropertyFilename GetScreenshotPropertyFilename; [MarshalAs(UnmanagedType.FunctionPtr)] internal _UpdateScreenshotProgress UpdateScreenshotProgress; [MarshalAs(UnmanagedType.FunctionPtr)] internal _TakeStereoScreenshot TakeStereoScreenshot; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SubmitScreenshot SubmitScreenshot; } public struct IVRResources { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _LoadSharedResource(IntPtr pchResourceName, string pchBuffer, uint unBufferLen); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetResourceFullPath(IntPtr pchResourceName, IntPtr pchResourceTypeDirectory, StringBuilder pchPathBuffer, uint unBufferLen); [MarshalAs(UnmanagedType.FunctionPtr)] internal _LoadSharedResource LoadSharedResource; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetResourceFullPath GetResourceFullPath; } public struct IVRDriverManager { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetDriverCount(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetDriverName(uint nDriver, StringBuilder pchValue, uint unBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _GetDriverHandle(IntPtr pchDriverName); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsEnabled(uint nDriver); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDriverCount GetDriverCount; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDriverName GetDriverName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDriverHandle GetDriverHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsEnabled IsEnabled; } public struct IVRInput { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _SetActionManifestPath(IntPtr pchActionManifestPath); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetActionSetHandle(IntPtr pchActionSetName, ref ulong pHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetActionHandle(IntPtr pchActionName, ref ulong pHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetInputSourceHandle(IntPtr pchInputSourcePath, ref ulong pHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _UpdateActionState([In][Out] VRActiveActionSet_t[] pSets, uint unSizeOfVRSelectedActionSet_t, uint unSetCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetDigitalActionData(ulong action, ref InputDigitalActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetAnalogActionData(ulong action, ref InputAnalogActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetPoseActionDataRelativeToNow(ulong action, ETrackingUniverseOrigin eOrigin, float fPredictedSecondsFromNow, ref InputPoseActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetPoseActionDataForNextFrame(ulong action, ETrackingUniverseOrigin eOrigin, ref InputPoseActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalActionData(ulong action, ref InputSkeletalActionData_t pActionData, uint unActionDataSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetDominantHand(ref ETrackedControllerRole peDominantHand); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _SetDominantHand(ETrackedControllerRole eDominantHand); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetBoneCount(ulong action, ref uint pBoneCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetBoneHierarchy(ulong action, [In][Out] int[] pParentIndices, uint unIndexArayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetBoneName(ulong action, int nBoneIndex, StringBuilder pchBoneName, uint unNameBufferSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalReferenceTransforms(ulong action, EVRSkeletalTransformSpace eTransformSpace, EVRSkeletalReferencePose eReferencePose, [In][Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalTrackingLevel(ulong action, ref EVRSkeletalTrackingLevel pSkeletalTrackingLevel); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalBoneData(ulong action, EVRSkeletalTransformSpace eTransformSpace, EVRSkeletalMotionRange eMotionRange, [In][Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalSummaryData(ulong action, EVRSummaryType eSummaryType, ref VRSkeletalSummaryData_t pSkeletalSummaryData); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetSkeletalBoneDataCompressed(ulong action, EVRSkeletalMotionRange eMotionRange, IntPtr pvCompressedData, uint unCompressedSize, ref uint punRequiredCompressedSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _DecompressSkeletalBoneData(IntPtr pvCompressedBuffer, uint unCompressedBufferSize, EVRSkeletalTransformSpace eTransformSpace, [In][Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _TriggerHapticVibrationAction(ulong action, float fStartSecondsFromNow, float fDurationSeconds, float fFrequency, float fAmplitude, ulong ulRestrictToDevice); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetActionOrigins(ulong actionSetHandle, ulong digitalActionHandle, [In][Out] ulong[] originsOut, uint originOutCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetOriginLocalizedName(ulong origin, StringBuilder pchNameArray, uint unNameArraySize, int unStringSectionsToInclude); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetOriginTrackedDeviceInfo(ulong origin, ref InputOriginInfo_t pOriginInfo, uint unOriginInfoSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetActionBindingInfo(ulong action, ref InputBindingInfo_t pOriginInfo, uint unBindingInfoSize, uint unBindingInfoCount, ref uint punReturnedBindingInfoCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _ShowActionOrigins(ulong actionSetHandle, ulong ulActionHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _ShowBindingsForActionSet([In][Out] VRActiveActionSet_t[] pSets, uint unSizeOfVRSelectedActionSet_t, uint unSetCount, ulong originToHighlight); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetComponentStateForBinding(IntPtr pchRenderModelName, IntPtr pchComponentName, ref InputBindingInfo_t pOriginInfo, uint unBindingInfoSize, uint unBindingInfoCount, ref RenderModel_ComponentState_t pComponentState); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsUsingLegacyInput(); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _OpenBindingUI(IntPtr pchAppKey, ulong ulActionSetHandle, ulong ulDeviceHandle, bool bShowOnDesktop); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRInputError _GetBindingVariant(ulong ulDevicePath, StringBuilder pchVariantArray, uint unVariantArraySize); [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetActionManifestPath SetActionManifestPath; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetActionSetHandle GetActionSetHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetActionHandle GetActionHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetInputSourceHandle GetInputSourceHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _UpdateActionState UpdateActionState; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDigitalActionData GetDigitalActionData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetAnalogActionData GetAnalogActionData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPoseActionDataRelativeToNow GetPoseActionDataRelativeToNow; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPoseActionDataForNextFrame GetPoseActionDataForNextFrame; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalActionData GetSkeletalActionData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDominantHand GetDominantHand; [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetDominantHand SetDominantHand; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBoneCount GetBoneCount; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBoneHierarchy GetBoneHierarchy; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBoneName GetBoneName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalReferenceTransforms GetSkeletalReferenceTransforms; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalTrackingLevel GetSkeletalTrackingLevel; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalBoneData GetSkeletalBoneData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalSummaryData GetSkeletalSummaryData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSkeletalBoneDataCompressed GetSkeletalBoneDataCompressed; [MarshalAs(UnmanagedType.FunctionPtr)] internal _DecompressSkeletalBoneData DecompressSkeletalBoneData; [MarshalAs(UnmanagedType.FunctionPtr)] internal _TriggerHapticVibrationAction TriggerHapticVibrationAction; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetActionOrigins GetActionOrigins; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOriginLocalizedName GetOriginLocalizedName; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOriginTrackedDeviceInfo GetOriginTrackedDeviceInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetActionBindingInfo GetActionBindingInfo; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowActionOrigins ShowActionOrigins; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ShowBindingsForActionSet ShowBindingsForActionSet; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentStateForBinding GetComponentStateForBinding; [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsUsingLegacyInput IsUsingLegacyInput; [MarshalAs(UnmanagedType.FunctionPtr)] internal _OpenBindingUI OpenBindingUI; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetBindingVariant GetBindingVariant; } public struct IVRIOBuffer { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EIOBufferError _Open(IntPtr pchPath, EIOBufferMode mode, uint unElementSize, uint unElements, ref ulong pulBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EIOBufferError _Close(ulong ulBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EIOBufferError _Read(ulong ulBuffer, IntPtr pDst, uint unBytes, ref uint punRead); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EIOBufferError _Write(ulong ulBuffer, IntPtr pSrc, uint unBytes); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _PropertyContainer(ulong ulBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _HasReaders(ulong ulBuffer); [MarshalAs(UnmanagedType.FunctionPtr)] internal _Open Open; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Close Close; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Read Read; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Write Write; [MarshalAs(UnmanagedType.FunctionPtr)] internal _PropertyContainer PropertyContainer; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HasReaders HasReaders; } public struct IVRSpatialAnchors { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRSpatialAnchorError _CreateSpatialAnchorFromDescriptor(IntPtr pchDescriptor, ref uint pHandleOut); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRSpatialAnchorError _CreateSpatialAnchorFromPose(uint unDeviceIndex, ETrackingUniverseOrigin eOrigin, ref SpatialAnchorPose_t pPose, ref uint pHandleOut); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRSpatialAnchorError _GetSpatialAnchorPose(uint unHandle, ETrackingUniverseOrigin eOrigin, ref SpatialAnchorPose_t pPoseOut); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRSpatialAnchorError _GetSpatialAnchorDescriptor(uint unHandle, StringBuilder pchDescriptorOut, ref uint punDescriptorBufferLenInOut); [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateSpatialAnchorFromDescriptor CreateSpatialAnchorFromDescriptor; [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateSpatialAnchorFromPose CreateSpatialAnchorFromPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSpatialAnchorPose GetSpatialAnchorPose; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSpatialAnchorDescriptor GetSpatialAnchorDescriptor; } public struct IVRDebug { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRDebugError _EmitVrProfilerEvent(IntPtr pchMessage); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRDebugError _BeginVrProfilerEvent(ref ulong pHandleOut); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRDebugError _FinishVrProfilerEvent(ulong hHandle, IntPtr pchMessage); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _DriverDebugRequest(uint unDeviceIndex, IntPtr pchRequest, StringBuilder pchResponseBuffer, uint unResponseBufferSize); [MarshalAs(UnmanagedType.FunctionPtr)] internal _EmitVrProfilerEvent EmitVrProfilerEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _BeginVrProfilerEvent BeginVrProfilerEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _FinishVrProfilerEvent FinishVrProfilerEvent; [MarshalAs(UnmanagedType.FunctionPtr)] internal _DriverDebugRequest DriverDebugRequest; } public struct IVRProperties { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _ReadPropertyBatch(ulong ulContainerHandle, ref PropertyRead_t pBatch, uint unBatchEntryCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _WritePropertyBatch(ulong ulContainerHandle, ref PropertyWrite_t pBatch, uint unBatchEntryCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetPropErrorNameFromEnum(ETrackedPropertyError error); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ulong _TrackedDeviceToPropertyContainer(uint nDevice); [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReadPropertyBatch ReadPropertyBatch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _WritePropertyBatch WritePropertyBatch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetPropErrorNameFromEnum GetPropErrorNameFromEnum; [MarshalAs(UnmanagedType.FunctionPtr)] internal _TrackedDeviceToPropertyContainer TrackedDeviceToPropertyContainer; } public struct IVRPaths { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _ReadPathBatch(ulong ulRootHandle, ref PathRead_t pBatch, uint unBatchEntryCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _WritePathBatch(ulong ulRootHandle, ref PathWrite_t pBatch, uint unBatchEntryCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _StringToHandle(ref ulong pHandle, IntPtr pchPath); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ETrackedPropertyError _HandleToString(ulong pHandle, string pchBuffer, uint unBufferSize, ref uint punBufferSizeUsed); [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReadPathBatch ReadPathBatch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _WritePathBatch WritePathBatch; [MarshalAs(UnmanagedType.FunctionPtr)] internal _StringToHandle StringToHandle; [MarshalAs(UnmanagedType.FunctionPtr)] internal _HandleToString HandleToString; } public struct IVRBlockQueue { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _Create(ref ulong pulQueueHandle, IntPtr pchPath, uint unBlockDataSize, uint unBlockHeaderSize, uint unBlockCount); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _Connect(ref ulong pulQueueHandle, IntPtr pchPath); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _Destroy(ulong ulQueueHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _AcquireWriteOnlyBlock(ulong ulQueueHandle, ref ulong pulBlockHandle, ref IntPtr ppvBuffer); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _ReleaseWriteOnlyBlock(ulong ulQueueHandle, ulong ulBlockHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _WaitAndAcquireReadOnlyBlock(ulong ulQueueHandle, ref ulong pulBlockHandle, ref IntPtr ppvBuffer, EBlockQueueReadType eReadType, uint unTimeoutMs); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _AcquireReadOnlyBlock(ulong ulQueueHandle, ref ulong pulBlockHandle, ref IntPtr ppvBuffer, EBlockQueueReadType eReadType); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _ReleaseReadOnlyBlock(ulong ulQueueHandle, ulong ulBlockHandle); [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EBlockQueueError _QueueHasReader(ulong ulQueueHandle, ref bool pbHasReaders); [MarshalAs(UnmanagedType.FunctionPtr)] internal _Create Create; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Connect Connect; [MarshalAs(UnmanagedType.FunctionPtr)] internal _Destroy Destroy; [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcquireWriteOnlyBlock AcquireWriteOnlyBlock; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseWriteOnlyBlock ReleaseWriteOnlyBlock; [MarshalAs(UnmanagedType.FunctionPtr)] internal _WaitAndAcquireReadOnlyBlock WaitAndAcquireReadOnlyBlock; [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcquireReadOnlyBlock AcquireReadOnlyBlock; [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseReadOnlyBlock ReleaseReadOnlyBlock; [MarshalAs(UnmanagedType.FunctionPtr)] internal _QueueHasReader QueueHasReader; } public class Utils { private static byte[] buffer = new byte[1024]; public static IntPtr ToUtf8(string managedString) { if (managedString == null) { return IntPtr.Zero; } int num = Encoding.UTF8.GetByteCount(managedString) + 1; if (buffer.Length < num) { buffer = new byte[num]; } int bytes = Encoding.UTF8.GetBytes(managedString, 0, managedString.Length, buffer, 0); buffer[bytes] = 0; IntPtr intPtr = Marshal.AllocHGlobal(bytes + 1); Marshal.Copy(buffer, 0, intPtr, bytes + 1); return intPtr; } } public class CVRSystem { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate b
plugins/Valheim_Data/Managed/UnityEngine.SpatialTracking.dll
Decompiled 5 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine.Events; using UnityEngine.Experimental.XR.Interaction; using UnityEngine.SpatialTracking; using UnityEngine.XR; using UnityEngine.XR.Tango; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("UnityEditor.XR.SpatialTracking")] [assembly: InternalsVisibleTo("UnityEditor.SpatialTracking")] [assembly: AssemblyVersion("0.0.0.0")] namespace UnityEngine.SpatialTracking { internal class TrackedPoseDriverDataDescription { internal struct PoseData { public List<string> PoseNames; public List<TrackedPoseDriver.TrackedPose> Poses; } internal static List<PoseData> DeviceData = new List<PoseData> { new PoseData { PoseNames = new List<string> { "Left Eye", "Right Eye", "Center Eye - HMD Reference", "Head", "Color Camera" }, Poses = new List<TrackedPoseDriver.TrackedPose> { TrackedPoseDriver.TrackedPose.LeftEye, TrackedPoseDriver.TrackedPose.RightEye, TrackedPoseDriver.TrackedPose.Center, TrackedPoseDriver.TrackedPose.Head, TrackedPoseDriver.TrackedPose.ColorCamera } }, new PoseData { PoseNames = new List<string> { "Left Controller", "Right Controller" }, Poses = new List<TrackedPoseDriver.TrackedPose> { TrackedPoseDriver.TrackedPose.LeftPose, TrackedPoseDriver.TrackedPose.RightPose } }, new PoseData { PoseNames = new List<string> { "Device Pose" }, Poses = new List<TrackedPoseDriver.TrackedPose> { TrackedPoseDriver.TrackedPose.RemotePose } } }; } [Flags] public enum PoseDataFlags { NoData = 0, Position = 1, Rotation = 2 } public static class PoseDataSource { internal static List<XRNodeState> nodeStates = new List<XRNodeState>(); internal static PoseDataFlags GetNodePoseData(XRNode node, out Pose resultPose) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) PoseDataFlags poseDataFlags = PoseDataFlags.NoData; InputTracking.GetNodeStates(nodeStates); foreach (XRNodeState nodeState in nodeStates) { XRNodeState current = nodeState; if (((XRNodeState)(ref current)).nodeType == node) { if (((XRNodeState)(ref current)).TryGetPosition(ref resultPose.position)) { poseDataFlags |= PoseDataFlags.Position; } if (((XRNodeState)(ref current)).TryGetRotation(ref resultPose.rotation)) { poseDataFlags |= PoseDataFlags.Rotation; } return poseDataFlags; } } resultPose = Pose.identity; return poseDataFlags; } public static bool TryGetDataFromSource(TrackedPoseDriver.TrackedPose poseSource, out Pose resultPose) { return GetDataFromSource(poseSource, out resultPose) == (PoseDataFlags.Position | PoseDataFlags.Rotation); } public static PoseDataFlags GetDataFromSource(TrackedPoseDriver.TrackedPose poseSource, out Pose resultPose) { //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) switch (poseSource) { case TrackedPoseDriver.TrackedPose.RemotePose: { PoseDataFlags nodePoseData = GetNodePoseData((XRNode)5, out resultPose); if (nodePoseData == PoseDataFlags.NoData) { return GetNodePoseData((XRNode)4, out resultPose); } return nodePoseData; } case TrackedPoseDriver.TrackedPose.LeftEye: return GetNodePoseData((XRNode)0, out resultPose); case TrackedPoseDriver.TrackedPose.RightEye: return GetNodePoseData((XRNode)1, out resultPose); case TrackedPoseDriver.TrackedPose.Head: return GetNodePoseData((XRNode)3, out resultPose); case TrackedPoseDriver.TrackedPose.Center: return GetNodePoseData((XRNode)2, out resultPose); case TrackedPoseDriver.TrackedPose.LeftPose: return GetNodePoseData((XRNode)4, out resultPose); case TrackedPoseDriver.TrackedPose.RightPose: return GetNodePoseData((XRNode)5, out resultPose); case TrackedPoseDriver.TrackedPose.ColorCamera: { PoseDataFlags poseDataFlags = TryGetTangoPose(out resultPose); if (poseDataFlags == PoseDataFlags.NoData) { return GetNodePoseData((XRNode)2, out resultPose); } return poseDataFlags; } default: Debug.LogWarningFormat("Unable to retrieve pose data for poseSource: {0}", new object[1] { poseSource.ToString() }); resultPose = Pose.identity; return PoseDataFlags.NoData; } } private static PoseDataFlags TryGetTangoPose(out Pose pose) { //IL_002f: 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_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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) PoseData val = default(PoseData); if (TangoInputTracking.TryGetPoseAtTime(ref val) && (int)val.statusCode == 1) { pose.position = ((PoseData)(ref val)).position; pose.rotation = ((PoseData)(ref val)).rotation; return PoseDataFlags.Position | PoseDataFlags.Rotation; } pose = Pose.identity; return PoseDataFlags.NoData; } } [Serializable] [DefaultExecutionOrder(-30000)] [AddComponentMenu("XR/Tracked Pose Driver")] [HelpURL("https://docs.unity3d.com/Packages/[email protected]/manual/index.html")] public class TrackedPoseDriver : MonoBehaviour { public enum DeviceType { GenericXRDevice, GenericXRController, GenericXRRemote } public enum TrackedPose { LeftEye, RightEye, Center, Head, LeftPose, RightPose, ColorCamera, DepthCameraDeprecated, FisheyeCameraDeprected, DeviceDeprecated, RemotePose } public enum TrackingType { RotationAndPosition, RotationOnly, PositionOnly } public enum UpdateType { UpdateAndBeforeRender, Update, BeforeRender } [SerializeField] private DeviceType m_Device; [SerializeField] private TrackedPose m_PoseSource = TrackedPose.Center; [SerializeField] private BasePoseProvider m_PoseProviderComponent; [SerializeField] private TrackingType m_TrackingType; [SerializeField] private UpdateType m_UpdateType; [SerializeField] private bool m_UseRelativeTransform; protected Pose m_OriginPose; public DeviceType deviceType { get { return m_Device; } internal set { m_Device = value; } } public TrackedPose poseSource { get { return m_PoseSource; } internal set { m_PoseSource = value; } } public BasePoseProvider poseProviderComponent { get { return m_PoseProviderComponent; } set { m_PoseProviderComponent = value; } } public TrackingType trackingType { get { return m_TrackingType; } set { m_TrackingType = value; } } public UpdateType updateType { get { return m_UpdateType; } set { m_UpdateType = value; } } public bool UseRelativeTransform { get { return m_UseRelativeTransform; } set { m_UseRelativeTransform = value; } } public Pose originPose { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_OriginPose; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_OriginPose = value; } } public bool SetPoseSource(DeviceType deviceType, TrackedPose pose) { if ((int)deviceType < TrackedPoseDriverDataDescription.DeviceData.Count) { TrackedPoseDriverDataDescription.PoseData poseData = TrackedPoseDriverDataDescription.DeviceData[(int)deviceType]; for (int i = 0; i < poseData.Poses.Count; i++) { if (poseData.Poses[i] == pose) { this.deviceType = deviceType; poseSource = pose; return true; } } } return false; } private PoseDataFlags GetPoseData(DeviceType device, TrackedPose poseSource, out Pose resultPose) { if ((Object)(object)m_PoseProviderComponent != (Object)null) { return m_PoseProviderComponent.GetPoseFromProvider(out resultPose); } return PoseDataSource.GetDataFromSource(poseSource, out resultPose); } private void CacheLocalPosition() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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) m_OriginPose.position = ((Component)this).transform.localPosition; m_OriginPose.rotation = ((Component)this).transform.localRotation; } private void ResetToCachedLocalPosition() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) SetLocalTransform(m_OriginPose.position, m_OriginPose.rotation, PoseDataFlags.Position | PoseDataFlags.Rotation); } protected virtual void Awake() { CacheLocalPosition(); } protected virtual void OnDestroy() { } protected virtual void OnEnable() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown Application.onBeforeRender += new UnityAction(OnBeforeRender); } protected virtual void OnDisable() { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown ResetToCachedLocalPosition(); Application.onBeforeRender -= new UnityAction(OnBeforeRender); } protected virtual void FixedUpdate() { if (m_UpdateType == UpdateType.Update || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void Update() { if (m_UpdateType == UpdateType.Update || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void OnBeforeRender() { if (m_UpdateType == UpdateType.BeforeRender || m_UpdateType == UpdateType.UpdateAndBeforeRender) { PerformUpdate(); } } protected virtual void SetLocalTransform(Vector3 newPosition, Quaternion newRotation, PoseDataFlags poseFlags) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if ((m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.RotationOnly) && (poseFlags & PoseDataFlags.Rotation) > PoseDataFlags.NoData) { ((Component)this).transform.localRotation = newRotation; } if ((m_TrackingType == TrackingType.RotationAndPosition || m_TrackingType == TrackingType.PositionOnly) && (poseFlags & PoseDataFlags.Position) > PoseDataFlags.NoData) { ((Component)this).transform.localPosition = newPosition; } } protected Pose TransformPoseByOriginIfNeeded(Pose pose) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (m_UseRelativeTransform) { return ((Pose)(ref pose)).GetTransformedBy(m_OriginPose); } return pose; } private bool HasStereoCamera() { Camera component = ((Component)this).GetComponent<Camera>(); if ((Object)(object)component != (Object)null) { return component.stereoEnabled; } return false; } protected virtual void PerformUpdate() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (((Behaviour)this).enabled) { Pose val = default(Pose); val = Pose.identity; PoseDataFlags poseData = GetPoseData(m_Device, m_PoseSource, out val); if (poseData != 0) { Pose val2 = TransformPoseByOriginIfNeeded(val); SetLocalTransform(val2.position, val2.rotation, poseData); } } } } } namespace UnityEngine.Experimental.XR.Interaction { [Serializable] public abstract class BasePoseProvider : MonoBehaviour { public virtual PoseDataFlags GetPoseFromProvider(out Pose output) { if (TryGetPoseFromProvider(out output)) { return PoseDataFlags.Position | PoseDataFlags.Rotation; } return PoseDataFlags.NoData; } [Obsolete("This function is provided for backwards compatibiltiy with the BasePoseProvider found in com.untiy.xr.legacyinputhelpers v1.3.X Please do not implement this function, instead use the new API via GetPoseFromProvider", false)] public virtual bool TryGetPoseFromProvider(out Pose output) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) output = Pose.identity; return false; } } }
plugins/Valheim_Data/Managed/UnityEngine.XR.LegacyInputHelpers.dll
Decompiled 5 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using UnityEngine; using UnityEngine.Experimental.XR.Interaction; using UnityEngine.SpatialTracking; using UnityEngine.XR; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("UnityEditor.XR.LegacyInputHelpers")] [assembly: AssemblyVersion("0.0.0.0")] namespace UnityEditor.XR.LegacyInputHelpers { public enum UserRequestedTrackingMode { Default, Device, Floor } [AddComponentMenu("XR/Camera Offset")] public class CameraOffset : MonoBehaviour { private const float k_DefaultCameraYOffset = 1.36144f; [SerializeField] [Tooltip("GameObject to move to desired height off the floor (defaults to this object if none provided).")] private GameObject m_CameraFloorOffsetObject; [SerializeField] [Tooltip("What the user wants the tracking origin mode to be")] private UserRequestedTrackingMode m_RequestedTrackingMode; [SerializeField] [Tooltip("Sets the type of tracking origin to use for this Rig. Tracking origins identify where 0,0,0 is in the world of tracking.")] private TrackingOriginModeFlags m_TrackingOriginMode; [SerializeField] [Tooltip("Set if the XR experience is Room Scale or Stationary.")] private TrackingSpaceType m_TrackingSpace; [SerializeField] [Tooltip("Camera Height to be used when in Device tracking space.")] private float m_CameraYOffset = 1.36144f; private bool m_CameraInitialized; private bool m_CameraInitializing; private static List<XRInputSubsystem> s_InputSubsystems = new List<XRInputSubsystem>(); public GameObject cameraFloorOffsetObject { get { return m_CameraFloorOffsetObject; } set { m_CameraFloorOffsetObject = value; SetupCamera(); } } public UserRequestedTrackingMode requestedTrackingMode { get { return m_RequestedTrackingMode; } set { m_RequestedTrackingMode = value; TryInitializeCamera(); } } public TrackingOriginModeFlags TrackingOriginMode { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_TrackingOriginMode; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_TrackingOriginMode = value; TryInitializeCamera(); } } [Obsolete("CameraOffset.trackingSpace is obsolete. Please use CameraOffset.trackingOriginMode.")] public TrackingSpaceType trackingSpace { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_TrackingSpace; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_TrackingSpace = value; TryInitializeCamera(); } } public float cameraYOffset { get { return m_CameraYOffset; } set { m_CameraYOffset = value; TryInitializeCamera(); } } private void UpgradeTrackingSpaceToTrackingOriginMode() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if ((int)m_TrackingOriginMode != 0 || (int)m_TrackingSpace > 1) { return; } TrackingSpaceType val = m_TrackingSpace; if ((int)val != 0) { if ((int)val == 1) { m_TrackingOriginMode = (TrackingOriginModeFlags)2; } } else { m_TrackingOriginMode = (TrackingOriginModeFlags)1; } m_TrackingSpace = (TrackingSpaceType)3; } private void Awake() { if (!Object.op_Implicit((Object)(object)m_CameraFloorOffsetObject)) { Debug.LogWarning((object)"No camera container specified for XR Rig, using attached GameObject"); m_CameraFloorOffsetObject = ((Component)this).gameObject; } } private void Start() { TryInitializeCamera(); } private void OnValidate() { UpgradeTrackingSpaceToTrackingOriginMode(); TryInitializeCamera(); } private void TryInitializeCamera() { m_CameraInitialized = SetupCamera(); if (!m_CameraInitialized & !m_CameraInitializing) { ((MonoBehaviour)this).StartCoroutine(RepeatInitializeCamera()); } } private IEnumerator RepeatInitializeCamera() { m_CameraInitializing = true; yield return null; while (!m_CameraInitialized) { m_CameraInitialized = SetupCamera(); yield return null; } m_CameraInitializing = false; } private bool SetupCamera() { SubsystemManager.GetInstances<XRInputSubsystem>(s_InputSubsystems); bool flag = true; if (s_InputSubsystems.Count != 0) { for (int i = 0; i < s_InputSubsystems.Count; i++) { flag &= SetupCamera(s_InputSubsystems[i]); } } else if (m_RequestedTrackingMode == UserRequestedTrackingMode.Floor) { SetupCameraLegacy((TrackingSpaceType)1); } else { SetupCameraLegacy((TrackingSpaceType)0); } return flag; } private bool SetupCamera(XRInputSubsystem subsystem) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between Unknown and I4 //IL_0044: 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_008b: Invalid comparison between Unknown and I4 //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) if (subsystem == null) { return false; } bool flag = false; float num = cameraYOffset; TrackingOriginModeFlags trackingOriginMode = subsystem.GetTrackingOriginMode(); TrackingOriginModeFlags supportedTrackingOriginModes = subsystem.GetSupportedTrackingOriginModes(); TrackingOriginModeFlags val = (TrackingOriginModeFlags)0; if (m_RequestedTrackingMode == UserRequestedTrackingMode.Default) { val = trackingOriginMode; } else if (m_RequestedTrackingMode == UserRequestedTrackingMode.Device) { val = (TrackingOriginModeFlags)1; } else if (m_RequestedTrackingMode == UserRequestedTrackingMode.Floor) { val = (TrackingOriginModeFlags)2; } else { Debug.LogWarning((object)"Unknown Requested Tracking Mode"); } if ((int)val == 2) { if ((supportedTrackingOriginModes & 2) == 0) { Debug.LogWarning((object)"CameraOffset.SetupCamera: Attempting to set the tracking space to Floor, but that is not supported by the SDK."); m_TrackingOriginMode = subsystem.GetTrackingOriginMode(); return true; } if (subsystem.TrySetTrackingOriginMode(val)) { num = 0f; flag = true; } } else if ((int)val == 1) { if ((supportedTrackingOriginModes & 1) == 0) { Debug.LogWarning((object)"CameraOffset.SetupCamera: Attempting to set the tracking space to Device, but that is not supported by the SDK."); m_TrackingOriginMode = subsystem.GetTrackingOriginMode(); return true; } if (subsystem.TrySetTrackingOriginMode(val)) { flag = subsystem.TryRecenter(); } } m_TrackingOriginMode = subsystem.GetTrackingOriginMode(); if (flag && Object.op_Implicit((Object)(object)m_CameraFloorOffsetObject)) { m_CameraFloorOffsetObject.transform.localPosition = new Vector3(m_CameraFloorOffsetObject.transform.localPosition.x, num, m_CameraFloorOffsetObject.transform.localPosition.z); } return flag; } private void SetupCameraLegacy(TrackingSpaceType trackingSpace) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_001a: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) float num = m_CameraYOffset; XRDevice.SetTrackingSpaceType(trackingSpace); if ((int)trackingSpace == 0) { InputTracking.Recenter(); } else if ((int)trackingSpace == 1) { num = 0f; } m_TrackingSpace = trackingSpace; if (Object.op_Implicit((Object)(object)m_CameraFloorOffsetObject)) { m_CameraFloorOffsetObject.transform.localPosition = new Vector3(m_CameraFloorOffsetObject.transform.localPosition.x, num, m_CameraFloorOffsetObject.transform.localPosition.z); } } } } namespace UnityEngine.XR.LegacyInputHelpers { public class ArmModel : BasePoseProvider { private Pose m_FinalPose; [SerializeField] private XRNode m_PoseSource = (XRNode)4; [SerializeField] private XRNode m_HeadPoseSource = (XRNode)2; [SerializeField] private Vector3 m_ElbowRestPosition = DEFAULT_ELBOW_REST_POSITION; [SerializeField] private Vector3 m_WristRestPosition = DEFAULT_WRIST_REST_POSITION; [SerializeField] private Vector3 m_ControllerRestPosition = DEFAULT_CONTROLLER_REST_POSITION; [SerializeField] private Vector3 m_ArmExtensionOffset = DEFAULT_ARM_EXTENSION_OFFSET; [Range(0f, 1f)] [SerializeField] private float m_ElbowBendRatio = 0.6f; [SerializeField] private bool m_IsLockedToNeck = true; protected Vector3 m_NeckPosition; protected Vector3 m_ElbowPosition; protected Quaternion m_ElbowRotation; protected Vector3 m_WristPosition; protected Quaternion m_WristRotation; protected Vector3 m_ControllerPosition; protected Quaternion m_ControllerRotation; protected Vector3 m_HandedMultiplier; protected Vector3 m_TorsoDirection; protected Quaternion m_TorsoRotation; protected static readonly Vector3 DEFAULT_ELBOW_REST_POSITION = new Vector3(0.195f, -0.5f, 0.005f); protected static readonly Vector3 DEFAULT_WRIST_REST_POSITION = new Vector3(0f, 0f, 0.25f); protected static readonly Vector3 DEFAULT_CONTROLLER_REST_POSITION = new Vector3(0f, 0f, 0.05f); protected static readonly Vector3 DEFAULT_ARM_EXTENSION_OFFSET = new Vector3(-0.13f, 0.14f, 0.08f); protected const float DEFAULT_ELBOW_BEND_RATIO = 0.6f; protected const float EXTENSION_WEIGHT = 0.4f; protected static readonly Vector3 SHOULDER_POSITION = new Vector3(0.17f, -0.2f, -0.03f); protected static readonly Vector3 NECK_OFFSET = new Vector3(0f, 0.075f, 0.08f); protected const float MIN_EXTENSION_ANGLE = 7f; protected const float MAX_EXTENSION_ANGLE = 60f; private List<XRNodeState> xrNodeStateListOrientation = new List<XRNodeState>(); private List<XRNodeState> xrNodeStateListPosition = new List<XRNodeState>(); private List<XRNodeState> xrNodeStateListAngularAcceleration = new List<XRNodeState>(); private List<XRNodeState> xrNodeStateListAngularVelocity = new List<XRNodeState>(); public Pose finalPose { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_FinalPose; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_FinalPose = value; } } public XRNode poseSource { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_PoseSource; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_PoseSource = value; } } public XRNode headGameObject { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_HeadPoseSource; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_HeadPoseSource = value; } } public Vector3 elbowRestPosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_ElbowRestPosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_ElbowRestPosition = value; } } public Vector3 wristRestPosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_WristRestPosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_WristRestPosition = value; } } public Vector3 controllerRestPosition { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_ControllerRestPosition; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_ControllerRestPosition = value; } } public Vector3 armExtensionOffset { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return m_ArmExtensionOffset; } set { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) m_ArmExtensionOffset = value; } } public float elbowBendRatio { get { return m_ElbowBendRatio; } set { m_ElbowBendRatio = value; } } public bool isLockedToNeck { get { return m_IsLockedToNeck; } set { m_IsLockedToNeck = value; } } public Vector3 neckPosition => m_NeckPosition; public Vector3 shoulderPosition => m_NeckPosition + m_TorsoRotation * Vector3.Scale(SHOULDER_POSITION, m_HandedMultiplier); public Quaternion shoulderRotation => m_TorsoRotation; public Vector3 elbowPosition => m_ElbowPosition; public Quaternion elbowRotation => m_ElbowRotation; public Vector3 wristPosition => m_WristPosition; public Quaternion wristRotation => m_WristRotation; public Vector3 controllerPosition => m_ControllerPosition; public Quaternion controllerRotation => m_ControllerRotation; public override PoseDataFlags GetPoseFromProvider(out Pose output) { //IL_0017: 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) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (OnControllerInputUpdated()) { output = finalPose; return (PoseDataFlags)3; } output = Pose.identity; return (PoseDataFlags)0; } protected virtual void OnEnable() { UpdateTorsoDirection(forceImmediate: true); OnControllerInputUpdated(); } protected virtual void OnDisable() { } public virtual bool OnControllerInputUpdated() { UpdateHandedness(); if (UpdateTorsoDirection(forceImmediate: false) && UpdateNeckPosition() && ApplyArmModel()) { return true; } return false; } protected virtual void UpdateHandedness() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Invalid comparison between Unknown and I4 //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Invalid comparison between Unknown and I4 ((Vector3)(ref m_HandedMultiplier)).Set(0f, 1f, 1f); if ((int)m_PoseSource == 5 || (int)m_PoseSource == 7) { m_HandedMultiplier.x = 1f; } else if ((int)m_PoseSource == 4) { m_HandedMultiplier.x = -1f; } } protected virtual bool UpdateTorsoDirection(bool forceImmediate) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_0078: Unknown result type (might be due to invalid IL or missing references) Vector3 forward = default(Vector3); if (TryGetForwardVector(m_HeadPoseSource, out forward)) { forward.y = 0f; ((Vector3)(ref forward)).Normalize(); Vector3 angularAccel; if (forceImmediate) { m_TorsoDirection = forward; } else if (TryGetAngularAcceleration(poseSource, out angularAccel)) { float num = Mathf.Clamp((((Vector3)(ref angularAccel)).magnitude - 0.2f) / 45f, 0f, 0.1f); m_TorsoDirection = Vector3.Slerp(m_TorsoDirection, forward, num); } m_TorsoRotation = Quaternion.FromToRotation(Vector3.forward, m_TorsoDirection); return true; } return false; } protected virtual bool UpdateNeckPosition() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (m_IsLockedToNeck && TryGetPosition(m_HeadPoseSource, out m_NeckPosition)) { return ApplyInverseNeckModel(m_NeckPosition, out m_NeckPosition); } m_NeckPosition = Vector3.zero; return true; } protected virtual bool ApplyArmModel() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: 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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_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) SetUntransformedJointPositions(); if (GetControllerRotation(out var rotation, out var xyRotation, out var xAngle)) { float extensionRatio = CalculateExtensionRatio(xAngle); ApplyExtensionOffset(extensionRatio); Quaternion lerpRotation = CalculateLerpRotation(xyRotation, extensionRatio); CalculateFinalJointRotations(rotation, xyRotation, lerpRotation); ApplyRotationToJoints(); m_FinalPose.position = m_ControllerPosition; m_FinalPose.rotation = m_ControllerRotation; return true; } return false; } protected virtual void SetUntransformedJointPositions() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) m_ElbowPosition = Vector3.Scale(m_ElbowRestPosition, m_HandedMultiplier); m_WristPosition = Vector3.Scale(m_WristRestPosition, m_HandedMultiplier); m_ControllerPosition = Vector3.Scale(m_ControllerRestPosition, m_HandedMultiplier); } protected virtual float CalculateExtensionRatio(float xAngle) { return Mathf.Clamp((xAngle - 7f) / 53f, 0f, 1f); } protected virtual void ApplyExtensionOffset(float extensionRatio) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Vector3.Scale(m_ArmExtensionOffset, m_HandedMultiplier); m_ElbowPosition += val * extensionRatio; } protected virtual Quaternion CalculateLerpRotation(Quaternion xyRotation, float extensionRatio) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) float num = Quaternion.Angle(xyRotation, Quaternion.identity); float num2 = 1f - Mathf.Pow(num / 180f, 6f); float num3 = 1f - m_ElbowBendRatio + m_ElbowBendRatio * extensionRatio * 0.4f; num3 *= num2; return Quaternion.Lerp(Quaternion.identity, xyRotation, num3); } protected virtual void CalculateFinalJointRotations(Quaternion controllerOrientation, Quaternion xyRotation, Quaternion lerpRotation) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) m_ElbowRotation = m_TorsoRotation * Quaternion.Inverse(lerpRotation) * xyRotation; m_WristRotation = m_ElbowRotation * lerpRotation; m_ControllerRotation = m_TorsoRotation * controllerOrientation; } protected virtual void ApplyRotationToJoints() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) m_ElbowPosition = m_NeckPosition + m_TorsoRotation * m_ElbowPosition; m_WristPosition = m_ElbowPosition + m_ElbowRotation * m_WristPosition; m_ControllerPosition = m_WristPosition + m_WristRotation * m_ControllerPosition; } protected virtual bool ApplyInverseNeckModel(Vector3 headPosition, out Vector3 calculatedPosition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: 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_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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) Quaternion rotation = default(Quaternion); if (TryGetRotation(m_HeadPoseSource, out rotation)) { Vector3 val = rotation * NECK_OFFSET - NECK_OFFSET.y * Vector3.up; headPosition -= val; calculatedPosition = headPosition; return true; } calculatedPosition = Vector3.zero; return false; } protected bool TryGetForwardVector(XRNode node, out Vector3 forward) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: 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) Pose val = default(Pose); if (TryGetRotation(node, out val.rotation) && TryGetPosition(node, out val.position)) { forward = ((Pose)(ref val)).forward; return true; } forward = Vector3.zero; return false; } protected bool TryGetRotation(XRNode node, out Quaternion rotation) { //IL_0022: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) InputTracking.GetNodeStates(xrNodeStateListOrientation); int count = xrNodeStateListOrientation.Count; for (int i = 0; i < count; i++) { XRNodeState val = xrNodeStateListOrientation[i]; if (((XRNodeState)(ref val)).nodeType == node && ((XRNodeState)(ref val)).TryGetRotation(ref rotation)) { return true; } } rotation = Quaternion.identity; return false; } protected bool TryGetPosition(XRNode node, out Vector3 position) { //IL_0022: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) InputTracking.GetNodeStates(xrNodeStateListPosition); int count = xrNodeStateListPosition.Count; for (int i = 0; i < count; i++) { XRNodeState val = xrNodeStateListPosition[i]; if (((XRNodeState)(ref val)).nodeType == node && ((XRNodeState)(ref val)).TryGetPosition(ref position)) { return true; } } position = Vector3.zero; return false; } protected bool TryGetAngularAcceleration(XRNode node, out Vector3 angularAccel) { //IL_0022: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) InputTracking.GetNodeStates(xrNodeStateListAngularAcceleration); int count = xrNodeStateListAngularAcceleration.Count; for (int i = 0; i < count; i++) { XRNodeState val = xrNodeStateListAngularAcceleration[i]; if (((XRNodeState)(ref val)).nodeType == node && ((XRNodeState)(ref val)).TryGetAngularAcceleration(ref angularAccel)) { return true; } } angularAccel = Vector3.zero; return false; } protected bool TryGetAngularVelocity(XRNode node, out Vector3 angVel) { //IL_0022: 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_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) InputTracking.GetNodeStates(xrNodeStateListAngularVelocity); int count = xrNodeStateListAngularVelocity.Count; for (int i = 0; i < count; i++) { XRNodeState val = xrNodeStateListAngularVelocity[i]; if (((XRNodeState)(ref val)).nodeType == node && ((XRNodeState)(ref val)).TryGetAngularVelocity(ref angVel)) { return true; } } angVel = Vector3.zero; return false; } protected bool GetControllerRotation(out Quaternion rotation, out Quaternion xyRotation, out float xAngle) { //IL_0002: 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_0068: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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) if (TryGetRotation(poseSource, out rotation)) { rotation = Quaternion.Inverse(m_TorsoRotation) * rotation; Vector3 val = rotation * Vector3.forward; xAngle = 90f - Vector3.Angle(val, Vector3.up); xyRotation = Quaternion.FromToRotation(Vector3.forward, val); return true; } rotation = Quaternion.identity; xyRotation = Quaternion.identity; xAngle = 0f; return false; } } public class SwingArmModel : ArmModel { [Tooltip("Portion of controller rotation applied to the shoulder joint.")] [SerializeField] [Range(0f, 1f)] private float m_ShoulderRotationRatio = 0.5f; [Tooltip("Portion of controller rotation applied to the elbow joint.")] [Range(0f, 1f)] [SerializeField] private float m_ElbowRotationRatio = 0.3f; [Tooltip("Portion of controller rotation applied to the wrist joint.")] [Range(0f, 1f)] [SerializeField] private float m_WristRotationRatio = 0.2f; [SerializeField] private Vector2 m_JointShiftAngle = new Vector2(160f, 180f); [Tooltip("Exponent applied to the joint shift ratio to control the curve of the shift.")] [Range(1f, 20f)] [SerializeField] private float m_JointShiftExponent = 6f; [Tooltip("Portion of controller rotation applied to the shoulder joint when the controller is backwards.")] [Range(0f, 1f)] [SerializeField] private float m_ShiftedShoulderRotationRatio = 0.1f; [Tooltip("Portion of controller rotation applied to the elbow joint when the controller is backwards.")] [Range(0f, 1f)] [SerializeField] private float m_ShiftedElbowRotationRatio = 0.4f; [Tooltip("Portion of controller rotation applied to the wrist joint when the controller is backwards.")] [Range(0f, 1f)] [SerializeField] private float m_ShiftedWristRotationRatio = 0.5f; public float shoulderRotationRatio { get { return m_ShoulderRotationRatio; } set { m_ShoulderRotationRatio = value; } } public float elbowRotationRatio { get { return m_ElbowRotationRatio; } set { m_ElbowRotationRatio = value; } } public float wristRotationRatio { get { return m_WristRotationRatio; } set { m_WristRotationRatio = value; } } public float minJointShiftAngle { get { return m_JointShiftAngle.x; } set { m_JointShiftAngle.x = value; } } public float maxJointShiftAngle { get { return m_JointShiftAngle.y; } set { m_JointShiftAngle.y = value; } } public float jointShiftExponent { get { return m_JointShiftExponent; } set { m_JointShiftExponent = value; } } public float shiftedShoulderRotationRatio { get { return m_ShiftedShoulderRotationRatio; } set { m_ShiftedShoulderRotationRatio = value; } } public float shiftedElbowRotationRatio { get { return m_ShiftedElbowRotationRatio; } set { m_ShiftedElbowRotationRatio = value; } } public float shiftedWristRotationRatio { get { return m_ShiftedWristRotationRatio; } set { m_ShiftedWristRotationRatio = value; } } protected override void CalculateFinalJointRotations(Quaternion controllerOrientation, Quaternion xyRotation, Quaternion lerpRotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) float num = Quaternion.Angle(xyRotation, Quaternion.identity); float num2 = maxJointShiftAngle - minJointShiftAngle; float num3 = Mathf.Pow(Mathf.Clamp01((num - minJointShiftAngle) / num2), m_JointShiftExponent); float num4 = Mathf.Lerp(m_ShoulderRotationRatio, m_ShiftedShoulderRotationRatio, num3); float num5 = Mathf.Lerp(m_ElbowRotationRatio, m_ShiftedElbowRotationRatio, num3); float num6 = Mathf.Lerp(m_WristRotationRatio, m_ShiftedWristRotationRatio, num3); Quaternion val = Quaternion.Lerp(Quaternion.identity, xyRotation, num4); Quaternion val2 = Quaternion.Lerp(Quaternion.identity, xyRotation, num5); Quaternion val3 = Quaternion.Lerp(Quaternion.identity, xyRotation, num6); Quaternion val4 = m_TorsoRotation * val; m_ElbowRotation = val4 * val2; m_WristRotation = base.elbowRotation * val3; m_ControllerRotation = m_TorsoRotation * controllerOrientation; m_TorsoRotation = val4; } } [Serializable] public class ArmModelTransition { [SerializeField] private string m_KeyName; [SerializeField] private ArmModel m_ArmModel; public string transitionKeyName { get { return m_KeyName; } set { m_KeyName = value; } } public ArmModel armModel { get { return m_ArmModel; } set { m_ArmModel = value; } } } public class TransitionArmModel : ArmModel { internal struct ArmModelBlendData { public ArmModel armModel; public float currentBlendAmount; } [SerializeField] private ArmModel m_CurrentArmModelComponent; [SerializeField] public List<ArmModelTransition> m_ArmModelTransitions = new List<ArmModelTransition>(); private const int MAX_ACTIVE_TRANSITIONS = 10; private const float DROP_TRANSITION_THRESHOLD = 0.035f; private const float LERP_CLAMP_THRESHOLD = 0.95f; private const float MIN_ANGULAR_VELOCITY = 0.2f; private const float ANGULAR_VELOCITY_DIVISOR = 45f; internal List<ArmModelBlendData> armModelBlendData = new List<ArmModelBlendData>(10); private ArmModelBlendData currentBlendingArmModel; public ArmModel currentArmModelComponent { get { return m_CurrentArmModelComponent; } set { m_CurrentArmModelComponent = value; } } public bool Queue(string key) { foreach (ArmModelTransition armModelTransition in m_ArmModelTransitions) { if (armModelTransition.transitionKeyName == key) { Queue(armModelTransition.armModel); return true; } } return false; } public void Queue(ArmModel newArmModel) { if (!((Object)(object)newArmModel == (Object)null)) { if ((Object)(object)m_CurrentArmModelComponent == (Object)null) { m_CurrentArmModelComponent = newArmModel; } RemoveJustStartingTransitions(); if (armModelBlendData.Count == 10) { RemoveOldestTransition(); } ArmModelBlendData item = default(ArmModelBlendData); item.armModel = newArmModel; item.currentBlendAmount = 0f; armModelBlendData.Add(item); } } private void RemoveJustStartingTransitions() { for (int i = 0; i < armModelBlendData.Count; i++) { if (armModelBlendData[i].currentBlendAmount < 0.035f) { armModelBlendData.RemoveAt(i); } } } private void RemoveOldestTransition() { armModelBlendData.RemoveAt(0); } public override PoseDataFlags GetPoseFromProvider(out Pose output) { //IL_0017: 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) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (UpdateBlends()) { output = base.finalPose; return (PoseDataFlags)3; } output = Pose.identity; return (PoseDataFlags)0; } private bool UpdateBlends() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: 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_007c: 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_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0202: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)currentArmModelComponent == (Object)null) { return false; } if (m_CurrentArmModelComponent.OnControllerInputUpdated()) { m_NeckPosition = m_CurrentArmModelComponent.neckPosition; m_ElbowPosition = m_CurrentArmModelComponent.elbowPosition; m_WristPosition = m_CurrentArmModelComponent.wristPosition; m_ControllerPosition = m_CurrentArmModelComponent.controllerPosition; m_ElbowRotation = m_CurrentArmModelComponent.elbowRotation; m_WristRotation = m_CurrentArmModelComponent.wristRotation; m_ControllerRotation = m_CurrentArmModelComponent.controllerRotation; if (TryGetAngularVelocity(base.poseSource, out var angVel) && armModelBlendData.Count > 0) { float num = Mathf.Clamp((((Vector3)(ref angVel)).magnitude - 0.2f) / 45f, 0f, 0.1f); for (int i = 0; i < armModelBlendData.Count; i++) { ArmModelBlendData value = armModelBlendData[i]; value.currentBlendAmount = Mathf.Lerp(value.currentBlendAmount, 1f, num); if (value.currentBlendAmount > 0.95f) { value.currentBlendAmount = 1f; } else { value.armModel.OnControllerInputUpdated(); m_NeckPosition = Vector3.Slerp(base.neckPosition, value.armModel.neckPosition, value.currentBlendAmount); m_ElbowPosition = Vector3.Slerp(base.elbowPosition, value.armModel.elbowPosition, value.currentBlendAmount); m_WristPosition = Vector3.Slerp(base.wristPosition, value.armModel.wristPosition, value.currentBlendAmount); m_ControllerPosition = Vector3.Slerp(base.controllerPosition, value.armModel.controllerPosition, value.currentBlendAmount); m_ElbowRotation = Quaternion.Slerp(base.elbowRotation, value.armModel.elbowRotation, value.currentBlendAmount); m_WristRotation = Quaternion.Slerp(base.wristRotation, value.armModel.wristRotation, value.currentBlendAmount); m_ControllerRotation = Quaternion.Slerp(base.controllerRotation, value.armModel.controllerRotation, value.currentBlendAmount); } armModelBlendData[i] = value; if (value.currentBlendAmount >= 1f) { m_CurrentArmModelComponent = value.armModel; armModelBlendData.RemoveRange(0, i + 1); } } } else if (armModelBlendData.Count > 0) { Debug.LogErrorFormat((Object)(object)((Component)this).gameObject, "Unable to get angular acceleration for node", Array.Empty<object>()); return false; } base.finalPose = new Pose(base.controllerPosition, base.controllerRotation); return true; } return false; } } }
plugins/Valheim_Data/Managed/Valve.Newtonsoft.Json.dll
Decompiled 5 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Valve.Newtonsoft.Json.Bson; using Valve.Newtonsoft.Json.Converters; using Valve.Newtonsoft.Json.Linq; using Valve.Newtonsoft.Json.Linq.JsonPath; using Valve.Newtonsoft.Json.Serialization; using Valve.Newtonsoft.Json.Utilities; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("Json.NET Unity3D")] [assembly: AllowPartiallyTrustedCallers] [assembly: InternalsVisibleTo("Valve.Newtonsoft.Json.Schema")] [assembly: InternalsVisibleTo("Valve.Newtonsoft.Json.Tests")] [assembly: InternalsVisibleTo("Assembly-CSharp")] [assembly: InternalsVisibleTo("Assembly-CSharp-Editor")] [assembly: InternalsVisibleTo("Valve.Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")] [assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Newtonsoft")] [assembly: AssemblyProduct("Json.NET")] [assembly: AssemblyCopyright("Copyright © James Newton-King 2008")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")] [assembly: AssemblyFileVersion("9.0.1.19813")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("9.0.0.0")] namespace Valve.Newtonsoft.Json { public enum ConstructorHandling { Default, AllowNonPublicDefaultConstructor } public enum DateFormatHandling { IsoDateFormat, MicrosoftDateFormat } public enum DateParseHandling { None, DateTime, DateTimeOffset } public enum DateTimeZoneHandling { Local, Utc, Unspecified, RoundtripKind } [Flags] public enum DefaultValueHandling { Include = 0, Ignore = 1, Populate = 2, IgnoreAndPopulate = 3 } public enum FloatFormatHandling { String, Symbol, DefaultValue } public enum FloatParseHandling { Double, Decimal } public enum Formatting { None, Indented } public interface IArrayPool<T> { T[] Rent(int minimumLength); void Return(T[] array); } public interface IJsonLineInfo { int LineNumber { get; } int LinePosition { get; } bool HasLineInfo(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { private bool _allowNullItems; public bool AllowNullItems { get { return _allowNullItems; } set { _allowNullItems = value; } } public JsonArrayAttribute() { } public JsonArrayAttribute(bool allowNullItems) { _allowNullItems = allowNullItems; } public JsonArrayAttribute(string id) : base(id) { } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)] public sealed class JsonConstructorAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public abstract class JsonContainerAttribute : Attribute { internal bool? _isReference; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; private Type _namingStrategyType; private object[] _namingStrategyParameters; public string Id { get; set; } public string Title { get; set; } public string Description { get; set; } public Type ItemConverterType { get; set; } public object[] ItemConverterParameters { get; set; } public Type NamingStrategyType { get { return _namingStrategyType; } set { _namingStrategyType = value; NamingStrategyInstance = null; } } public object[] NamingStrategyParameters { get { return _namingStrategyParameters; } set { _namingStrategyParameters = value; NamingStrategyInstance = null; } } internal NamingStrategy NamingStrategyInstance { get; set; } public bool IsReference { get { return _isReference ?? false; } set { _isReference = value; } } public bool ItemIsReference { get { return _itemIsReference ?? false; } set { _itemIsReference = value; } } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling ?? TypeNameHandling.None; } set { _itemTypeNameHandling = value; } } protected JsonContainerAttribute() { } protected JsonContainerAttribute(string id) { Id = id; } } public static class JsonConvert { public static readonly string True = "true"; public static readonly string False = "false"; public static readonly string Null = "null"; public static readonly string Undefined = "undefined"; public static readonly string PositiveInfinity = "Infinity"; public static readonly string NegativeInfinity = "-Infinity"; public static readonly string NaN = "NaN"; public static Func<JsonSerializerSettings> DefaultSettings { get; set; } public static string ToString(DateTime value) { return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind); } public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling) { DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling); using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(DateTimeOffset value) { return ToString(value, DateFormatHandling.IsoDateFormat); } public static string ToString(DateTimeOffset value, DateFormatHandling format) { using StringWriter stringWriter = StringUtils.CreateStringWriter(64); stringWriter.Write('"'); DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture); stringWriter.Write('"'); return stringWriter.ToString(); } public static string ToString(bool value) { if (!value) { return False; } return True; } public static string ToString(char value) { return ToString(char.ToString(value)); } public static string ToString(Enum value) { return value.ToString("D"); } public static string ToString(int value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(short value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(long value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(float value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value))) { return text; } if (floatFormatHandling == FloatFormatHandling.DefaultValue) { if (nullable) { return Null; } return "0.0"; } return quoteChar + text + quoteChar; } public static string ToString(double value) { return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)); } internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable) { return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable); } private static string EnsureDecimalPlace(double value, string text) { if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1) { return text; } return text + ".0"; } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1) { return text; } return text + ".0"; } public static string ToString(byte value) { return value.ToString(null, CultureInfo.InvariantCulture); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(null, CultureInfo.InvariantCulture); } public static string ToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture)); } public static string ToString(Guid value) { return ToString(value, '"'); } internal static string ToString(Guid value, char quoteChar) { string text = value.ToString("D", CultureInfo.InvariantCulture); string text2 = quoteChar.ToString(CultureInfo.InvariantCulture); return text2 + text + text2; } public static string ToString(TimeSpan value) { return ToString(value, '"'); } internal static string ToString(TimeSpan value, char quoteChar) { return ToString(value.ToString(), quoteChar); } public static string ToString(Uri value) { if (value == null) { return Null; } return ToString(value, '"'); } internal static string ToString(Uri value, char quoteChar) { return ToString(value.OriginalString, quoteChar); } public static string ToString(string value) { return ToString(value, '"'); } public static string ToString(string value, char delimiter) { return ToString(value, delimiter, StringEscapeHandling.Default); } public static string ToString(string value, char delimiter, StringEscapeHandling stringEscapeHandling) { if (delimiter != '"' && delimiter != '\'') { throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter"); } return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling); } public static string ToString(object value) { if (value == null) { return Null; } return ConvertUtils.GetTypeCode(value.GetType()) switch { PrimitiveTypeCode.String => ToString((string)value), PrimitiveTypeCode.Char => ToString((char)value), PrimitiveTypeCode.Boolean => ToString((bool)value), PrimitiveTypeCode.SByte => ToString((sbyte)value), PrimitiveTypeCode.Int16 => ToString((short)value), PrimitiveTypeCode.UInt16 => ToString((ushort)value), PrimitiveTypeCode.Int32 => ToString((int)value), PrimitiveTypeCode.Byte => ToString((byte)value), PrimitiveTypeCode.UInt32 => ToString((uint)value), PrimitiveTypeCode.Int64 => ToString((long)value), PrimitiveTypeCode.UInt64 => ToString((ulong)value), PrimitiveTypeCode.Single => ToString((float)value), PrimitiveTypeCode.Double => ToString((double)value), PrimitiveTypeCode.DateTime => ToString((DateTime)value), PrimitiveTypeCode.Decimal => ToString((decimal)value), PrimitiveTypeCode.DBNull => Null, PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), PrimitiveTypeCode.Guid => ToString((Guid)value), PrimitiveTypeCode.Uri => ToString((Uri)value), PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), _ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), }; } public static string SerializeObject(object value) { return SerializeObject(value, (Type)null, (JsonSerializerSettings)null); } public static string SerializeObject(object value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings)null); } public static string SerializeObject(object value, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, settings); } public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return SerializeObject(value, null, formatting, settings); } public static string SerializeObject(object value, JsonSerializerSettings settings) { return SerializeObject(value, null, settings); } public static string SerializeObject(object value, Type type, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); return SerializeObjectInternal(value, type, jsonSerializer); } public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings) { return SerializeObject(value, null, formatting, settings); } public static string SerializeObject(object value, Type type, Formatting formatting, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); jsonSerializer.Formatting = formatting; return SerializeObjectInternal(value, type, jsonSerializer); } private static string SerializeObjectInternal(object value, Type type, JsonSerializer jsonSerializer) { StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture); using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter)) { jsonTextWriter.Formatting = jsonSerializer.Formatting; jsonSerializer.Serialize(jsonTextWriter, value, type); } return stringWriter.ToString(); } public static object DeserializeObject(string value) { return DeserializeObject(value, (Type)null, (JsonSerializerSettings)null); } public static object DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); } public static object DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings)null); } public static T DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings)null); } public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject) { return DeserializeObject<T>(value); } public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject<T>(value, settings); } public static T DeserializeObject<T>(string value, params JsonConverter[] converters) { return (T)DeserializeObject(value, typeof(T), converters); } public static T DeserializeObject<T>(string value, JsonSerializerSettings settings) { return (T)DeserializeObject(value, typeof(T), settings); } public static object DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings { Converters = converters } : null); return DeserializeObject(value, type, settings); } public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings) { ValidationUtils.ArgumentNotNull(value, "value"); JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); if (!jsonSerializer.IsCheckAdditionalContentSet()) { jsonSerializer.CheckAdditionalContent = true; } using JsonTextReader reader = new JsonTextReader(new StringReader(value)); return jsonSerializer.Deserialize(reader, type); } public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); } public static void PopulateObject(string value, object target, JsonSerializerSettings settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); using JsonReader jsonReader = new JsonTextReader(new StringReader(value)); jsonSerializer.Populate(jsonReader, target); if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) { throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object."); } } } public abstract class JsonConverter { public virtual bool CanRead => true; public virtual bool CanWrite => true; public abstract void WriteJson(JsonWriter writer, object value, JsonSerializer serializer); public abstract object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer); public abstract bool CanConvert(Type objectType); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonConverterAttribute : Attribute { private readonly Type _converterType; public Type ConverterType => _converterType; public object[] ConverterParameters { get; private set; } public JsonConverterAttribute(Type converterType) { if ((object)converterType == null) { throw new ArgumentNullException("converterType"); } _converterType = converterType; } public JsonConverterAttribute(Type converterType, params object[] converterParameters) : this(converterType) { ConverterParameters = converterParameters; } } public class JsonConverterCollection : Collection<JsonConverter> { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonDictionaryAttribute : JsonContainerAttribute { public JsonDictionaryAttribute() { } public JsonDictionaryAttribute(string id) : base(id) { } } [Serializable] public class JsonException : Exception { public JsonException() { } public JsonException(string message) : base(message) { } public JsonException(string message, Exception innerException) : base(message, innerException) { } public JsonException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonException(message); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public class JsonExtensionDataAttribute : Attribute { public bool WriteData { get; set; } public bool ReadData { get; set; } public JsonExtensionDataAttribute() { WriteData = true; ReadData = true; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonObjectAttribute : JsonContainerAttribute { private MemberSerialization _memberSerialization; internal Required? _itemRequired; public MemberSerialization MemberSerialization { get { return _memberSerialization; } set { _memberSerialization = value; } } public Required ItemRequired { get { return _itemRequired ?? Required.Default; } set { _itemRequired = value; } } public JsonObjectAttribute() { } public JsonObjectAttribute(MemberSerialization memberSerialization) { MemberSerialization = memberSerialization; } public JsonObjectAttribute(string id) : base(id) { } } internal enum JsonContainerType { None, Object, Array, Constructor } internal struct JsonPosition { private static readonly char[] SpecialCharacters = new char[6] { '.', ' ', '[', ']', '(', ')' }; internal JsonContainerType Type; internal int Position; internal string PropertyName; internal bool HasIndex; public JsonPosition(JsonContainerType type) { Type = type; HasIndex = TypeHasIndex(type); Position = -1; PropertyName = null; } internal int CalculateLength() { switch (Type) { case JsonContainerType.Object: return PropertyName.Length + 5; case JsonContainerType.Array: case JsonContainerType.Constructor: return MathUtils.IntLength((ulong)Position) + 2; default: throw new ArgumentOutOfRangeException("Type"); } } internal void WriteTo(StringBuilder sb) { switch (Type) { case JsonContainerType.Object: { string propertyName = PropertyName; if (propertyName.IndexOfAny(SpecialCharacters) != -1) { sb.Append("['"); sb.Append(propertyName); sb.Append("']"); break; } if (sb.Length > 0) { sb.Append('.'); } sb.Append(propertyName); break; } case JsonContainerType.Array: case JsonContainerType.Constructor: sb.Append('['); sb.Append(Position); sb.Append(']'); break; } } internal static bool TypeHasIndex(JsonContainerType type) { if (type != JsonContainerType.Array) { return type == JsonContainerType.Constructor; } return true; } internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition) { int num = 0; if (positions != null) { for (int i = 0; i < positions.Count; i++) { num += positions[i].CalculateLength(); } } if (currentPosition.HasValue) { num += currentPosition.GetValueOrDefault().CalculateLength(); } StringBuilder stringBuilder = new StringBuilder(num); if (positions != null) { foreach (JsonPosition position in positions) { position.WriteTo(stringBuilder); } } currentPosition?.WriteTo(stringBuilder); return stringBuilder.ToString(); } internal static string FormatMessage(IJsonLineInfo lineInfo, string path, string message) { if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { message = message.Trim(); if (!StringUtils.EndsWith(message, '.')) { message += "."; } message += " "; } message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); if (lineInfo != null && lineInfo.HasLineInfo()) { message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); } message += "."; return message; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; public Type ItemConverterType { get; set; } public object[] ItemConverterParameters { get; set; } public Type NamingStrategyType { get; set; } public object[] NamingStrategyParameters { get; set; } public NullValueHandling NullValueHandling { get { return _nullValueHandling ?? NullValueHandling.Include; } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling ?? DefaultValueHandling.Include; } set { _defaultValueHandling = value; } } public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _referenceLoopHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling ?? ObjectCreationHandling.Auto; } set { _objectCreationHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling ?? TypeNameHandling.None; } set { _typeNameHandling = value; } } public bool IsReference { get { return _isReference ?? false; } set { _isReference = value; } } public int Order { get { return _order ?? 0; } set { _order = value; } } public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } public string PropertyName { get; set; } public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _itemReferenceLoopHandling = value; } } public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling ?? TypeNameHandling.None; } set { _itemTypeNameHandling = value; } } public bool ItemIsReference { get { return _itemIsReference ?? false; } set { _itemIsReference = value; } } public JsonPropertyAttribute() { } public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } public abstract class JsonReader : IDisposable { protected internal enum State { Start, Complete, Property, ObjectStart, Object, ArrayStart, Array, Closed, PostValue, ConstructorStart, Constructor, Error, Finished } private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; protected State CurrentState => _currentState; public bool CloseInput { get; set; } public bool SupportMultipleContent { get; set; } public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException("value"); } _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset) { throw new ArgumentOutOfRangeException("value"); } _dateParseHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException("value"); } _floatParseHandling = value; } } public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; } } public virtual JsonToken TokenType => _tokenType; public virtual object Value => _value; public virtual Type ValueType { get { if (_value == null) { return null; } return _value.GetType(); } } public virtual int Depth { get { int num = ((_stack != null) ? _stack.Count : 0); if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return num; } return num + 1; } } public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null); return JsonPosition.BuildPath(_stack, currentPosition); } } public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); return; } if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); if (_maxDepth.HasValue) { int num = Depth + 1; int? maxDepth = _maxDepth; if (num > maxDepth.GetValueOrDefault() && maxDepth.HasValue && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition currentPosition; if (_stack != null && _stack.Count > 0) { currentPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { currentPosition = _currentPosition; _currentPosition = default(JsonPosition); } if (_maxDepth.HasValue && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return currentPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } public abstract bool Read(); public virtual int? ReadAsInt32() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is int)) { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), updateIndex: false); } return (int)Value; case JsonToken.String: { string s = (string)Value; return ReadInt32String(s); } default: throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (int.TryParse(s, NumberStyles.Integer, Culture, out var result)) { SetToken(JsonToken.Integer, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual string ReadAsString() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; default: if (JsonTokenUtils.IsPrimitiveToken(contentToken) && Value != null) { string text = ((Value is IFormattable) ? ((IFormattable)Value).ToString(null, Culture) : ((!(Value is Uri)) ? Value.ToString() : ((Uri)Value).OriginalString)); SetToken(JsonToken.String, text, updateIndex: false); return text; } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } public virtual byte[] ReadAsBytes() { JsonToken contentToken = GetContentToken(); if (contentToken == JsonToken.None) { return null; } if (TokenType == JsonToken.StartObject) { ReadIntoWrappedTypeObject(); byte[] array = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } switch (contentToken) { case JsonToken.String: { string text = (string)Value; Guid g; byte[] array3 = ((text.Length == 0) ? new byte[0] : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray())); SetToken(JsonToken.Bytes, array3, updateIndex: false); return array3; } case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if ((object)ValueType == typeof(Guid)) { byte[] array2 = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, array2, updateIndex: false); return array2; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); default: throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal byte[] ReadArrayIntoByteArray() { List<byte> list = new List<byte>(); while (true) { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: break; case JsonToken.EndArray: { byte[] array = list.ToArray(); SetToken(JsonToken.Bytes, array, updateIndex: false); return array; } default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } list.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); } } public virtual double? ReadAsDouble() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is double)) { double num = Convert.ToDouble(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Float, num, updateIndex: false); } return (double)Value; case JsonToken.String: return ReadDoubleString((string)Value); default: throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual bool? ReadAsBoolean() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: { bool flag = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Boolean, flag, updateIndex: false); return flag; } case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; default: throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (bool.TryParse(s, out var result)) { SetToken(JsonToken.Boolean, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual decimal? ReadAsDecimal() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is decimal)) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), updateIndex: false); } return (decimal)Value; case JsonToken.String: return ReadDecimalString((string)Value); default: throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result)) { SetToken(JsonToken.Float, result, updateIndex: false); return result; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTimeOffset) { SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, updateIndex: false); } return (DateTime)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken contentToken = GetContentToken(); switch (contentToken) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime) { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), updateIndex: false); } return (DateTimeOffset)Value; case JsonToken.String: { string s = (string)Value; return ReadDateTimeOffsetString(s); } default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, updateIndex: false); return null; } if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return dt; } SetToken(JsonToken.String, s, updateIndex: false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value.ToString() == "$type") { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == "$value") { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && depth < Depth) { } } } protected void SetToken(JsonToken newToken) { SetToken(newToken, null, updateIndex: true); } protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, updateIndex: true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Raw: case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: SetPostValueState(updateIndex); break; case JsonToken.Comment: break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != 0) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType jsonContainerType = Pop(); if (GetTypeForCloseToken(endToken) != jsonContainerType) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType)); } if (Peek() != 0) { _currentState = State.PostValue; } else { SetFinished(); } } protected void SetStateBasedOnCurrent() { JsonContainerType jsonContainerType = Peek(); switch (jsonContainerType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType)); } } private void SetFinished() { if (SupportMultipleContent) { _currentState = State.Start; } else { _currentState = State.Finished; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { return token switch { JsonToken.EndObject => JsonContainerType.Object, JsonToken.EndArray => JsonContainerType.Array, JsonToken.EndConstructor => JsonContainerType.Constructor, _ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), }; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadAndMoveToContent() { if (Read()) { return MoveToContent(); } return false; } internal bool MoveToContent() { JsonToken tokenType = TokenType; while (tokenType == JsonToken.None || tokenType == JsonToken.Comment) { if (!Read()) { return false; } tokenType = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken tokenType; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } tokenType = TokenType; } while (tokenType == JsonToken.Comment); return tokenType; } } [Serializable] public class JsonReaderException : JsonException { public int LineNumber { get; private set; } public int LinePosition { get; private set; } public string Path { get; private set; } public JsonReaderException() { } public JsonReaderException(string message) : base(message) { } public JsonReaderException(string message, Exception innerException) : base(message, innerException) { } public JsonReaderException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal JsonReaderException(string message, Exception innerException, string path, int lineNumber, int linePosition) : base(message, innerException) { Path = path; LineNumber = lineNumber; LinePosition = linePosition; } internal static JsonReaderException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); int lineNumber; int linePosition; if (lineInfo != null && lineInfo.HasLineInfo()) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = 0; linePosition = 0; } return new JsonReaderException(message, ex, path, lineNumber, linePosition); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] public sealed class JsonRequiredAttribute : Attribute { } [Serializable] public class JsonSerializationException : JsonException { public JsonSerializationException() { } public JsonSerializationException(string message) : base(message) { } public JsonSerializationException(string message, Exception innerException) : base(message, innerException) { } public JsonSerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } internal static JsonSerializationException Create(JsonReader reader, string message) { return Create(reader, message, null); } internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) { return Create(reader as IJsonLineInfo, reader.Path, message, ex); } internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) { message = JsonPosition.FormatMessage(lineInfo, path, message); return new JsonSerializationException(message, ex); } } public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal FormatterAssemblyStyle _typeNameAssemblyFormat; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal IEqualityComparer _equalityComparer; internal SerializationBinder _binder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException("value", "Reference resolver cannot be null."); } _referenceResolver = value; } } public virtual SerializationBinder Binder { get { return _binder; } set { if (value == null) { throw new ArgumentNullException("value", "Serialization binder cannot be null."); } _binder = value; } } public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } public virtual IEqualityComparer EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException("value"); } _typeNameHandling = value; } } public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException("value"); } _typeNameAssemblyFormat = value; } } public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException("value"); } _preserveReferencesHandling = value; } } public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException("value"); } _referenceLoopHandling = value; } } public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException("value"); } _missingMemberHandling = value; } } public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _nullValueHandling = value; } } public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException("value"); } _defaultValueHandling = value; } } public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException("value"); } _objectCreationHandling = value; } } public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException("value"); } _constructorHandling = value; } } public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException("value"); } _metadataPropertyHandling = value; } } public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } public virtual StreamingContext Context { get { return _context; } set { _context = value; } } public virtual Formatting Formatting { get { return _formatting ?? Formatting.None; } set { _formatting = value; } } public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? DateFormatHandling.IsoDateFormat; } set { _dateFormatHandling = value; } } public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? FloatParseHandling.Double; } set { _floatParseHandling = value; } } public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? FloatFormatHandling.String; } set { _floatFormatHandling = value; } } public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? StringEscapeHandling.Default; } set { _stringEscapeHandling = value; } } public virtual string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? false; } set { _checkAdditionalContent = value; } } public virtual event EventHandler<Valve.Newtonsoft.Json.Serialization.ErrorEventArgs> Error; internal bool IsCheckAdditionalContentSet() { return _checkAdditionalContent.HasValue; } public JsonSerializer() { _referenceLoopHandling = ReferenceLoopHandling.Error; _missingMemberHandling = MissingMemberHandling.Ignore; _nullValueHandling = NullValueHandling.Include; _defaultValueHandling = DefaultValueHandling.Include; _objectCreationHandling = ObjectCreationHandling.Auto; _preserveReferencesHandling = PreserveReferencesHandling.None; _constructorHandling = ConstructorHandling.Default; _typeNameHandling = TypeNameHandling.None; _metadataPropertyHandling = MetadataPropertyHandling.Default; _context = JsonSerializerSettings.DefaultContext; _binder = DefaultSerializationBinder.Instance; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } public static JsonSerializer Create() { return new JsonSerializer(); } public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer jsonSerializer = Create(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } public static JsonSerializer CreateDefault() { return Create(JsonConvert.DefaultSettings?.Invoke()); } public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer jsonSerializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(jsonSerializer, settings); } return jsonSerializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } if (settings._typeNameHandling.HasValue) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling.HasValue) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormat.HasValue) { serializer.TypeNameAssemblyFormat = settings.TypeNameAssemblyFormat; } if (settings._preserveReferencesHandling.HasValue) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling.HasValue) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling.HasValue) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling.HasValue) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling.HasValue) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling.HasValue) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling.HasValue) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context.HasValue) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent.HasValue) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.Binder != null) { serializer.Binder = settings.Binder; } if (settings._formatting.HasValue) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling.HasValue) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling.HasValue) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling.HasValue) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling.HasValue) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling.HasValue) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling.HasValue) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } } public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(target, "target"); SetupReader(reader, out var previousCulture, out var previousDateTimeZoneHandling, out var previousDateParseHandling, out var previousFloatParseHandling, out var previousMaxDepth, out var previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null); new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, "reader"); SetupReader(reader, out var previousCulture, out var previousDateTimeZoneHandling, out var previousDateParseHandling, out var previousFloatParseHandling, out var previousMaxDepth, out var previousDateFormatString); TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null); object result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return result; } private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (reader is JsonTextReader jsonTextReader && _contractResolver is DefaultContractResolver defaultContractResolver) { jsonTextReader.NameTable = defaultContractResolver.GetState().NameTable; } } private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling.HasValue) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling.HasValue) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling.HasValue) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } if (reader is JsonTextReader jsonTextReader) { jsonTextReader.NameTable = null; } } public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter"); Formatting? formatting = null; if (_formatting.HasValue && jsonWriter.Formatting != _formatting) { formatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? dateFormatHandling = null; if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling) { dateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? dateTimeZoneHandling = null; if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? floatFormatHandling = null; if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling) { floatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? stringEscapeHandling = null; if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { stringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo cultureInfo = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { cultureInfo = jsonWriter.Culture; jsonWriter.Culture = _culture; } string dateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { dateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null); new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } if (formatting.HasValue) { jsonWriter.Formatting = formatting.GetValueOrDefault(); } if (dateFormatHandling.HasValue) { jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault(); } if (dateTimeZoneHandling.HasValue) { jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault(); } if (floatFormatHandling.HasValue) { jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault(); } if (stringEscapeHandling.HasValue) { jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = dateFormatString; } if (cultureInfo != null) { jsonWriter.Culture = cultureInfo; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter jsonConverter = converters[i]; if (jsonConverter.CanConvert(objectType)) { return jsonConverter; } } } return null; } internal void OnError(Valve.Newtonsoft.Json.Serialization.ErrorEventArgs e) { this.Error?.Invoke(this, e); } } public class JsonSerializerSettings { internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error; internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore; internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include; internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include; internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto; internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None; internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default; internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None; internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default; internal const FormatterAssemblyStyle DefaultTypeNameAssemblyFormat = FormatterAssemblyStyle.Simple; internal static readonly StreamingContext DefaultContext; internal const Formatting DefaultFormatting = Formatting.None; internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat; internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime; internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double; internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String; internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default; internal const FormatterAssemblyStyle DefaultFormatterAssemblyStyle = FormatterAssemblyStyle.Simple; internal static readonly CultureInfo DefaultCulture; internal const bool DefaultCheckAdditionalContent = false; internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; internal Formatting? _formatting; internal DateFormatHandling? _dateFormatHandling; internal DateTimeZoneHandling? _dateTimeZoneHandling; internal DateParseHandling? _dateParseHandling; internal FloatFormatHandling? _floatFormatHandling; internal FloatParseHandling? _floatParseHandling; internal StringEscapeHandling? _stringEscapeHandling; internal CultureInfo _culture; internal bool? _checkAdditionalContent; internal int? _maxDepth; internal bool _maxDepthSet; internal string _dateFormatString; internal bool _dateFormatStringSet; internal FormatterAssemblyStyle? _typeNameAssemblyFormat; internal DefaultValueHandling? _defaultValueHandling; internal PreserveReferencesHandling? _preserveReferencesHandling; internal NullValueHandling? _nullValueHandling; internal ObjectCreationHandling? _objectCreationHandling; internal MissingMemberHandling? _missingMemberHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal StreamingContext? _context; internal ConstructorHandling? _constructorHandling; internal TypeNameHandling? _typeNameHandling; internal MetadataPropertyHandling? _metadataPropertyHandling; public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling ?? ReferenceLoopHandling.Error; } set { _referenceLoopHandling = value; } } public MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling ?? MissingMemberHandling.Ignore; } set { _missingMemberHandling = value; } } public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling ?? ObjectCreationHandling.Auto; } set { _objectCreationHandling = value; } } public NullValueHandling NullValueHandling { get { return _nullValueHandling ?? NullValueHandling.Include; } set { _nullValueHandling = value; } } public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling ?? DefaultValueHandling.Include; } set { _defaultValueHandling = value; } } public IList<JsonConverter> Converters { get; set; } public PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling ?? PreserveReferencesHandling.None; } set { _preserveReferencesHandling = value; } } public TypeNameHandling TypeNameHandling { get { return _typeNameHandling ?? TypeNameHandling.None; } set { _typeNameHandling = value; } } public MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling ?? MetadataPropertyHandling.Default; } set { _metadataPropertyHandling = value; } } public FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _typeNameAssemblyFormat ?? FormatterAssemblyStyle.Simple; } set { _typeNameAssemblyFormat = value; } } public ConstructorHandling ConstructorHandling { get { return _constructorHandling ?? ConstructorHandling.Default; } set { _constructorHandling = value; } } public IContractResolver ContractResolver { get; set; } public IEqualityComparer EqualityComparer { get; set; } [Obsolete("ReferenceResolver property is obsolete. Use the ReferenceResolverProvider property to set the IReferenceResolver: settings.ReferenceResolverProvider = () => resolver")] public IReferenceResolver ReferenceResolver { get { if (ReferenceResolverProvider == null) { return null; } return ReferenceResolverProvider(); } set { ReferenceResolverProvider = ((value != null) ? ((Func<IReferenceResolver>)(() => value)) : null); } } public Func<IReferenceResolver> ReferenceResolverProvider { get; set; } public ITraceWriter TraceWriter { get; set; } public SerializationBinder Binder { get; set; } public EventHandler<Valve.Newtonsoft.Json.Serialization.ErrorEventArgs> Error { get; set; } public StreamingContext Context { get { return _context ?? DefaultContext; } set { _context = value; } } public string DateFormatString { get { return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK"; } set { _dateFormatString = value; _dateFormatStringSet = true; } } public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", "value"); } _maxDepth = value; _maxDepthSet = true; } } public Formatting Formatting { get { return _formatting ?? Formatting.None; } set { _formatting = value; } } public DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? DateFormatHandling.IsoDateFormat; } set { _dateFormatHandling = value; } } public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind; } set { _dateTimeZoneHandling = value; } } public DateParseHandling DateParseHandling { get { return _dateParseHandling ?? DateParseHandling.DateTime; } set { _dateParseHandling = value; } } public FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? FloatFormatHandling.String; } set { _floatFormatHandling = value; } } public FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? FloatParseHandling.Double; } set { _floatParseHandling = value; } } public StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? StringEscapeHandling.Default; } set { _stringEscapeHandling = value; } } public CultureInfo Culture { get { return _culture ?? DefaultCulture; } set { _culture = value; } } public bool CheckAdditionalContent { get { return _checkAdditionalContent ?? false; } set { _checkAdditionalContent = value; } } static JsonSerializerSettings() { DefaultContext = default(StreamingContext); DefaultCulture = CultureInfo.InvariantCulture; } public JsonSerializerSettings() { Converters = new List<JsonConverter>(); } } internal enum ReadType { Read, ReadAsInt32, ReadAsBytes, ReadAsString, ReadAsDecimal, ReadAsDateTime, ReadAsDateTimeOffset, ReadAsDouble, ReadAsBoolean } public class JsonTextReader : JsonReader, IJsonLineInfo { private const char UnicodeReplacementChar = '\ufffd'; private const int MaximumJavascriptIntegerCharacterLength = 380; private readonly TextReader _reader; private char[] _chars; private int _charsUsed; private int _charPos; private int _lineStartPos; private int _lineNumber; private bool _isEndOfFile; private StringBuffer _stringBuffer; private StringReference _stringReference; private IArrayPool<char> _arrayPool; internal PropertyNameTable NameTable; public IArrayPool<char> ArrayPool { get { return _arrayPool; } set { if (value == null) { throw new ArgumentNullException("value"); } _arrayPool = value; } } public int LineNumber { get { if (base.CurrentState == State.Start && LinePosition == 0 && TokenType != JsonToken.Comment) { return 0; } return _lineNumber; } } public int LinePosition => _charPos - _lineStartPos; public JsonTextReader(TextReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } _reader = reader; _lineNumber = 1; } private void EnsureBufferNotEmpty() { if (_stringBuffer.IsEmpty) { _stringBuffer = new StringBuffer(_arrayPool, 1024); } } private void OnNewLine(int pos) { _lineNumber++; _lineStartPos = pos; } private void ParseString(char quote, ReadType readType) { _charPos++; ShiftBufferIfNeeded(); ReadStringIntoBuffer(quote); SetPostValueState(updateIndex: true); switch (readType) { case ReadType.ReadAsBytes: { Guid g; byte[] value2 = ((_stringReference.Length == 0) ? new byte[0] : ((_stringReference.Length != 36 || !ConvertUtils.TryConvertGuid(_stringReference.ToString(), out g)) ? Convert.FromBase64CharArray(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length) : g.ToByteArray())); SetToken(JsonToken.Bytes, value2, updateIndex: false); return; } case ReadType.ReadAsString: { string value = _stringReference.ToString(); SetToken(JsonToken.String, value, updateIndex: false); _quoteChar = quote; return; } case ReadType.ReadAsInt32: case ReadType.ReadAsDecimal: case ReadType.ReadAsBoolean: return; } if (_dateParseHandling != 0) { DateTimeOffset dt2; if (readType switch { ReadType.ReadAsDateTime => 1, ReadType.ReadAsDateTimeOffset => 2, _ => (int)_dateParseHandling, } == 1) { if (DateTimeUtils.TryParseDateTime(_stringReference, base.DateTimeZoneHandling, base.DateFormatString, base.Culture, out var dt)) { SetToken(JsonToken.Date, dt, updateIndex: false); return; } } else if (DateTimeUtils.TryParseDateTimeOffset(_stringReference, base.DateFormatString, base.Culture, out dt2)) { SetToken(JsonToken.Date, dt2, updateIndex: false); return; } } SetToken(JsonToken.String, _stringReference.ToString(), updateIndex: false); _quoteChar = quote; } private static void BlockCopyChars(char[] src, int srcOffset, char[] dst, int dstOffset, int count) { Buffer.BlockCopy(src, srcOffset * 2, dst, dstOffset * 2, count * 2); } private void ShiftBufferIfNeeded() { int num = _chars.Length; if ((double)(num - _charPos) <= (double)num * 0.1) { int num2 = _charsUsed - _charPos; if (num2 > 0) { BlockCopyChars(_chars, _charPos, _chars, 0, num2); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = num2; _chars[_charsUsed] = '\0'; } } private int ReadData(bool append) { return ReadData(append, 0); } private int ReadData(bool append, int charsRequired) { if (_isEndOfFile) { return 0; } if (_charsUsed + charsRequired >= _chars.Length - 1) { if (append) { int minSize = Math.Max(_chars.Length * 2, _charsUsed + charsRequired + 1); char[] array = BufferUtils.RentBuffer(_arrayPool, minSize); BlockCopyChars(_chars, 0, array, 0, _chars.Length); BufferUtils.ReturnBuffer(_arrayPool, _chars); _chars = array; } else { int num = _charsUsed - _charPos; if (num + charsRequired + 1 >= _chars.Length) { char[] array2 = BufferUtils.RentBuffer(_arrayPool, num + charsRequired + 1); if (num > 0) { BlockCopyChars(_chars, _charPos, array2, 0, num); } BufferUtils.ReturnBuffer(_arrayPool, _chars); _chars = array2; } else if (num > 0) { BlockCopyChars(_chars, _charPos, _chars, 0, num); } _lineStartPos -= _charPos; _charPos = 0; _charsUsed = num; } } int count = _chars.Length - _charsUsed - 1; int num2 = _reader.Read(_chars, _charsUsed, count); _charsUsed += num2; if (num2 == 0) { _isEndOfFile = true; } _chars[_charsUsed] = '\0'; return num2; } private bool EnsureChars(int relativePosition, bool append) { if (_charPos + relativePosition >= _charsUsed) { return ReadChars(relativePosition, append); } return true; } private bool ReadChars(int relativePosition, bool append) { if (_isEndOfFile) { return false; } int num = _charPos + relativePosition - _charsUsed + 1; int num2 = 0; do { int num3 = ReadData(append, num - num2); if (num3 == 0) { break; } num2 += num3; } while (num2 < num); if (num2 < num) { return false; } return true; } public override bool Read() { EnsureBuffer(); do { switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.ConstructorStart: case State.Constructor: return ParseValue(); case State.ObjectStart: case State.Object: return ParseObject(); case State.PostValue: break; case State.Finished: if (EnsureChars(0, append: false)) { EatWhitespace(oneOrMore: false); if (_isEndOfFile) { SetToken(JsonToken.None); return false; } if (_chars[_charPos] == '/') { ParseComment(setToken: true); return true; } throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } SetToken(JsonToken.None); return false; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } while (!ParsePostValue()); return true; } public override int? ReadAsInt32() { return (int?)ReadNumberValue(ReadType.ReadAsInt32); } public override DateTime? ReadAsDateTime() { return (DateTime?)ReadStringValue(ReadType.ReadAsDateTime); } public override string ReadAsString() { return (string)ReadStringValue(ReadType.ReadAsString); } public override byte[] ReadAsBytes() { EnsureBuffer(); bool flag = false; switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': { ParseString(c, ReadType.ReadAsBytes); byte[] array = (byte[])Value; if (flag) { ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, array, updateIndex: false); } return array; } case '{': _charPos++; SetToken(JsonToken.StartObject); ReadIntoWrappedTypeObject(); flag = true; break; case '[': _charPos++; SetToken(JsonToken.StartArray); return ReadArrayIntoByteArray(); case 'n': HandleNull(); return null; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private object ReadStringValue(ReadType readType) { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, readType); switch (readType) { case ReadType.ReadAsBytes: return Value; case ReadType.ReadAsString: return Value; case ReadType.ReadAsDateTime: if (Value is DateTime) { return (DateTime)Value; } return ReadDateTimeString((string)Value); case ReadType.ReadAsDateTimeOffset: if (Value is DateTimeOffset) { return (DateTimeOffset)Value; } return ReadDateTimeOffsetString((string)Value); default: throw new ArgumentOutOfRangeException("readType"); } case '-': if (EnsureChars(1, append: true) && _chars[_charPos + 1] == 'I') { return ParseNumberNegativeInfinity(readType); } ParseNumber(readType); return Value; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(c); } ParseNumber(ReadType.ReadAsString); return Value; case 'f': case 't': { if (readType != ReadType.ReadAsString) { _charPos++; throw CreateUnexpectedCharacterException(c); } string text = ((c == 't') ? JsonConvert.True : JsonConvert.False); if (!MatchValueWithTrailingSeparator(text)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.String, text); return text; } case 'I': return ParseNumberPositiveInfinity(readType); case 'N': return ParseNumberNaN(readType); case 'n': HandleNull(); return null; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private JsonReaderException CreateUnexpectedCharacterException(char c) { return JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, c)); } public override bool? ReadAsBoolean() { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, ReadType.Read); return ReadBooleanString(_stringReference.ToString()); case 'n': HandleNull(); return null; case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { ParseNumber(ReadType.Read); bool flag2 = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); SetToken(JsonToken.Boolean, flag2, updateIndex: false); return flag2; } case 'f': case 't': { bool flag = c == 't'; string value = (flag ? JsonConvert.True : JsonConvert.False); if (!MatchValueWithTrailingSeparator(value)) { throw CreateUnexpectedCharacterException(_chars[_charPos]); } SetToken(JsonToken.Boolean, flag); return flag; } case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } private void ProcessValueComma() { _charPos++; if (_currentState != State.PostValue) { SetToken(JsonToken.Undefined); throw CreateUnexpectedCharacterException(','); } SetStateBasedOnCurrent(); } private object ReadNumberValue(ReadType readType) { EnsureBuffer(); switch (_currentState) { case State.Start: case State.Property: case State.ArrayStart: case State.Array: case State.PostValue: case State.ConstructorStart: case State.Constructor: while (true) { char c = _chars[_charPos]; switch (c) { case '\0': if (ReadNullChar()) { SetToken(JsonToken.None, null, updateIndex: false); return null; } break; case '"': case '\'': ParseString(c, readType); return readType switch { ReadType.ReadAsInt32 => ReadInt32String(_stringReference.ToString()), ReadType.ReadAsDecimal => ReadDecimalString(_stringReference.ToString()), ReadType.ReadAsDouble => ReadDoubleString(_stringReference.ToString()), _ => throw new ArgumentOutOfRangeException("readType"), }; case 'n': HandleNull(); return null; case 'N': return ParseNumberNaN(readType); case 'I': return ParseNumberPositiveInfinity(readType); case '-': if (EnsureChars(1, append: true) && _chars[_charPos + 1] == 'I') { return ParseNumberNegativeInfinity(readType); } ParseNumber(readType); return Value; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ParseNumber(readType); return Value; case '/': ParseComment(setToken: false); break; case ',': ProcessValueComma(); break; case ']': _charPos++; if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue) { SetToken(JsonToken.EndArray); return null; } throw CreateUnexpectedCharacterException(c); case '\r': ProcessCarriageReturn(append: false); break; case '\n': ProcessLineFeed(); break; case '\t': case ' ': _charPos++; break; default: _charPos++; if (!char.IsWhiteSpace(c)) { throw CreateUnexpectedCharacterException(c); } break; } } case State.Finished: ReadFinished(); return null; default: throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, base.CurrentState)); } } public override DateTimeOffset? ReadAsDateTimeOffset() { return (DateTimeOffset?)ReadStringValue(ReadType.ReadAsDateTimeOffset); } public override decimal? ReadAsDecimal() { return (decimal?)ReadNumberValue(ReadType.ReadAsDecimal); } public override double? ReadAsDouble() { return (double?)ReadNumberValue(ReadType.ReadAsDouble); } private void HandleNull() { if (EnsureChars(1, append: true)) { if (_chars[_charPos + 1] == 'u') { ParseNull(); return; } _charPos += 2; throw CreateUnexpectedCharacterException(_chars[_charPos - 1]); } _charPos =