Decompiled source of Preben Mod v1.7.7

BepInEx/plugins/Preben_Mod/ForgePhotoHead.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using HarmonyLib;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Rendering;

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

[Serializable]
public class MeshSkin
{
	public string mesh;

	public string texture;

	public string geometry;
}
[Serializable]
public class VisualFit
{
	public string mesh;

	public string anchorMesh;

	public float[] localPosition;

	public float[] localScale;

	public float[] localRotation;

	public bool hide;
}
[Serializable]
public class PhotoSettings
{
	public int format;

	public string mode;

	public MeshSkin[] meshes;

	public string[] hiddenRenderers;

	public VisualFit[] visualFits;
}
[Serializable]
public class PortraitGeometry
{
	public float[] vertices;

	public int[] triangles;

	public float[] uv;

	public float[] normals;
}
[BepInPlugin("local.repomodforge.photohead", "Forge 3D Photo Head", "3.0.1")]
[BepInProcess("REPO.exe")]
public sealed class PhotoHeadPlugin : BaseUnityPlugin
{
	internal static PhotoHeadPlugin Instance;

	internal readonly Dictionary<string, Texture2D> Textures = new Dictionary<string, Texture2D>();

	internal readonly Dictionary<string, Mesh> Meshes = new Dictionary<string, Mesh>();

	internal readonly HashSet<string> HiddenRenderers = new HashSet<string>();

	internal readonly Dictionary<string, VisualFit> VisualFits = new Dictionary<string, VisualFit>();

	private bool ready;

	private Harmony harmony;

	internal static string SafePath(string folder, string relative)
	{
		if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative))
		{
			throw new Exception("Pack files must use relative paths.");
		}
		string text = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
		string fullPath = Path.GetFullPath(Path.Combine(text, relative));
		if (!fullPath.StartsWith(text + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
		{
			throw new Exception("Pack file must be inside its own folder.");
		}
		return fullPath;
	}

	internal static void ValidateGeometry(PortraitGeometry data)
	{
		if (data == null || data.vertices == null || data.vertices.Length == 0 || data.vertices.Length % 3 != 0)
		{
			throw new Exception("Malformed portrait vertices.");
		}
		int num = data.vertices.Length / 3;
		if (num > 100000 || data.uv == null || data.uv.Length != num * 2 || data.normals == null || data.normals.Length != num * 3 || data.triangles == null || data.triangles.Length == 0 || data.triangles.Length % 3 != 0)
		{
			throw new Exception("Invalid portrait array lengths.");
		}
		float[][] array = new float[3][] { data.vertices, data.uv, data.normals };
		foreach (float[] array2 in array)
		{
			foreach (float f in array2)
			{
				if (float.IsNaN(f) || float.IsInfinity(f))
				{
					throw new Exception("Non-finite portrait coordinate.");
				}
			}
		}
		int[] triangles = data.triangles;
		foreach (int num2 in triangles)
		{
			if (num2 < 0 || num2 >= num)
			{
				throw new Exception("Invalid portrait triangle index.");
			}
		}
	}

	private static Mesh LoadGeometry(string path)
	{
		//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_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_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)
		//IL_00da: Expected O, but got Unknown
		PortraitGeometry portraitGeometry = JsonConvert.DeserializeObject<PortraitGeometry>(File.ReadAllText(path));
		ValidateGeometry(portraitGeometry);
		int num = portraitGeometry.vertices.Length / 3;
		Vector3[] array = (Vector3[])(object)new Vector3[num];
		Vector3[] array2 = (Vector3[])(object)new Vector3[num];
		Vector2[] array3 = (Vector2[])(object)new Vector2[num];
		for (int i = 0; i < num; i++)
		{
			array[i] = new Vector3(portraitGeometry.vertices[i * 3], portraitGeometry.vertices[i * 3 + 1], portraitGeometry.vertices[i * 3 + 2]);
			array2[i] = new Vector3(portraitGeometry.normals[i * 3], portraitGeometry.normals[i * 3 + 1], portraitGeometry.normals[i * 3 + 2]);
			array3[i] = new Vector2(portraitGeometry.uv[i * 2], portraitGeometry.uv[i * 2 + 1]);
		}
		Mesh val = new Mesh();
		((Object)val).name = "Forge portrait: " + Path.GetFileNameWithoutExtension(path);
		if (num > 65535)
		{
			val.indexFormat = (IndexFormat)1;
		}
		val.vertices = array;
		val.uv = array3;
		val.normals = array2;
		val.triangles = portraitGeometry.triangles;
		val.RecalculateBounds();
		val.UploadMeshData(true);
		return val;
	}

	private void Awake()
	{
		//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b4: Expected O, but got Unknown
		//IL_04cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d7: Expected O, but got Unknown
		//IL_04f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_0504: Expected O, but got Unknown
		//IL_0518: Unknown result type (might be due to invalid IL or missing references)
		//IL_0522: Expected O, but got Unknown
		Instance = this;
		try
		{
			string directoryName = Path.GetDirectoryName(typeof(PhotoHeadPlugin).Assembly.Location);
			string text = Path.Combine(directoryName, "forge-photo-head.json");
			if (!File.Exists(text))
			{
				string[] files = Directory.GetFiles(Paths.PluginPath, "forge-photo-head.json", SearchOption.AllDirectories);
				if (files.Length != 1)
				{
					throw new Exception("Keep one Forge photo-head pack enabled per profile.");
				}
				text = files[0];
				directoryName = Path.GetDirectoryName(text);
			}
			PhotoSettings photoSettings = JsonConvert.DeserializeObject<PhotoSettings>(File.ReadAllText(text));
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Configuration: " + text + "; format=" + ((photoSettings == null) ? "null" : photoSettings.format.ToString()) + "; mode=" + ((photoSettings == null) ? "null" : photoSettings.mode) + "; targets=" + ((photoSettings == null || photoSettings.meshes == null) ? "null" : photoSettings.meshes.Length.ToString())));
			if (photoSettings == null || photoSettings.meshes == null || photoSettings.meshes.Length == 0 || ((photoSettings.format != 2 || !(photoSettings.mode == "mesh_texture")) && (photoSettings.format != 3 || !(photoSettings.mode == "portrait_mesh"))))
			{
				throw new Exception("Rebuild this pack with the current 3D Photo Headman editor.");
			}
			Dictionary<string, Texture2D> dictionary = new Dictionary<string, Texture2D>(StringComparer.OrdinalIgnoreCase);
			MeshSkin[] meshes = photoSettings.meshes;
			foreach (MeshSkin meshSkin in meshes)
			{
				if (meshSkin == null || string.IsNullOrWhiteSpace(meshSkin.mesh))
				{
					throw new Exception("Missing target mesh name.");
				}
				string text2 = SafePath(directoryName, meshSkin.texture);
				if (!dictionary.TryGetValue(text2, out var value))
				{
					value = new Texture2D(2, 2, (TextureFormat)4, true, false);
					Textures.Add(meshSkin.mesh, value);
					if (!ImageConversion.LoadImage(value, File.ReadAllBytes(text2)))
					{
						throw new Exception("Cannot decode " + text2);
					}
					((Object)value).name = "Forge photo: " + Path.GetFileName(text2);
					((Texture)value).wrapMode = (TextureWrapMode)(photoSettings.format == 3);
					((Texture)value).filterMode = (FilterMode)2;
					((Texture)value).anisoLevel = 4;
					value.Apply(true, true);
					dictionary.Add(text2, value);
				}
				else
				{
					Textures.Add(meshSkin.mesh, value);
				}
				if (photoSettings.format == 3)
				{
					Meshes.Add(meshSkin.mesh, LoadGeometry(SafePath(directoryName, meshSkin.geometry)));
				}
			}
			if (photoSettings.format == 3 && photoSettings.hiddenRenderers != null)
			{
				string[] hiddenRenderers = photoSettings.hiddenRenderers;
				foreach (string item in hiddenRenderers)
				{
					HiddenRenderers.Add(item);
				}
			}
			if (photoSettings.format == 3 && photoSettings.visualFits != null)
			{
				VisualFit[] visualFits = photoSettings.visualFits;
				foreach (VisualFit visualFit in visualFits)
				{
					if (visualFit == null || string.IsNullOrWhiteSpace(visualFit.mesh) || string.IsNullOrWhiteSpace(visualFit.anchorMesh) || visualFit.localPosition == null || visualFit.localPosition.Length != 3 || visualFit.localScale == null || visualFit.localScale.Length != 3 || visualFit.localRotation == null || visualFit.localRotation.Length != 4)
					{
						throw new Exception("Malformed mouth fit.");
					}
					float[] localPosition = visualFit.localPosition;
					foreach (float f in localPosition)
					{
						if (float.IsNaN(f) || float.IsInfinity(f))
						{
							throw new Exception("Non-finite mouth fit.");
						}
					}
					localPosition = visualFit.localScale;
					foreach (float num in localPosition)
					{
						if (float.IsNaN(num) || float.IsInfinity(num) || num <= 0f)
						{
							throw new Exception("Invalid mouth scale.");
						}
					}
					float num2 = 0f;
					localPosition = visualFit.localRotation;
					foreach (float num3 in localPosition)
					{
						if (float.IsNaN(num3) || float.IsInfinity(num3))
						{
							throw new Exception("Invalid mouth rotation.");
						}
						num2 += num3 * num3;
					}
					if ((double)Math.Abs(num2 - 1f) > 0.01)
					{
						throw new Exception("Mouth rotation must be normalized.");
					}
					VisualFits.Add(visualFit.mesh, visualFit);
				}
			}
			Type type = AccessTools.TypeByName("EnemyHeadController");
			MethodInfo methodInfo = ((type == null) ? null : AccessTools.DeclaredMethod(type, "Awake", (Type[])null, (Type[])null));
			if (methodInfo == null)
			{
				throw new Exception("EnemyHeadController.Awake was not found.");
			}
			harmony = new Harmony("local.repomodforge.photohead");
			ready = true;
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PhotoHeadPlugin), "Attach", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Object[] array = Object.FindObjectsOfType(type);
			for (int i = 0; i < array.Length; i++)
			{
				Attach((Component)array[i]);
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + Textures.Count + " Headman targets, " + dictionary.Count + " photo textures and " + Meshes.Count + " portrait meshes."));
		}
		catch (Exception ex)
		{
			ready = false;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			foreach (Texture2D item2 in new HashSet<Texture2D>(Textures.Values))
			{
				Object.Destroy((Object)(object)item2);
			}
			foreach (Mesh value2 in Meshes.Values)
			{
				Object.Destroy((Object)(object)value2);
			}
			Textures.Clear();
			Meshes.Clear();
			HiddenRenderers.Clear();
			VisualFits.Clear();
			((BaseUnityPlugin)this).Logger.LogError((object)("Photo head could not load; original enemy is unchanged: " + ex));
		}
	}

	private static void Attach(Component __instance)
	{
		if (!((Object)(object)Instance == (Object)null) && Instance.ready)
		{
			Transform val = __instance.transform;
			while ((Object)(object)val.parent != (Object)null && ((Object)val).name != "Enemy - Head" && ((Object)val).name != "Enemy - Head(Clone)")
			{
				val = val.parent;
			}
			if ((!(((Object)val).name != "Enemy - Head") || !(((Object)val).name != "Enemy - Head(Clone)")) && (Object)(object)((Component)val).GetComponent<PhotoHeadSkin>() == (Object)null)
			{
				((Component)val).gameObject.AddComponent<PhotoHeadSkin>();
			}
		}
	}

	internal void Report(string message)
	{
		((BaseUnityPlugin)this).Logger.LogInfo((object)message);
	}

	private void OnDestroy()
	{
		ready = false;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		PhotoHeadSkin[] array = Object.FindObjectsOfType<PhotoHeadSkin>();
		for (int i = 0; i < array.Length; i++)
		{
			array[i].Restore();
		}
		foreach (Texture2D item in new HashSet<Texture2D>(Textures.Values))
		{
			Object.Destroy((Object)(object)item);
		}
		foreach (Mesh value in Meshes.Values)
		{
			Object.Destroy((Object)(object)value);
		}
		Meshes.Clear();
		HiddenRenderers.Clear();
		VisualFits.Clear();
		Textures.Clear();
		Instance = null;
	}
}
public sealed class PhotoHeadSkin : MonoBehaviour
{
	private sealed class MouthBinding
	{
		internal MeshRenderer source;

		internal MeshRenderer fitted;

		internal bool hide;
	}

	private readonly Dictionary<Renderer, Material[]> originals = new Dictionary<Renderer, Material[]>();

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

	private readonly Dictionary<MeshFilter, Mesh> originalMeshes = new Dictionary<MeshFilter, Mesh>();

	private readonly Dictionary<Renderer, bool> originalVisibility = new Dictionary<Renderer, bool>();

	private readonly List<GameObject> fittedMouths = new List<GameObject>();

	private readonly List<MouthBinding> mouthBindings = new List<MouthBinding>();

	private static readonly string[] AlbedoSlots = new string[3] { "_AlbedoTexture", "_BaseMap", "_MainTex" };

	private void Start()
	{
		try
		{
			Apply();
		}
		catch (Exception ex)
		{
			Restore();
			if ((Object)(object)PhotoHeadPlugin.Instance != (Object)null)
			{
				PhotoHeadPlugin.Instance.Report("Photo fit failed; original enemy restored: " + ex);
			}
		}
	}

	private void Apply()
	{
		//IL_041f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0426: Expected O, but got Unknown
		//IL_0477: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a3: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0510: Unknown result type (might be due to invalid IL or missing references)
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0154: Expected O, but got Unknown
		//IL_017e: 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_01ab: Unknown result type (might be due to invalid IL or missing references)
		PhotoHeadPlugin instance = PhotoHeadPlugin.Instance;
		if ((Object)(object)instance == (Object)null)
		{
			return;
		}
		MeshFilter[] componentsInChildren = ((Component)this).GetComponentsInChildren<MeshFilter>(true);
		Dictionary<string, Transform> dictionary = new Dictionary<string, Transform>();
		MeshFilter[] array = componentsInChildren;
		foreach (MeshFilter val in array)
		{
			if ((Object)(object)val.sharedMesh != (Object)null && !dictionary.ContainsKey(((Object)val.sharedMesh).name))
			{
				dictionary.Add(((Object)val.sharedMesh).name, ((Component)val).transform);
			}
		}
		int num = 0;
		array = componentsInChildren;
		foreach (MeshFilter val2 in array)
		{
			Mesh sharedMesh = val2.sharedMesh;
			MeshRenderer component = ((Component)val2).GetComponent<MeshRenderer>();
			if ((Object)(object)sharedMesh == (Object)null || (Object)(object)component == (Object)null || !instance.Textures.TryGetValue(((Object)sharedMesh).name, out var value))
			{
				continue;
			}
			Material[] sharedMaterials = ((Renderer)component).sharedMaterials;
			Material[] array2 = (Material[])(object)new Material[sharedMaterials.Length];
			bool flag = false;
			for (int j = 0; j < sharedMaterials.Length; j++)
			{
				array2[j] = sharedMaterials[j];
				if ((Object)(object)sharedMaterials[j] == (Object)null)
				{
					continue;
				}
				string text = null;
				string[] albedoSlots = AlbedoSlots;
				foreach (string text2 in albedoSlots)
				{
					if (sharedMaterials[j].HasProperty(text2))
					{
						text = text2;
						break;
					}
				}
				if (text == null)
				{
					continue;
				}
				Material val3 = new Material(sharedMaterials[j]);
				((Object)val3).name = ((Object)sharedMaterials[j]).name + " [Forge photo]";
				val3.SetTexture(text, (Texture)(object)value);
				val3.SetTextureScale(text, Vector2.one);
				val3.SetTextureOffset(text, Vector2.zero);
				if (val3.HasProperty("_AlbedoColor"))
				{
					val3.SetColor("_AlbedoColor", Color.white);
				}
				if (instance.Meshes.ContainsKey(((Object)sharedMesh).name))
				{
					albedoSlots = new string[3] { "_NormalTexture", "_NormalMap", "_BumpMap" };
					foreach (string text3 in albedoSlots)
					{
						if (val3.HasProperty(text3))
						{
							val3.SetTexture(text3, (Texture)null);
						}
					}
					val3.DisableKeyword("_NORMALMAP");
					if (val3.HasProperty("_NormalStrength"))
					{
						val3.SetFloat("_NormalStrength", 0f);
					}
					if (val3.HasProperty("_BumpScale"))
					{
						val3.SetFloat("_BumpScale", 0f);
					}
					albedoSlots = new string[2] { "_TilingX", "_TilingY" };
					foreach (string text4 in albedoSlots)
					{
						if (val3.HasProperty(text4))
						{
							val3.SetFloat(text4, 1f);
						}
					}
					albedoSlots = new string[2] { "_OffsetX", "_OffsetY" };
					foreach (string text5 in albedoSlots)
					{
						if (val3.HasProperty(text5))
						{
							val3.SetFloat(text5, 0f);
						}
					}
				}
				array2[j] = val3;
				owned.Add(val3);
				flag = true;
			}
			if (flag)
			{
				originals[(Renderer)(object)component] = sharedMaterials;
				((Renderer)component).sharedMaterials = array2;
				if (instance.Meshes.TryGetValue(((Object)sharedMesh).name, out var value2))
				{
					originalMeshes[val2] = sharedMesh;
					val2.sharedMesh = value2;
				}
				num++;
			}
		}
		if (num == 0)
		{
			instance.Report("No compatible renderers found; original face remains visible.");
			return;
		}
		array = componentsInChildren;
		foreach (MeshFilter val4 in array)
		{
			if (!((Object)(object)val4.sharedMesh == (Object)null) && instance.VisualFits.TryGetValue(((Object)val4.sharedMesh).name, out var value3))
			{
				MeshRenderer component2 = ((Component)val4).GetComponent<MeshRenderer>();
				if ((Object)(object)component2 == (Object)null || !dictionary.TryGetValue(value3.anchorMesh, out var value4))
				{
					throw new Exception("Missing mouth anchor: " + value3.anchorMesh);
				}
				GameObject val5 = new GameObject("Forge fitted " + value3.mesh);
				fittedMouths.Add(val5);
				val5.layer = ((Component)component2).gameObject.layer;
				val5.transform.SetParent(value4, false);
				val5.transform.localPosition = new Vector3(value3.localPosition[0], value3.localPosition[1], value3.localPosition[2]);
				val5.transform.localScale = new Vector3(value3.localScale[0], value3.localScale[1], value3.localScale[2]);
				val5.transform.localRotation = new Quaternion(value3.localRotation[0], value3.localRotation[1], value3.localRotation[2], value3.localRotation[3]);
				val5.AddComponent<MeshFilter>().sharedMesh = val4.sharedMesh;
				MeshRenderer val6 = val5.AddComponent<MeshRenderer>();
				((Renderer)val6).sharedMaterials = ((Renderer)component2).sharedMaterials;
				((Renderer)val6).shadowCastingMode = ((Renderer)component2).shadowCastingMode;
				((Renderer)val6).receiveShadows = ((Renderer)component2).receiveShadows;
				originalVisibility[(Renderer)(object)component2] = ((Renderer)component2).enabled;
				((Renderer)component2).enabled = false;
				mouthBindings.Add(new MouthBinding
				{
					source = component2,
					fitted = val6,
					hide = value3.hide
				});
				((Renderer)val6).enabled = !value3.hide && MouthVisible(component2);
			}
		}
		Renderer[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val7 in componentsInChildren2)
		{
			bool flag2 = instance.HiddenRenderers.Contains(((Object)val7).name);
			if (instance.Meshes.Count > 0 && ((Object)val7).name.StartsWith("Mouth Inside", StringComparison.Ordinal))
			{
				flag2 = true;
			}
			if (instance.Meshes.Count > 0)
			{
				Material[] sharedMaterials2 = val7.sharedMaterials;
				foreach (Material val8 in sharedMaterials2)
				{
					if ((Object)(object)val8 != (Object)null && ((Object)val8).name.StartsWith("Headman Hair", StringComparison.OrdinalIgnoreCase))
					{
						flag2 = true;
					}
				}
			}
			if (flag2)
			{
				originalVisibility[val7] = val7.enabled;
				val7.enabled = false;
			}
		}
		instance.Report("Applied 3D photo head to " + num + " Headman renderers, including animation variants.");
	}

	private static bool MouthVisible(MeshRenderer source)
	{
		if ((Object)(object)source != (Object)null)
		{
			return ((Component)source).gameObject.activeInHierarchy;
		}
		return false;
	}

	private void LateUpdate()
	{
		foreach (MouthBinding mouthBinding in mouthBindings)
		{
			if ((Object)(object)mouthBinding.fitted != (Object)null)
			{
				((Renderer)mouthBinding.fitted).enabled = !mouthBinding.hide && MouthVisible(mouthBinding.source);
			}
			if ((Object)(object)mouthBinding.source != (Object)null)
			{
				((Renderer)mouthBinding.source).enabled = false;
			}
		}
	}

	public void Restore()
	{
		foreach (KeyValuePair<Renderer, Material[]> original in originals)
		{
			if ((Object)(object)original.Key != (Object)null)
			{
				original.Key.sharedMaterials = original.Value;
			}
		}
		originals.Clear();
		foreach (KeyValuePair<MeshFilter, Mesh> originalMesh in originalMeshes)
		{
			if ((Object)(object)originalMesh.Key != (Object)null)
			{
				originalMesh.Key.sharedMesh = originalMesh.Value;
			}
		}
		foreach (KeyValuePair<Renderer, bool> item in originalVisibility)
		{
			if ((Object)(object)item.Key != (Object)null)
			{
				item.Key.enabled = item.Value;
			}
		}
		originalMeshes.Clear();
		originalVisibility.Clear();
		foreach (GameObject fittedMouth in fittedMouths)
		{
			if ((Object)(object)fittedMouth != (Object)null)
			{
				fittedMouth.SetActive(false);
				Object.Destroy((Object)(object)fittedMouth);
			}
		}
		fittedMouths.Clear();
		mouthBindings.Clear();
		foreach (Material item2 in owned)
		{
			if ((Object)(object)item2 != (Object)null)
			{
				Object.Destroy((Object)(object)item2);
			}
		}
		owned.Clear();
	}

	private void OnDestroy()
	{
		Restore();
	}
}

BepInEx/plugins/Preben_Mod/PrebenDuck.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using HarmonyLib;
using UnityEngine;

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

[BepInPlugin("local.repomodforge.prebenduck", "Preben Blue Duck", "1.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("REPO.exe")]
public sealed class PrebenDuckPlugin : BaseUnityPlugin
{
	internal static PrebenDuckPlugin Instance;

	internal AudioClip clip;

	internal float volume = 0.8f;

	private Harmony harmony;

	private readonly Dictionary<Material, Material> skins = new Dictionary<Material, Material>();

	private readonly Dictionary<Texture, Texture2D> textures = new Dictionary<Texture, Texture2D>();

	private void Awake()
	{
		//IL_0036: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Expected O, but got Unknown
		//IL_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_0095: Expected O, but got Unknown
		//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Expected O, but got Unknown
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Expected O, but got Unknown
		Instance = this;
		try
		{
			clip = LoadWav(Path.Combine(Path.GetDirectoryName(((object)this).GetType().Assembly.Location), "duck/pip.wav"));
			harmony = new Harmony("local.repomodforge.prebenduck");
			string[] array = new string[2] { "Quack", "NoticeSound" };
			foreach (string text in array)
			{
				harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(EnemyDuckAnim), text, (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(PrebenDuckPlugin), "ReplaceQuack", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(EnemyDuckAnim), "FootstepSound", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(PrebenDuckPlugin), "WalkingSound", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(EnemyDuckAnim), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(PrebenDuckPlugin), "DuckAwake", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Blue Duck ready: supplied pip for quack, notice and walking; " + clip.length.ToString("F2") + "s, mono, linear 1m-18m proximity; full-clip playback without stacking."));
		}
		catch (Exception ex)
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			((BaseUnityPlugin)this).Logger.LogError((object)("Blue Duck could not initialize: " + ex));
		}
	}

	private static IEnumerable<CodeInstruction> ReplaceQuack(IEnumerable<CodeInstruction> instructions)
	{
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Expected O, but got Unknown
		//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
		//IL_0100: Expected O, but got Unknown
		MethodInfo methodInfo = AccessTools.Method(typeof(Sound), "Play", new Type[5]
		{
			typeof(Vector3),
			typeof(float),
			typeof(float),
			typeof(float),
			typeof(float)
		}, (Type[])null);
		MethodInfo methodInfo2 = AccessTools.Method(typeof(PrebenDuckPlugin), "PlayQuack", (Type[])null, (Type[])null);
		int num = 0;
		List<CodeInstruction> list = new List<CodeInstruction>();
		foreach (CodeInstruction instruction in instructions)
		{
			if (CodeInstructionExtensions.Calls(instruction, methodInfo))
			{
				CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
				val.labels.AddRange(instruction.labels);
				instruction.labels.Clear();
				val.blocks.AddRange(instruction.blocks);
				instruction.blocks.Clear();
				list.Add(val);
				list.Add(new CodeInstruction(OpCodes.Call, (object)methodInfo2));
				num++;
			}
			else
			{
				list.Add(instruction);
			}
		}
		if (num != 1)
		{
			throw new Exception("Expected one native duck quack call; found " + num);
		}
		return list;
	}

	private static AudioSource PlayQuack(Sound original, Vector3 position, float a, float b, float c, float d, EnemyDuckAnim duck)
	{
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)Instance == (Object)null || (Object)(object)Instance.clip == (Object)null || (Object)(object)duck == (Object)null)
		{
			return original.Play(position, a, b, c, d);
		}
		return PlayPip(duck);
	}

	private static void WalkingSound(EnemyDuckAnim __instance)
	{
		if ((Object)(object)Instance != (Object)null && (Object)(object)Instance.clip != (Object)null && (Object)(object)__instance != (Object)null)
		{
			PlayPip(__instance);
		}
	}

	private static AudioSource PlayPip(EnemyDuckAnim duck)
	{
		try
		{
			PrebenDuckVoice prebenDuckVoice = ((Component)duck).GetComponent<PrebenDuckVoice>();
			if ((Object)(object)prebenDuckVoice == (Object)null)
			{
				prebenDuckVoice = ((Component)duck).gameObject.AddComponent<PrebenDuckVoice>();
			}
			return prebenDuckVoice.Play(Instance.clip, Instance.volume);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Duck pip skipped: " + ex.Message));
			return null;
		}
	}

	private static void DuckAwake(EnemyDuckAnim __instance)
	{
		if ((Object)(object)Instance == (Object)null)
		{
			return;
		}
		try
		{
			Instance.ApplySkin(__instance);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Duck skin skipped: " + ex.Message));
		}
	}

	internal void ApplySkin(EnemyDuckAnim duck)
	{
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0119: Expected O, but got Unknown
		Transform val = ((Component)duck).transform;
		while ((Object)(object)val != (Object)null && ((Object)val).name != "Enemy - Duck" && ((Object)val).name != "Enemy - Duck(Clone)")
		{
			val = val.parent;
		}
		if ((Object)(object)val == (Object)null)
		{
			return;
		}
		Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val2 in componentsInChildren)
		{
			Material[] sharedMaterials = val2.sharedMaterials;
			bool flag = false;
			for (int j = 0; j < sharedMaterials.Length; j++)
			{
				Material val3 = sharedMaterials[j];
				if ((Object)(object)val3 == (Object)null || !val3.HasProperty("_AlbedoTexture"))
				{
					continue;
				}
				Texture texture = val3.GetTexture("_AlbedoTexture");
				if ((Object)(object)texture == (Object)null || (((Object)texture).name != "duckckckck_Enemy_Duck_BaseColor" && ((Object)texture).name != "Duck monster_BaseColor"))
				{
					continue;
				}
				if (!skins.TryGetValue(val3, out var value))
				{
					if (!textures.TryGetValue(texture, out var value2))
					{
						value2 = BlueTexture(texture);
						textures.Add(texture, value2);
					}
					value = new Material(val3);
					((Object)value).name = ((Object)val3).name + " [Preben blue duck]";
					value.SetTexture("_AlbedoTexture", (Texture)(object)value2);
					skins.Add(val3, value);
				}
				sharedMaterials[j] = value;
				flag = true;
			}
			if (flag)
			{
				val2.sharedMaterials = sharedMaterials;
			}
		}
	}

	private static Texture2D BlueTexture(Texture source)
	{
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected O, but got Unknown
		//IL_0058: 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_00b9: 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)
		RenderTexture active = RenderTexture.active;
		RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2);
		Texture2D val = null;
		try
		{
			Graphics.Blit(source, temporary);
			RenderTexture.active = temporary;
			val = new Texture2D(source.width, source.height, (TextureFormat)4, true, false);
			val.ReadPixels(new Rect(0f, 0f, (float)source.width, (float)source.height), 0, 0);
			Color[] pixels = val.GetPixels();
			for (int i = 0; i < pixels.Length; i++)
			{
				pixels[i] = BluePixel(pixels[i]);
			}
			val.SetPixels(pixels);
			val.Apply(true, false);
			((Object)val).name = ((Object)source).name + " [Preben blue]";
			((Texture)val).wrapMode = source.wrapMode;
			((Texture)val).filterMode = source.filterMode;
			((Texture)val).anisoLevel = source.anisoLevel;
			return val;
		}
		catch
		{
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)val);
			}
			throw;
		}
		finally
		{
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
		}
	}

	internal static Color BluePixel(Color pixel)
	{
		//IL_0000: 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_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_0046: Unknown result type (might be due to invalid IL or missing references)
		float num = default(float);
		float num2 = default(float);
		float num3 = default(float);
		Color.RGBToHSV(pixel, ref num, ref num2, ref num3);
		if (num >= 7f / 72f && num <= 0.2f && num2 >= 0.25f && num3 > 0.03f)
		{
			Color result = Color.HSVToRGB(0.6f, num2, num3);
			result.a = pixel.a;
			return result;
		}
		return pixel;
	}

	private static AudioClip LoadWav(string path)
	{
		byte[] array = File.ReadAllBytes(path);
		if (array.Length < 44 || Encoding.ASCII.GetString(array, 0, 4) != "RIFF" || Encoding.ASCII.GetString(array, 8, 4) != "WAVE")
		{
			throw new Exception("Invalid duck WAV.");
		}
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5;
		for (int i = 12; i + 8 <= array.Length; i += 8 + num5 + (num5 & 1))
		{
			string text = Encoding.ASCII.GetString(array, i, 4);
			num5 = BitConverter.ToInt32(array, i + 4);
			if (num5 < 0 || (long)i + 8L + num5 > array.Length)
			{
				throw new Exception("Invalid WAV chunk.");
			}
			if (text == "fmt " && num5 >= 16)
			{
				num = BitConverter.ToInt16(array, i + 8);
				num2 = BitConverter.ToInt16(array, i + 10);
				num3 = BitConverter.ToInt32(array, i + 12);
				num4 = BitConverter.ToInt16(array, i + 22);
			}
			if (text == "data")
			{
				if (num != 1 || num2 != 1 || num4 != 16 || num3 != 44100 || num5 <= 0 || num5 % 2 != 0)
				{
					throw new Exception("Duck WAV must be 44.1kHz 16-bit mono PCM.");
				}
				float[] array2 = new float[num5 / 2];
				for (int j = 0; j < array2.Length; j++)
				{
					array2[j] = (float)BitConverter.ToInt16(array, i + 8 + j * 2) / 32768f;
				}
				AudioClip obj = AudioClip.Create("Preben Duck pip", array2.Length, 1, num3, false);
				obj.SetData(array2, 0);
				return obj;
			}
		}
		throw new Exception("Duck WAV has no samples.");
	}

	private void OnDestroy()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		foreach (Material value in skins.Values)
		{
			if ((Object)(object)value != (Object)null)
			{
				Object.Destroy((Object)(object)value);
			}
		}
		foreach (Texture2D value2 in textures.Values)
		{
			if ((Object)(object)value2 != (Object)null)
			{
				Object.Destroy((Object)(object)value2);
			}
		}
		skins.Clear();
		textures.Clear();
		if ((Object)(object)clip != (Object)null)
		{
			Object.Destroy((Object)(object)clip);
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}
}
public sealed class PrebenDuckVoice : MonoBehaviour
{
	private AudioSource source;

	internal AudioSource Play(AudioClip clip, float volume)
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		if ((Object)(object)source == (Object)null)
		{
			GameObject val = new GameObject("Preben Duck pip voice");
			val.transform.SetParent(((Component)this).transform, false);
			source = val.AddComponent<AudioSource>();
		}
		if (source.isPlaying && (Object)(object)source.clip == (Object)(object)clip)
		{
			return source;
		}
		source.Stop();
		source.clip = clip;
		source.volume = volume;
		source.playOnAwake = false;
		source.loop = false;
		source.spatialBlend = 1f;
		source.dopplerLevel = 0f;
		source.rolloffMode = (AudioRolloffMode)1;
		source.minDistance = 1f;
		source.maxDistance = 18f;
		if ((Object)(object)AudioManager.instance != (Object)null)
		{
			source.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		source.Play();
		return source;
	}

	private void OnDisable()
	{
		if ((Object)(object)source != (Object)null)
		{
			source.Stop();
		}
	}
}

BepInEx/plugins/Preben_Mod/PrebenRobe.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using HarmonyLib;
using UnityEngine;

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

[BepInPlugin("local.repomodforge.prebenrobe", "Preben Robe", "1.1.0")]
[BepInProcess("REPO.exe")]
public sealed class PrebenRobePlugin : BaseUnityPlugin
{
	private sealed class KillEvent
	{
		internal Vector3 position;
	}

	internal static readonly Color FaceBrown = new Color(0.7f, 0.42f, 0.2f, 1f);

	internal static PrebenRobePlugin Instance;

	private Harmony harmony;

	private AudioClip killClip;

	private float killVolume = 0.8f;

	private readonly List<GameObject> voices = new List<GameObject>();

	private void Awake()
	{
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		//IL_008e: Expected O, but got Unknown
		//IL_00a5: 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_00c7: Expected O, but got Unknown
		//IL_00c7: Expected O, but got Unknown
		Instance = this;
		((MonoBehaviour)this).StartCoroutine(WatchForRobes());
		((BaseUnityPlugin)this).Logger.LogInfo((object)"Brown Robe face skin ready.");
		try
		{
			string directoryName = Path.GetDirectoryName(typeof(PrebenRobePlugin).Assembly.Location);
			killClip = LoadWav(Path.Combine(directoryName, "robe/kill.wav"));
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(PlayerAvatar), "PlayerDeathRPC", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				throw new Exception("PlayerDeathRPC was not found.");
			}
			harmony = new Harmony("local.repomodforge.prebenrobe");
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(PrebenRobePlugin), "BeforeDeath", (Type[])null), new HarmonyMethod(typeof(PrebenRobePlugin), "AfterDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Robe kill audio ready: " + killClip.length.ToString("F2") + "s, mono, 1m-18m proximity."));
		}
		catch (Exception ex)
		{
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			((BaseUnityPlugin)this).Logger.LogError((object)("Robe kill audio could not load: " + ex));
		}
	}

	private static void BeforeDeath(PlayerAvatar __instance, int enemyIndex, bool ___deadSet, ref KillEvent __state)
	{
		//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)
		__state = null;
		if ((Object)(object)Instance == (Object)null || (Object)(object)Instance.killClip == (Object)null || ___deadSet || enemyIndex < 0)
		{
			return;
		}
		try
		{
			Enemy val = SemiFunc.EnemyGetFromIndex(enemyIndex);
			if (!((Object)(object)val == (Object)null))
			{
				EnemyRobe val2 = ((Component)val).GetComponentInChildren<EnemyRobe>(true);
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Component)val).GetComponentInParent<EnemyRobe>();
				}
				if ((Object)(object)val2 != (Object)null)
				{
					__state = new KillEvent
					{
						position = ((Component)val2).transform.position
					};
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Robe killer lookup skipped: " + ex.Message));
		}
	}

	private static void AfterDeath(bool ___deadSet, KillEvent __state)
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		if (__state == null || !___deadSet || (Object)(object)Instance == (Object)null)
		{
			return;
		}
		try
		{
			Instance.PlayKill(__state.position);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Robe kill audio skipped: " + ex.Message));
		}
	}

	private void PlayKill(Vector3 position)
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Expected O, but got Unknown
		//IL_003c: Unknown result type (might be due to invalid IL or missing references)
		voices.RemoveAll((GameObject voice) => (Object)(object)voice == (Object)null);
		GameObject val = new GameObject("Preben Robe kill audio");
		val.transform.position = position;
		AudioSource val2 = val.AddComponent<AudioSource>();
		val2.clip = killClip;
		val2.playOnAwake = false;
		val2.loop = false;
		val2.spatialBlend = 1f;
		val2.volume = killVolume;
		val2.dopplerLevel = 0f;
		val2.rolloffMode = (AudioRolloffMode)1;
		val2.minDistance = 1f;
		val2.maxDistance = 18f;
		if ((Object)(object)AudioManager.instance != (Object)null)
		{
			val2.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		voices.Add(val);
		val2.Play();
		Object.Destroy((Object)(object)val, killClip.length + 0.25f);
	}

	private static AudioClip LoadWav(string path)
	{
		byte[] array = File.ReadAllBytes(path);
		if (array.Length < 44 || Encoding.ASCII.GetString(array, 0, 4) != "RIFF" || Encoding.ASCII.GetString(array, 8, 4) != "WAVE")
		{
			throw new Exception("Invalid Robe kill WAV.");
		}
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5;
		for (int i = 12; i + 8 <= array.Length; i += 8 + num5 + (num5 & 1))
		{
			string text = Encoding.ASCII.GetString(array, i, 4);
			num5 = BitConverter.ToInt32(array, i + 4);
			if (num5 < 0 || (long)i + 8L + num5 > array.Length)
			{
				throw new Exception("Invalid WAV chunk length.");
			}
			if (text == "fmt " && num5 >= 16)
			{
				num4 = BitConverter.ToInt16(array, i + 8);
				num = BitConverter.ToInt16(array, i + 10);
				num3 = BitConverter.ToInt32(array, i + 12);
				num2 = BitConverter.ToInt16(array, i + 22);
			}
			if (text == "data")
			{
				if (num4 != 1 || num != 1 || num2 != 16 || num3 != 44100 || num5 <= 0 || num5 % 2 != 0)
				{
					throw new Exception("Kill WAV must be 44.1kHz 16-bit mono PCM.");
				}
				float[] array2 = new float[num5 / 2];
				for (int j = 0; j < array2.Length; j++)
				{
					array2[j] = (float)BitConverter.ToInt16(array, i + 8 + j * 2) / 32768f;
				}
				AudioClip obj = AudioClip.Create("Preben Robe player kill", array2.Length, 1, num3, false);
				obj.SetData(array2, 0);
				return obj;
			}
		}
		throw new Exception("Robe kill WAV contains no audio.");
	}

	private void OnDestroy()
	{
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		foreach (GameObject voice in voices)
		{
			if ((Object)(object)voice != (Object)null)
			{
				Object.Destroy((Object)(object)voice);
			}
		}
		voices.Clear();
		if ((Object)(object)killClip != (Object)null)
		{
			Object.Destroy((Object)(object)killClip);
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}

	private IEnumerator WatchForRobes()
	{
		WaitForSeconds wait = new WaitForSeconds(0.5f);
		while (true)
		{
			try
			{
				MeshFilter[] array = Object.FindObjectsOfType<MeshFilter>(true);
				foreach (MeshFilter val in array)
				{
					if (!((Object)(object)val == (Object)null) && !((Object)(object)val.sharedMesh == (Object)null) && string.Equals(((Object)val.sharedMesh).name, "head_top", StringComparison.OrdinalIgnoreCase) && BelongsToRobe(((Component)val).transform) && !((Object)(object)((Component)val).GetComponent<PrebenRobeFace>() != (Object)null))
					{
						((Component)val).gameObject.AddComponent<PrebenRobeFace>();
					}
				}
			}
			catch (Exception ex)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("Robe face scan skipped: " + ex.Message));
			}
			yield return wait;
		}
	}

	private static bool BelongsToRobe(Transform node)
	{
		while ((Object)(object)node != (Object)null)
		{
			if (((Object)node).name == "Enemy - Robe" || ((Object)node).name == "Enemy - Robe(Clone)")
			{
				return true;
			}
			node = node.parent;
		}
		return false;
	}
}
public sealed class PrebenRobeFace : MonoBehaviour
{
	private MeshRenderer renderer;

	private Material[] original;

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

	private void Start()
	{
		//IL_006e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0074: Expected O, but got Unknown
		//IL_009d: 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_00db: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			renderer = ((Component)this).GetComponent<MeshRenderer>();
			if ((Object)(object)renderer == (Object)null || ((Renderer)renderer).sharedMaterials == null)
			{
				return;
			}
			original = ((Renderer)renderer).sharedMaterials;
			Material[] array = (Material[])(object)new Material[original.Length];
			for (int i = 0; i < original.Length; i++)
			{
				Material val = original[i];
				if ((Object)(object)val == (Object)null)
				{
					array[i] = null;
					continue;
				}
				Material val2 = new Material(val);
				((Object)val2).name = ((Object)val).name + " [Preben brown face]";
				if (val2.HasProperty("_AlbedoColor"))
				{
					val2.SetColor("_AlbedoColor", PrebenRobePlugin.FaceBrown);
				}
				else if (val2.HasProperty("_BaseColor"))
				{
					val2.SetColor("_BaseColor", PrebenRobePlugin.FaceBrown);
				}
				else if (val2.HasProperty("_Color"))
				{
					val2.SetColor("_Color", PrebenRobePlugin.FaceBrown);
				}
				array[i] = val2;
				owned.Add(val2);
			}
			((Renderer)renderer).sharedMaterials = array;
		}
		catch (Exception ex)
		{
			Restore();
			Debug.LogWarning((object)("Preben brown Robe face was not applied: " + ex.Message));
		}
	}

	private void Restore()
	{
		if ((Object)(object)renderer != (Object)null && original != null)
		{
			((Renderer)renderer).sharedMaterials = original;
		}
		original = null;
		foreach (Material item in owned)
		{
			if ((Object)(object)item != (Object)null)
			{
				Object.Destroy((Object)(object)item);
			}
		}
		owned.Clear();
	}

	private void OnDestroy()
	{
		Restore();
	}
}

BepInEx/plugins/Preben_Mod/PrebenSlotsClassic.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using Newtonsoft.Json;
using REPOLib.Modules;
using UnityEngine;

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

public class SlotsMaterial
{
	public string name;

	public string texture;

	public float[] color;

	public float metallic;

	public float smoothness;
}
public class SlotsMesh
{
	public string name;

	public int material;

	public float[] vertices;

	public float[] normals;

	public float[] uv;

	public int[] triangles;
}
public class SlotsData
{
	public int format;

	public int value;

	public int canCount;

	public string name;

	public string displayName;

	public string sound;

	public float mass;

	public float[] size;

	public SlotsMaterial[] materials;

	public SlotsMesh[] meshes;
}
public sealed class SlotsPickupAudio : MonoBehaviour
{
	private PhysGrabObject grab;

	private AudioSource source;

	private bool wasHeld;

	private int playCount;

	private void Awake()
	{
		grab = ((Component)this).GetComponent<PhysGrabObject>();
		source = ((Component)this).GetComponent<AudioSource>();
	}

	private void Update()
	{
		if (!((Object)(object)source == (Object)null) && !((Object)(object)grab == (Object)null))
		{
			if ((Object)(object)source.outputAudioMixerGroup == (Object)null && (Object)(object)AudioManager.instance != (Object)null)
			{
				source.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
			}
			HandleHeld(grab.playerGrabbing != null && grab.playerGrabbing.Count > 0);
		}
	}

	private void HandleHeld(bool held)
	{
		if (held && !wasHeld)
		{
			source.Stop();
			source.Play();
			playCount++;
		}
		wasHeld = held;
	}
}
[BepInPlugin("local.repomodforge.slotsclassic", "Preben Slots Classic", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("REPO.exe")]
public sealed class PrebenSlotsClassicPlugin : BaseUnityPlugin
{
	private static readonly HashSet<string> Generic = new HashSet<string> { "ValuableObject", "ValuableDiscover", "ValuableDiscoverGraphic", "MapValuable", "ValuablePropSwitch" };

	private string folder;

	private bool done;

	private GameObject prefabHolder;

	private void Awake()
	{
		folder = Path.Combine(Path.GetDirectoryName(typeof(PrebenSlotsClassicPlugin).Assembly.Location), "slots-classic");
	}

	private void Update()
	{
		if (done || ValuablePresets.AllValuablePresets.Count == 0)
		{
			return;
		}
		done = true;
		try
		{
			Register();
		}
		catch (Exception ex)
		{
			if ((Object)(object)prefabHolder != (Object)null)
			{
				Object.Destroy((Object)(object)prefabHolder);
			}
			((BaseUnityPlugin)this).Logger.LogError((object)("Slots Classic not registered: " + ex));
		}
	}

	private GameObject FindTemplate()
	{
		foreach (LevelValuables value in ValuablePresets.AllValuablePresets.Values)
		{
			List<PrefabRef>[] array = new List<PrefabRef>[3] { value.small, value.medium, value.tiny };
			for (int i = 0; i < array.Length; i++)
			{
				foreach (PrefabRef item in array[i])
				{
					GameObject val = ((PrefabRef<GameObject>)(object)item)?.Prefab;
					if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponent<ValuableObject>() == (Object)null || (Object)(object)val.GetComponent<PhysGrabObject>() == (Object)null || (Object)(object)val.GetComponent<Rigidbody>() == (Object)null || (Object)(object)val.GetComponent<InstrumentPlayer>() != (Object)null || (Object)(object)val.GetComponent<SlotsPickupAudio>() != (Object)null)
					{
						continue;
					}
					bool flag = true;
					MonoBehaviour[] componentsInChildren = val.GetComponentsInChildren<MonoBehaviour>(true);
					foreach (MonoBehaviour val2 in componentsInChildren)
					{
						string text = (((Object)(object)val2 == (Object)null) ? "" : ((object)val2).GetType().Name);
						if (text.Contains("Valuable") && !Generic.Contains(text))
						{
							flag = false;
							break;
						}
					}
					if (!flag)
					{
						continue;
					}
					List<Collider> list = new List<Collider>();
					Collider[] componentsInChildren2 = val.GetComponentsInChildren<Collider>(true);
					foreach (Collider val3 in componentsInChildren2)
					{
						if (!val3.isTrigger && val3.enabled)
						{
							list.Add(val3);
						}
					}
					if (list.Count == 1 && list[0] is BoxCollider && !((Object)(object)val.GetComponent<ValuableObject>().physAttributePreset == (Object)null))
					{
						return val;
					}
				}
			}
		}
		throw new Exception("No plain vanilla box valuable is available as a physics template.");
	}

	private void Register()
	{
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Expected O, but got Unknown
		//IL_00e0: 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_0100: Unknown result type (might be due to invalid IL or missing references)
		//IL_01da: 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_01fc: 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_021a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0247: Unknown result type (might be due to invalid IL or missing references)
		//IL_024c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0259: Unknown result type (might be due to invalid IL or missing references)
		//IL_025e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0286: Unknown result type (might be due to invalid IL or missing references)
		//IL_028b: Unknown result type (might be due to invalid IL or missing references)
		//IL_029a: Expected O, but got Unknown
		//IL_02af: 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_02c6: Unknown result type (might be due to invalid IL or missing references)
		//IL_02cf: Expected O, but got Unknown
		//IL_0500: Unknown result type (might be due to invalid IL or missing references)
		//IL_0505: Unknown result type (might be due to invalid IL or missing references)
		//IL_0517: Unknown result type (might be due to invalid IL or missing references)
		//IL_06b4: Unknown result type (might be due to invalid IL or missing references)
		//IL_06b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_035e: Unknown result type (might be due to invalid IL or missing references)
		//IL_036c: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e6: Unknown result type (might be due to invalid IL or missing references)
		SlotsData slotsData = JsonConvert.DeserializeObject<SlotsData>(File.ReadAllText(Path.Combine(folder, "valuable.json")));
		if (slotsData == null || slotsData.format != 1 || slotsData.name != "Valuable Slots Classic" || slotsData.value != 10000 || slotsData.canCount != 24 || slotsData.mass <= 0f || slotsData.materials == null || slotsData.materials.Length != 6 || slotsData.meshes == null || slotsData.meshes.Length != 6)
		{
			throw new Exception("Malformed Slots Classic configuration.");
		}
		GameObject val = FindTemplate();
		prefabHolder = new GameObject("Preben Slots Classic Prefab");
		prefabHolder.SetActive(false);
		Object.DontDestroyOnLoad((Object)(object)prefabHolder);
		GameObject val2 = Object.Instantiate<GameObject>(val, prefabHolder.transform);
		((Object)val2).name = slotsData.name;
		val2.transform.localPosition = Vector3.zero;
		val2.transform.localRotation = Quaternion.identity;
		val2.transform.localScale = Vector3.one;
		Material val3 = null;
		Renderer[] componentsInChildren = val2.GetComponentsInChildren<Renderer>(true);
		foreach (Renderer val4 in componentsInChildren)
		{
			if ((Object)(object)val3 == (Object)null && val4 is MeshRenderer && val4.enabled && (Object)(object)val4.sharedMaterial != (Object)null)
			{
				val3 = val4.sharedMaterial;
			}
			val4.enabled = false;
		}
		if ((Object)(object)val3 == (Object)null)
		{
			throw new Exception("Physics template has no usable material.");
		}
		BoxCollider val5 = null;
		Collider[] componentsInChildren2 = val2.GetComponentsInChildren<Collider>(true);
		foreach (Collider val6 in componentsInChildren2)
		{
			if (!val6.isTrigger && val6.enabled)
			{
				val5 = (BoxCollider)(object)((val6 is BoxCollider) ? val6 : null);
			}
		}
		if ((Object)(object)val5 == (Object)null)
		{
			throw new Exception("The expected solid collider disappeared.");
		}
		((Component)val5).transform.localPosition = Vector3.zero;
		((Component)val5).transform.localRotation = Quaternion.identity;
		((Component)val5).transform.localScale = Vector3.one;
		val5.center = Vector3.zero;
		val5.size = V(slotsData.size);
		PhysGrabObject component = val2.GetComponent<PhysGrabObject>();
		component.colliders = new List<Transform> { ((Component)val5).transform };
		component.midPointOffset = Vector3.zero;
		component.boundingBox = V(slotsData.size);
		Material[] array = (Material[])(object)new Material[slotsData.materials.Length];
		Color val9 = default(Color);
		for (int j = 0; j < array.Length; j++)
		{
			SlotsMaterial slotsMaterial = slotsData.materials[j];
			Material val7 = new Material(val3)
			{
				name = slotsMaterial.name
			};
			Texture2D val8 = null;
			if (!string.IsNullOrWhiteSpace(slotsMaterial.texture))
			{
				val8 = new Texture2D(2, 2, (TextureFormat)4, true)
				{
					name = "Slots original reference",
					filterMode = (FilterMode)1,
					wrapMode = (TextureWrapMode)1
				};
				if (!ImageConversion.LoadImage(val8, File.ReadAllBytes(SafePath(slotsMaterial.texture)), true))
				{
					throw new Exception("Photo texture could not be decoded.");
				}
			}
			string[] texturePropertyNames = val7.GetTexturePropertyNames();
			foreach (string text in texturePropertyNames)
			{
				string text2 = text.ToLowerInvariant();
				val7.SetTexture(text, (Texture)(object)((text2.Contains("albedo") || text2.Contains("main") || text2.Contains("base") || text2.Contains("diffuse")) ? val8 : null));
				val7.SetTextureScale(text, Vector2.one);
				val7.SetTextureOffset(text, Vector2.zero);
			}
			((Color)(ref val9))..ctor(slotsMaterial.color[0], slotsMaterial.color[1], slotsMaterial.color[2], 1f);
			texturePropertyNames = new string[3] { "_Color", "_BaseColor", "_AlbedoColor" };
			foreach (string text3 in texturePropertyNames)
			{
				if (val7.HasProperty(text3))
				{
					val7.SetColor(text3, val9);
				}
			}
			texturePropertyNames = new string[2] { "_Metallic", "_Metalness" };
			foreach (string text4 in texturePropertyNames)
			{
				if (val7.HasProperty(text4))
				{
					val7.SetFloat(text4, slotsMaterial.metallic);
				}
			}
			texturePropertyNames = new string[2] { "_Glossiness", "_Smoothness" };
			foreach (string text5 in texturePropertyNames)
			{
				if (val7.HasProperty(text5))
				{
					val7.SetFloat(text5, slotsMaterial.smoothness);
				}
			}
			val7.DisableKeyword("_EMISSION");
			array[j] = val7;
		}
		SlotsMesh[] meshes = slotsData.meshes;
		foreach (SlotsMesh slotsMesh in meshes)
		{
			if (slotsMesh.material < 0 || slotsMesh.material >= array.Length)
			{
				throw new Exception("Bad material index.");
			}
			GameObject val10 = new GameObject("Slots " + slotsMesh.name);
			val10.transform.SetParent(val2.transform, false);
			val10.AddComponent<MeshFilter>().sharedMesh = BuildMesh(slotsMesh);
			((Renderer)val10.AddComponent<MeshRenderer>()).sharedMaterial = array[slotsMesh.material];
		}
		ValuableObject component2 = val2.GetComponent<ValuableObject>();
		Value val11 = ScriptableObject.CreateInstance<Value>();
		((Object)val11).name = "Slots Classic $10000";
		val11.valueMin = slotsData.value;
		val11.valueMax = slotsData.value;
		component2.valuePreset = val11;
		PhysAttribute val12 = Object.Instantiate<PhysAttribute>(component2.physAttributePreset);
		((Object)val12).name = "Slots Classic case mass";
		val12.mass = slotsData.mass;
		component2.physAttributePreset = val12;
		val2.GetComponent<Rigidbody>().mass = slotsData.mass;
		component.massOriginal = slotsData.mass;
		AudioSource val13 = val2.AddComponent<AudioSource>();
		val13.clip = LoadWav(SafePath(slotsData.sound));
		val13.loop = false;
		val13.playOnAwake = false;
		val13.spatialBlend = 1f;
		val13.volume = 0.8f;
		val13.rolloffMode = (AudioRolloffMode)1;
		val13.minDistance = 1f;
		val13.maxDistance = 18f;
		val13.dopplerLevel = 0f;
		if ((Object)(object)AudioManager.instance != (Object)null)
		{
			val13.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		val2.AddComponent<SlotsPickupAudio>();
		if (Valuables.RegisterValuable(component2, new List<string> { "Valuables - Generic" }) == null)
		{
			throw new Exception("REPOLib rejected the network prefab.");
		}
		((BaseUnityPlugin)this).Logger.LogInfo((object)(slotsData.name + " registered: 24 cans, $10000, " + ((object)val5.size/*cast due to .constrained prefix*/).ToString() + ", " + slotsData.mass + " kg; pickup audio " + val13.clip.length.ToString("F2") + "s, 18m proximity. Template=" + ((Object)val).name + ", shader=" + ((Object)val3.shader).name));
	}

	private static Vector3 V(float[] a)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		if (a == null || a.Length != 3)
		{
			throw new Exception("Expected a three-number vector.");
		}
		return new Vector3(a[0], a[1], a[2]);
	}

	private string SafePath(string relative)
	{
		if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative))
		{
			throw new Exception("Asset path must be relative.");
		}
		string fullPath = Path.GetFullPath(Path.Combine(folder, relative));
		if (!fullPath.StartsWith(Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
		{
			throw new Exception("Asset path escaped the valuable folder.");
		}
		return fullPath;
	}

	private static Mesh BuildMesh(SlotsMesh d)
	{
		//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ee: 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_0113: 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_0162: Unknown result type (might be due to invalid IL or missing references)
		//IL_0167: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0181: Unknown result type (might be due to invalid IL or missing references)
		//IL_0188: 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_019a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Expected O, but got Unknown
		int num = ((d.vertices != null) ? (d.vertices.Length / 3) : 0);
		if (num == 0 || num > 65000 || d.vertices.Length != num * 3 || d.normals == null || d.normals.Length != num * 3 || d.uv == null || d.uv.Length != num * 2 || d.triangles == null || d.triangles.Length % 3 != 0)
		{
			throw new Exception("Malformed Slots mesh.");
		}
		Vector3[] array = (Vector3[])(object)new Vector3[num];
		Vector3[] array2 = (Vector3[])(object)new Vector3[num];
		Vector2[] array3 = (Vector2[])(object)new Vector2[num];
		for (int i = 0; i < num; i++)
		{
			array[i] = new Vector3(d.vertices[i * 3], d.vertices[i * 3 + 1], d.vertices[i * 3 + 2]);
			array2[i] = new Vector3(d.normals[i * 3], d.normals[i * 3 + 1], d.normals[i * 3 + 2]);
			array3[i] = new Vector2(d.uv[i * 2], d.uv[i * 2 + 1]);
		}
		int[] triangles = d.triangles;
		foreach (int num2 in triangles)
		{
			if (num2 < 0 || num2 >= num)
			{
				throw new Exception("Invalid Slots mesh index.");
			}
		}
		Mesh val = new Mesh
		{
			name = d.name,
			vertices = array,
			normals = array2,
			uv = array3,
			triangles = d.triangles
		};
		val.RecalculateBounds();
		val.UploadMeshData(true);
		return val;
	}

	private static AudioClip LoadWav(string path)
	{
		byte[] array = File.ReadAllBytes(path);
		if (array.Length < 44 || Encoding.ASCII.GetString(array, 0, 4) != "RIFF" || Encoding.ASCII.GetString(array, 8, 4) != "WAVE")
		{
			throw new Exception("Invalid pickup WAV.");
		}
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5;
		for (int i = 12; i + 8 <= array.Length; i += 8 + num5 + (num5 & 1))
		{
			string text = Encoding.ASCII.GetString(array, i, 4);
			num5 = BitConverter.ToInt32(array, i + 4);
			if (num5 < 0 || (long)i + 8L + num5 > array.Length)
			{
				throw new Exception("Invalid WAV chunk length.");
			}
			if (text == "fmt " && num5 >= 16)
			{
				num4 = BitConverter.ToInt16(array, i + 8);
				num = BitConverter.ToInt16(array, i + 10);
				num3 = BitConverter.ToInt32(array, i + 12);
				num2 = BitConverter.ToInt16(array, i + 22);
			}
			if (text == "data")
			{
				if (num4 != 1 || num != 1 || num2 != 16 || num3 != 44100 || num5 <= 0 || num5 % 2 != 0)
				{
					throw new Exception("Pickup WAV must be 44.1kHz 16-bit mono PCM.");
				}
				float[] array2 = new float[num5 / 2];
				for (int j = 0; j < array2.Length; j++)
				{
					array2[j] = (float)BitConverter.ToInt16(array, i + 8 + j * 2) / 32768f;
				}
				AudioClip obj = AudioClip.Create("bajer pickup", array2.Length, 1, num3, false);
				obj.SetData(array2, 0);
				return obj;
			}
		}
		throw new Exception("Pickup WAV contains no audio.");
	}
}

BepInEx/plugins/Preben_Mod/PrebenSoundboard.dll

Decompiled 2 months ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using ExitGames.Client.Photon;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Utilities;

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

[BepInPlugin("local.repomodforge.prebensoundboard", "Preben Soundboard", "1.0.0")]
public sealed class SoundboardPlugin : BaseUnityPlugin
{
	internal static SoundboardPlugin Instance;

	private static readonly Key[] Defaults;

	private static readonly InputKey[] Expressions;

	private const byte EventCode = 197;

	private const string EventTag = "local.repomodforge.prebensoundboard.v1";

	private readonly ConfigEntry<string>[] keyConfig = new ConfigEntry<string>[5];

	private readonly ConfigEntry<string>[] soundConfig = new ConfigEntry<string>[5];

	private readonly Key[] keys = (Key[])(object)new Key[5];

	private readonly string[] sounds = new string[5];

	private AudioClip jaClip;

	private float[] jaEnvelope;

	private Harmony harmony;

	private bool menuOpen;

	private int listeningSlot = -1;

	private Rect window = new Rect(30f, 90f, 480f, 360f);

	private float lastPlayed = -10f;

	private void Awake()
	{
		//IL_0142: Unknown result type (might be due to invalid IL or missing references)
		//IL_014c: Expected O, but got Unknown
		//IL_00be: 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)
		Instance = this;
		for (int i = 0; i < 5; i++)
		{
			keyConfig[i] = ((BaseUnityPlugin)this).Config.Bind<string>("Soundboard", "Slot" + (i + 1) + "Key", ((object)Unsafe.As<Key, Key>(ref Defaults[i])/*cast due to .constrained prefix*/).ToString(), "Keyboard key for this soundboard slot. Native gameplay keys are rejected.");
			soundConfig[i] = ((BaseUnityPlugin)this).Config.Bind<string>("Soundboard", "Slot" + (i + 1) + "Sound", (i == 0) ? "ja" : "none", "Only sounds shipped in the Preben package can be assigned.");
			keys[i] = (Key)((Enum.TryParse<Key>(keyConfig[i].Value, ignoreCase: true, out Key result) && (int)result != 0) ? ((int)result) : ((int)Defaults[i]));
			sounds[i] = ((soundConfig[i].Value == "ja") ? "ja" : "none");
		}
		try
		{
			string directoryName = Path.GetDirectoryName(((object)this).GetType().Assembly.Location);
			jaClip = LoadWav(Path.Combine(directoryName, "soundboard", "07_ja.wav"), out jaEnvelope);
			harmony = new Harmony("local.repomodforge.prebensoundboard");
			harmony.PatchAll(((object)this).GetType().Assembly);
			PhotonNetwork.NetworkingClient.EventReceived += OnNetworkEvent;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Soundboard ready: 0/9/8/7/6 slots, F8 binding menu, supplied 07_ja clip.");
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Soundboard could not initialize: " + ex));
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}

	private void OnDestroy()
	{
		if (PhotonNetwork.NetworkingClient != null)
		{
			PhotonNetwork.NetworkingClient.EventReceived -= OnNetworkEvent;
		}
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
		if ((Object)(object)Instance == (Object)(object)this)
		{
			Instance = null;
		}
	}

	private void Update()
	{
		//IL_0154: 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_015b: 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_016a: Expected O, but got Unknown
		Keyboard current = Keyboard.current;
		if (current == null || (Object)(object)jaClip == (Object)null)
		{
			return;
		}
		if (((ButtonControl)current.f8Key).wasPressedThisFrame)
		{
			menuOpen = !menuOpen;
			listeningSlot = -1;
		}
		if (menuOpen)
		{
			if (listeningSlot >= 0)
			{
				CaptureKey(current);
			}
			return;
		}
		PlayerAvatar instance = PlayerAvatar.instance;
		if ((Object)(object)instance == (Object)null || (Object)(object)instance.photonView == (Object)null || !instance.photonView.IsMine || UiBlocked())
		{
			return;
		}
		for (int i = 0; i < keys.Length; i++)
		{
			if (sounds[i] != "ja" || IsNativeConflict(keys[i]))
			{
				continue;
			}
			KeyControl val = current[keys[i]];
			if (val != null && ((ButtonControl)val).wasPressedThisFrame && !(Time.unscaledTime - lastPlayed < 0.25f))
			{
				lastPlayed = Time.unscaledTime;
				(((Component)instance).GetComponent<SoundboardPlayer>() ?? ((Component)instance).gameObject.AddComponent<SoundboardPlayer>()).Play(jaClip, jaEnvelope);
				if (PhotonNetwork.InRoom)
				{
					PhotonNetwork.RaiseEvent((byte)197, (object)new object[3]
					{
						"local.repomodforge.prebensoundboard.v1",
						instance.photonView.ViewID,
						(byte)i
					}, new RaiseEventOptions
					{
						Receivers = (ReceiverGroup)0
					}, SendOptions.SendReliable);
				}
				break;
			}
		}
	}

	private void OnNetworkEvent(EventData ev)
	{
		if (ev.Code == 197 && !((Object)(object)jaClip == (Object)null) && ev.CustomData is object[] array && array.Length == 3 && array[0] is string && !((string)array[0] != "local.repomodforge.prebensoundboard.v1") && array[1] is int && array[2] is byte && (byte)array[2] < 5)
		{
			PhotonView val = PhotonView.Find((int)array[1]);
			PlayerAvatar val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent<PlayerAvatar>());
			if (!((Object)(object)val2 == (Object)null) && !val.IsMine && val.OwnerActorNr == ev.Sender)
			{
				(((Component)val2).GetComponent<SoundboardPlayer>() ?? ((Component)val2).gameObject.AddComponent<SoundboardPlayer>()).Play(jaClip, jaEnvelope);
			}
		}
	}

	internal static bool UiBlocked()
	{
		if ((Object)(object)Instance == (Object)null || Instance.menuOpen)
		{
			return true;
		}
		if ((Object)(object)ChatManager.instance != (Object)null && ChatManager.instance.StateIsActive())
		{
			return true;
		}
		if ((Object)(object)MenuManager.instance != (Object)null)
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(MenuManager), "textInputActive");
			if (fieldInfo != null && (bool)fieldInfo.GetValue(MenuManager.instance))
			{
				return true;
			}
			FieldInfo fieldInfo2 = AccessTools.Field(typeof(MenuManager), "currentMenuPage");
			if (fieldInfo2 != null && fieldInfo2.GetValue(MenuManager.instance) != null)
			{
				return true;
			}
		}
		return false;
	}

	private static string Leaf(string path)
	{
		if (!string.IsNullOrEmpty(path))
		{
			return path.Substring(path.LastIndexOf('/') + 1);
		}
		return "";
	}

	private static bool ActionUses(Key key, InputKey actionKey)
	{
		//IL_001c: 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_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_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_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)
		InputManager instance = InputManager.instance;
		Keyboard current = Keyboard.current;
		if ((Object)(object)instance == (Object)null || current == null)
		{
			return false;
		}
		try
		{
			InputAction action = instance.GetAction(actionKey);
			if (action == null)
			{
				return false;
			}
			string b = Leaf(((InputControl)current[key]).path);
			Enumerator<InputBinding> enumerator = action.bindings.GetEnumerator();
			try
			{
				while (enumerator.MoveNext())
				{
					InputBinding current2 = enumerator.Current;
					if (string.Equals(Leaf(((InputBinding)(ref current2)).effectivePath), b, StringComparison.OrdinalIgnoreCase))
					{
						return true;
					}
				}
			}
			finally
			{
				((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
			}
		}
		catch
		{
		}
		return false;
	}

	private static bool IsNativeConflict(Key key)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0003: Invalid comparison between Unknown and I4
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_0008: Invalid comparison between Unknown and I4
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Invalid comparison between Unknown and I4
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0017: Invalid comparison between Unknown and I4
		//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_0043: 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_004d: Unknown result type (might be due to invalid IL or missing references)
		if ((int)key == 41 || (int)key == 42 || (int)key == 43 || (int)key == 101 || (int)key == 60)
		{
			return true;
		}
		foreach (InputKey value in Enum.GetValues(typeof(InputKey)))
		{
			if (Array.IndexOf(Expressions, value) < 0 && ActionUses(key, value))
			{
				return true;
			}
		}
		return false;
	}

	internal static bool OverrideExpression(InputKey action)
	{
		//IL_002b: 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)
		if ((Object)(object)Instance == (Object)null || (Object)(object)Instance.jaClip == (Object)null || UiBlocked() || Array.IndexOf(Expressions, action) < 0)
		{
			return false;
		}
		for (int i = 0; i < 5; i++)
		{
			if (Instance.sounds[i] == "ja" && !IsNativeConflict(Instance.keys[i]) && ActionUses(Instance.keys[i], action))
			{
				return true;
			}
		}
		return false;
	}

	private unsafe void CaptureKey(Keyboard keyboard)
	{
		//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_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_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_0031: Invalid comparison between Unknown and I4
		//IL_003f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0042: Invalid comparison between Unknown and I4
		//IL_0044: 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_00b0: Expected I4, but got Unknown
		//IL_008b: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Invalid comparison between I4 and Unknown
		Enumerator<KeyControl> enumerator = keyboard.allKeys.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				KeyControl current = enumerator.Current;
				if (!((ButtonControl)current).wasPressedThisFrame)
				{
					continue;
				}
				Key keyCode = current.keyCode;
				if ((int)keyCode == 60)
				{
					listeningSlot = -1;
					break;
				}
				if ((int)keyCode == 101 || IsNativeConflict(keyCode))
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Soundboard key conflicts with a game control: " + ((object)(*(Key*)(&keyCode))/*cast due to .constrained prefix*/).ToString()));
					break;
				}
				for (int i = 0; i < keys.Length; i++)
				{
					if (i != listeningSlot && (int)keys[i] == (int)keyCode)
					{
						return;
					}
				}
				keys[listeningSlot] = (Key)(int)keyCode;
				keyConfig[listeningSlot].Value = ((object)(*(Key*)(&keyCode))/*cast due to .constrained prefix*/).ToString();
				listeningSlot = -1;
				((BaseUnityPlugin)this).Config.Save();
				break;
			}
		}
		finally
		{
			((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose();
		}
	}

	private void OnGUI()
	{
		//IL_000f: 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_002a: Expected O, but got Unknown
		//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)
		if (menuOpen)
		{
			window = GUI.Window(827104, window, new WindowFunction(DrawWindow), "Preben Soundboard - bindings");
		}
	}

	private void DrawWindow(int id)
	{
		//IL_0014: 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_0073: 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_01bf: 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_00f9: Unknown result type (might be due to invalid IL or missing references)
		GUI.Label(new Rect(16f, 30f, 440f, 40f), "Only supplied sounds can be assigned. Weapon and item keys stay reserved.");
		for (int i = 0; i < 5; i++)
		{
			int num = 78 + 49 * i;
			GUI.Label(new Rect(16f, (float)num, 60f, 30f), "Slot " + (i + 1));
			if (GUI.Button(new Rect(80f, (float)num, 130f, 28f), (listeningSlot == i) ? "Press a key..." : ((object)Unsafe.As<Key, Key>(ref keys[i])/*cast due to .constrained prefix*/).ToString()))
			{
				listeningSlot = i;
			}
			GUI.Label(new Rect(222f, (float)num, 90f, 30f), (sounds[i] == "ja") ? "07_ja" : "Empty");
			if (GUI.Button(new Rect(318f, (float)num, 140f, 28f), (sounds[i] == "ja") ? "Clear sound" : "Assign 07_ja"))
			{
				sounds[i] = ((sounds[i] == "ja") ? "none" : "ja");
				soundConfig[i].Value = sounds[i];
				((BaseUnityPlugin)this).Config.Save();
			}
		}
		if (GUI.Button(new Rect(350f, 326f, 108f, 26f), "Close (F8)"))
		{
			menuOpen = false;
			listeningSlot = -1;
		}
		GUI.DragWindow(new Rect(0f, 0f, 480f, 25f));
	}

	private static AudioClip LoadWav(string path, out float[] envelope)
	{
		byte[] array = File.ReadAllBytes(path);
		if (array.Length < 44 || Encoding.ASCII.GetString(array, 0, 4) != "RIFF" || Encoding.ASCII.GetString(array, 8, 4) != "WAVE")
		{
			throw new Exception("Invalid soundboard WAV.");
		}
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4 = 0;
		int num5;
		for (int i = 12; i + 8 <= array.Length; i += 8 + num5 + (num5 & 1))
		{
			string text = Encoding.ASCII.GetString(array, i, 4);
			num5 = BitConverter.ToInt32(array, i + 4);
			if (num5 < 0 || (long)i + 8L + num5 > array.Length)
			{
				throw new Exception("Invalid WAV chunk.");
			}
			if (text == "fmt " && num5 >= 16)
			{
				num = BitConverter.ToInt16(array, i + 8);
				num2 = BitConverter.ToInt16(array, i + 10);
				num3 = BitConverter.ToInt32(array, i + 12);
				num4 = BitConverter.ToInt16(array, i + 22);
			}
			if (text == "data")
			{
				if (num != 1 || num2 != 1 || num4 != 16 || num3 != 44100 || num5 <= 0 || num5 % 2 != 0)
				{
					throw new Exception("Soundboard WAV must be 44.1 kHz 16-bit mono PCM.");
				}
				float[] array2 = new float[num5 / 2];
				envelope = new float[(array2.Length + 882 - 1) / 882];
				for (int j = 0; j < array2.Length; j++)
				{
					float num6 = (array2[j] = (float)BitConverter.ToInt16(array, i + 8 + j * 2) / 32768f);
					envelope[j / 882] += num6 * num6;
				}
				for (int k = 0; k < envelope.Length; k++)
				{
					envelope[k] = Mathf.Clamp01(Mathf.Sqrt(envelope[k] / (float)Mathf.Min(882, array2.Length - k * 882)) * 3f);
				}
				AudioClip obj = AudioClip.Create("Preben supplied 07_ja", array2.Length, 1, num3, false);
				obj.SetData(array2, 0);
				return obj;
			}
		}
		throw new Exception("Soundboard WAV has no samples.");
	}

	static SoundboardPlugin()
	{
		Key[] array = new Key[5];
		RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		Defaults = (Key[])(object)array;
		InputKey[] array2 = new InputKey[6];
		RuntimeHelpers.InitializeArray(array2, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
		Expressions = (InputKey[])(object)array2;
	}
}
[HarmonyPatch(typeof(InputManager), "KeyDown")]
internal static class ExpressionDownPatch
{
	private static bool Prefix(InputKey key, ref bool __result)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (!SoundboardPlugin.OverrideExpression(key))
		{
			return true;
		}
		__result = false;
		return false;
	}
}
[HarmonyPatch(typeof(InputManager), "KeyHold")]
internal static class ExpressionHoldPatch
{
	private static bool Prefix(InputKey key, ref bool __result)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (!SoundboardPlugin.OverrideExpression(key))
		{
			return true;
		}
		__result = false;
		return false;
	}
}
[HarmonyPatch(typeof(InputManager), "KeyUp")]
internal static class ExpressionUpPatch
{
	private static bool Prefix(InputKey key, ref bool __result)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		if (!SoundboardPlugin.OverrideExpression(key))
		{
			return true;
		}
		__result = false;
		return false;
	}
}
internal sealed class SoundboardPlayer : MonoBehaviour
{
	private AudioSource source;

	private float[] envelope;

	private PlayerVoiceChat voice;

	private PlayerAvatarTalkAnimation[] mouths;

	private float closeUntil;

	internal void Play(AudioClip clip, float[] levels)
	{
		if ((Object)(object)source == (Object)null)
		{
			source = ((Component)this).gameObject.AddComponent<AudioSource>();
			source.playOnAwake = false;
			source.loop = false;
			source.spatialBlend = 1f;
			source.rolloffMode = (AudioRolloffMode)1;
			source.minDistance = 1f;
			source.maxDistance = 18f;
			source.dopplerLevel = 0f;
			if ((Object)(object)AudioManager.instance != (Object)null)
			{
				source.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
			}
		}
		envelope = levels;
		source.Stop();
		source.clip = clip;
		source.volume = 1f;
		source.Play();
		closeUntil = Time.time + clip.length + 0.2f;
	}

	private void LateUpdate()
	{
		//IL_0184: 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_01aa: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)source == (Object)null || Time.time > closeUntil)
		{
			return;
		}
		float num = 0f;
		if (source.isPlaying && envelope != null && envelope.Length != 0)
		{
			num = envelope[Mathf.Clamp((int)(source.time * 50f), 0, envelope.Length - 1)];
		}
		if ((Object)(object)voice == (Object)null)
		{
			PlayerAvatar component = ((Component)this).GetComponent<PlayerAvatar>();
			if ((Object)(object)component != (Object)null)
			{
				ref PlayerVoiceChat reference = ref voice;
				object? value = AccessTools.Field(typeof(PlayerAvatar), "voiceChat").GetValue(component);
				reference = (PlayerVoiceChat)((value is PlayerVoiceChat) ? value : null);
			}
		}
		if ((Object)(object)voice != (Object)null && num > 0f)
		{
			voice.OverrideClipLoudnessAnimationValue(num);
		}
		if (mouths == null || mouths.Length == 0)
		{
			mouths = ((Component)this).GetComponentsInChildren<PlayerAvatarTalkAnimation>(true);
		}
		PlayerAvatarTalkAnimation[] array = mouths;
		foreach (PlayerAvatarTalkAnimation val in array)
		{
			if (!((Object)(object)val == (Object)null))
			{
				object? value2 = AccessTools.Field(typeof(PlayerAvatarTalkAnimation), "objectToRotate").GetValue(val);
				GameObject val2 = (GameObject)((value2 is GameObject) ? value2 : null);
				if (!((Object)(object)val2 == (Object)null))
				{
					float num2 = (float)AccessTools.Field(typeof(PlayerAvatarTalkAnimation), "rotationMaxAngle").GetValue(val);
					float num3 = Mathf.Lerp(0f, 0f - num2, Mathf.Clamp01(num * 4f));
					val2.transform.localRotation = Quaternion.Slerp(val2.transform.localRotation, Quaternion.Euler(num3, 0f, 0f), Mathf.Clamp01(100f * Time.deltaTime));
				}
			}
		}
	}
}

BepInEx/plugins/Preben_Mod/PrebenViolin.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using Newtonsoft.Json;
using REPOLib.Modules;
using UnityEngine;

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

public class InstrumentPart
{
	public string name;

	public float[] vertices;

	public int[] triangles;

	public float[] normals;

	public float[] uv;

	public float[] pivot;

	public int parent;

	public float[] slide;

	public float slidePeriod;

	public float[] rotate;

	public float rotatePeriod;

	public float phase;

	public bool press;

	public bool hideIdle;
}
public class InstrumentData
{
	public string name;

	public float valueMin;

	public float valueMax;

	public string sound;

	public int[][] palette;

	public InstrumentPart[] parts;
}
public sealed class InstrumentPlayer : MonoBehaviour
{
	public Transform[] parts;

	public Vector3[] home;

	public Vector3[] slide;

	public Vector3[] rotate;

	public float[] slidePeriod;

	public float[] rotatePeriod;

	public float[] phase;

	public bool[] press;

	public bool[] hideIdle;

	private PhysGrabObject grab;

	private AudioSource source;

	private float time;

	private bool wasHeld;

	private void Awake()
	{
		grab = ((Component)this).GetComponent<PhysGrabObject>();
		source = ((Component)this).GetComponent<AudioSource>();
		if ((Object)(object)source.outputAudioMixerGroup == (Object)null && (Object)(object)AudioManager.instance != (Object)null)
		{
			source.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
	}

	private float Wave(int i, float period)
	{
		if (period <= 0f)
		{
			return 0f;
		}
		float num = Mathf.Sin((float)Math.PI * 2f * (time / period + phase[i]));
		if (!press[i])
		{
			return num;
		}
		return Mathf.Max(0f, num);
	}

	private void Update()
	{
		//IL_0109: 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_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_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_015b: 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_00b5: 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)
		bool flag = (Object)(object)grab != (Object)null && grab.playerGrabbing != null && grab.playerGrabbing.Count > 0;
		if (flag && !source.isPlaying)
		{
			source.Play();
		}
		else if (!flag && source.isPlaying)
		{
			source.Stop();
		}
		if (flag != wasHeld)
		{
			time = 0f;
			wasHeld = flag;
			for (int i = 0; i < parts.Length; i++)
			{
				if (hideIdle[i])
				{
					((Component)parts[i]).gameObject.SetActive(flag);
				}
				parts[i].localPosition = home[i];
				parts[i].localRotation = Quaternion.identity;
			}
		}
		if (flag)
		{
			time += Time.deltaTime;
			for (int j = 0; j < parts.Length; j++)
			{
				parts[j].localPosition = home[j] + slide[j] * Wave(j, slidePeriod[j]);
				parts[j].localRotation = Quaternion.Euler(rotate[j] * Wave(j, rotatePeriod[j]));
			}
		}
	}
}
[BepInPlugin("local.repomodforge.prebenviolin", "Preben Instruments", "2.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInProcess("REPO.exe")]
public sealed class PrebenViolinPlugin : BaseUnityPlugin
{
	private static readonly HashSet<string> Generic = new HashSet<string> { "ValuableObject", "ValuableDiscover", "ValuableDiscoverGraphic", "MapValuable", "ValuablePropSwitch" };

	private string root;

	private bool done;

	private void Awake()
	{
		root = Path.GetDirectoryName(typeof(PrebenViolinPlugin).Assembly.Location);
	}

	private void Update()
	{
		//IL_0052: Unknown result type (might be due to invalid IL or missing references)
		//IL_0058: Expected O, but got Unknown
		if (done || ValuablePresets.AllValuablePresets.Count == 0)
		{
			return;
		}
		done = true;
		GameObject template;
		try
		{
			template = FindTemplate();
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Instruments not registered: " + ex));
			return;
		}
		GameObject val = new GameObject("Preben Instrument Prefabs");
		val.SetActive(false);
		Object.DontDestroyOnLoad((Object)(object)val);
		string[] directories = Directory.GetDirectories(root);
		foreach (string text in directories)
		{
			if (File.Exists(Path.Combine(text, "instrument.json")))
			{
				try
				{
					Register(template, val.transform, text);
				}
				catch (Exception ex2)
				{
					((BaseUnityPlugin)this).Logger.LogError((object)("Instrument in " + Path.GetFileName(text) + " not registered: " + ex2));
				}
			}
		}
	}

	private GameObject FindTemplate()
	{
		foreach (LevelValuables value in ValuablePresets.AllValuablePresets.Values)
		{
			foreach (PrefabRef item in value.tiny)
			{
				GameObject val = ((PrefabRef<GameObject>)(object)item)?.Prefab;
				if ((Object)(object)val == (Object)null || (Object)(object)val.GetComponent<ValuableObject>() == (Object)null)
				{
					continue;
				}
				bool flag = true;
				MonoBehaviour[] componentsInChildren = val.GetComponentsInChildren<MonoBehaviour>(true);
				foreach (MonoBehaviour val2 in componentsInChildren)
				{
					string text = (((Object)(object)val2 == (Object)null) ? "" : ((object)val2).GetType().Name);
					if (text.Contains("Valuable") && !Generic.Contains(text))
					{
						flag = false;
						break;
					}
				}
				if (flag)
				{
					return val;
				}
			}
		}
		throw new Exception("No plain tiny valuable found to use as a physics template.");
	}

	private static Vector3 V(float[] a)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		if (a == null || a.Length != 3)
		{
			throw new Exception("Expected a 3-number vector.");
		}
		return new Vector3(a[0], a[1], a[2]);
	}

	private void Register(GameObject template, Transform holder, string folder)
	{
		//IL_009a: 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_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_01ff: Unknown result type (might be due to invalid IL or missing references)
		//IL_0208: Expected O, but got Unknown
		//IL_0103: 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_010a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0113: 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_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_023b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0240: Unknown result type (might be due to invalid IL or missing references)
		//IL_0264: Unknown result type (might be due to invalid IL or missing references)
		//IL_0269: Unknown result type (might be due to invalid IL or missing references)
		//IL_0277: Expected O, but got Unknown
		//IL_0128: 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_0358: Unknown result type (might be due to invalid IL or missing references)
		//IL_035f: Expected O, but got Unknown
		//IL_0324: Unknown result type (might be due to invalid IL or missing references)
		//IL_05c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_05c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_05cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_05d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
		//IL_05f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0608: 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_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_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_0648: Unknown result type (might be due to invalid IL or missing references)
		//IL_0613: 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_017e: 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_0464: Unknown result type (might be due to invalid IL or missing references)
		//IL_046b: Expected O, but got Unknown
		//IL_0659: Unknown result type (might be due to invalid IL or missing references)
		//IL_0662: Unknown result type (might be due to invalid IL or missing references)
		//IL_0667: Unknown result type (might be due to invalid IL or missing references)
		//IL_066b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0676: Unknown result type (might be due to invalid IL or missing references)
		//IL_0641: Unknown result type (might be due to invalid IL or missing references)
		//IL_062b: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_050f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0514: Unknown result type (might be due to invalid IL or missing references)
		//IL_0529: Unknown result type (might be due to invalid IL or missing references)
		//IL_052e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0598: Unknown result type (might be due to invalid IL or missing references)
		InstrumentData instrumentData = JsonConvert.DeserializeObject<InstrumentData>(File.ReadAllText(Path.Combine(folder, "instrument.json")));
		if (instrumentData == null || string.IsNullOrWhiteSpace(instrumentData.name) || instrumentData.parts == null || instrumentData.parts.Length == 0 || instrumentData.parts.Length > 64 || instrumentData.palette == null || instrumentData.palette.Length == 0 || instrumentData.sound == null || instrumentData.valueMin <= 0f || instrumentData.valueMax < instrumentData.valueMin)
		{
			throw new Exception("instrument.json is incomplete.");
		}
		GameObject val = Object.Instantiate<GameObject>(template, holder);
		((Object)val).name = instrumentData.name;
		Material val2 = null;
		Bounds val3 = default(Bounds);
		bool flag = false;
		Matrix4x4 worldToLocalMatrix = val.transform.worldToLocalMatrix;
		MeshRenderer[] componentsInChildren = val.GetComponentsInChildren<MeshRenderer>(true);
		foreach (MeshRenderer val4 in componentsInChildren)
		{
			MeshFilter component = ((Component)val4).GetComponent<MeshFilter>();
			if ((Object)(object)component != (Object)null && (Object)(object)component.sharedMesh != (Object)null && ((Renderer)val4).enabled)
			{
				Bounds bounds = component.sharedMesh.bounds;
				Matrix4x4 val5 = worldToLocalMatrix * ((Component)val4).transform.localToWorldMatrix;
				for (int j = 0; j < 8; j++)
				{
					Vector3 val6 = ((Matrix4x4)(ref val5)).MultiplyPoint3x4(((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, new Vector3((float)(((j & 1) != 0) ? 1 : (-1)), (float)(((j & 2) != 0) ? 1 : (-1)), (float)(((j & 4) != 0) ? 1 : (-1)))));
					if (flag)
					{
						((Bounds)(ref val3)).Encapsulate(val6);
						continue;
					}
					((Bounds)(ref val3))..ctor(val6, Vector3.zero);
					flag = true;
				}
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = ((Renderer)val4).sharedMaterial;
				}
			}
			((Renderer)val4).enabled = false;
		}
		if (!flag || (Object)(object)val2 == (Object)null)
		{
			throw new Exception("Template " + ((Object)template).name + " has no visible mesh.");
		}
		Texture2D val7 = new Texture2D(instrumentData.palette.Length, 1, (TextureFormat)4, false)
		{
			filterMode = (FilterMode)0,
			wrapMode = (TextureWrapMode)1
		};
		for (int k = 0; k < instrumentData.palette.Length; k++)
		{
			val7.SetPixel(k, 0, Color32.op_Implicit(new Color32((byte)instrumentData.palette[k][0], (byte)instrumentData.palette[k][1], (byte)instrumentData.palette[k][2], byte.MaxValue)));
		}
		val7.Apply();
		Material val8 = new Material(val2)
		{
			name = instrumentData.name
		};
		string[] texturePropertyNames = val8.GetTexturePropertyNames();
		foreach (string text in texturePropertyNames)
		{
			string text2 = text.ToLowerInvariant();
			val8.SetTexture(text, (Texture)(object)((text2.Contains("main") || text2.Contains("albedo") || text2.Contains("base") || text2.Contains("diffuse")) ? val7 : null));
		}
		texturePropertyNames = new string[3] { "_Color", "_BaseColor", "_AlbedoColor" };
		foreach (string text3 in texturePropertyNames)
		{
			if (val8.HasProperty(text3))
			{
				val8.SetColor(text3, Color.white);
			}
		}
		val8.DisableKeyword("_EMISSION");
		GameObject val9 = new GameObject(instrumentData.name + " Mesh");
		val9.transform.SetParent(val.transform, false);
		int num = instrumentData.parts.Length;
		Transform[] array = (Transform[])(object)new Transform[num];
		InstrumentPlayer instrumentPlayer = val.AddComponent<InstrumentPlayer>();
		instrumentPlayer.parts = array;
		instrumentPlayer.home = (Vector3[])(object)new Vector3[num];
		instrumentPlayer.slide = (Vector3[])(object)new Vector3[num];
		instrumentPlayer.rotate = (Vector3[])(object)new Vector3[num];
		instrumentPlayer.slidePeriod = new float[num];
		instrumentPlayer.rotatePeriod = new float[num];
		instrumentPlayer.phase = new float[num];
		instrumentPlayer.press = new bool[num];
		instrumentPlayer.hideIdle = new bool[num];
		Mesh val10 = null;
		for (int l = 0; l < num; l++)
		{
			InstrumentPart instrumentPart = instrumentData.parts[l];
			if (instrumentPart.parent >= l || instrumentPart.parent < -1)
			{
				throw new Exception("Part " + l + " has an invalid parent.");
			}
			GameObject val11 = new GameObject(instrumentData.name + " " + instrumentPart.name);
			val11.transform.SetParent((instrumentPart.parent < 0) ? val9.transform : array[instrumentPart.parent], false);
			Mesh val12 = BuildMesh(instrumentPart, instrumentData.name + " " + instrumentPart.name);
			if (l == 0)
			{
				val10 = val12;
			}
			val11.AddComponent<MeshFilter>().sharedMesh = val12;
			((Renderer)val11.AddComponent<MeshRenderer>()).sharedMaterial = val8;
			array[l] = val11.transform;
			instrumentPlayer.home[l] = V(instrumentPart.pivot);
			instrumentPlayer.slide[l] = V(instrumentPart.slide);
			instrumentPlayer.rotate[l] = V(instrumentPart.rotate);
			instrumentPlayer.slidePeriod[l] = instrumentPart.slidePeriod;
			instrumentPlayer.rotatePeriod[l] = instrumentPart.rotatePeriod;
			instrumentPlayer.phase[l] = instrumentPart.phase;
			instrumentPlayer.press[l] = instrumentPart.press;
			instrumentPlayer.hideIdle[l] = instrumentPart.hideIdle;
			val11.transform.localPosition = instrumentPlayer.home[l];
			if (instrumentPart.hideIdle)
			{
				val11.SetActive(false);
			}
		}
		Vector3 size = ((Bounds)(ref val3)).size;
		float num2 = Mathf.Max(size.x, Mathf.Max(size.y, size.z));
		val9.transform.localPosition = ((Bounds)(ref val3)).center;
		val9.transform.localRotation = ((num2 == size.y) ? Quaternion.identity : ((num2 == size.x) ? Quaternion.Euler(0f, 0f, 90f) : Quaternion.Euler(90f, 0f, 0f)));
		Transform transform = val9.transform;
		Vector3 one = Vector3.one;
		float num3 = num2;
		Bounds bounds2 = val10.bounds;
		transform.localScale = one * (num3 / ((Bounds)(ref bounds2)).size.y);
		ValuableObject component2 = val.GetComponent<ValuableObject>();
		Value val13 = ScriptableObject.CreateInstance<Value>();
		val13.valueMin = instrumentData.valueMin;
		val13.valueMax = instrumentData.valueMax;
		((Object)val13).name = "Value - " + instrumentData.name;
		component2.valuePreset = val13;
		AudioSource val14 = val.AddComponent<AudioSource>();
		val14.clip = LoadWav(SafePath(folder, instrumentData.sound), instrumentData.name);
		val14.loop = true;
		val14.playOnAwake = false;
		val14.spatialBlend = 1f;
		val14.volume = 0.8f;
		val14.rolloffMode = (AudioRolloffMode)1;
		val14.minDistance = 1f;
		val14.maxDistance = 20f;
		val14.dopplerLevel = 0f;
		if ((Object)(object)AudioManager.instance != (Object)null)
		{
			val14.outputAudioMixerGroup = AudioManager.instance.SoundMasterGroup;
		}
		Valuables.RegisterValuable(component2, new List<string> { "Valuables - Generic" });
		((BaseUnityPlugin)this).Logger.LogInfo((object)(instrumentData.name + " registered (" + num + " parts, template " + ((Object)template).name + ", shader " + ((Object)val8.shader).name + ", length " + num2.ToString("0.000") + " m)."));
	}

	private static string SafePath(string folder, string relative)
	{
		if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative))
		{
			throw new Exception("Sound must be a relative path.");
		}
		string text = Path.GetFullPath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
		string fullPath = Path.GetFullPath(Path.Combine(text, relative));
		if (!fullPath.StartsWith(text + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
		{
			throw new Exception("Sound must be inside the instrument folder.");
		}
		return fullPath;
	}

	private static Mesh BuildMesh(InstrumentPart data, string name)
	{
		//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_0124: 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_0149: 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_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0166: Unknown result type (might be due to invalid IL or missing references)
		//IL_016d: 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_017b: 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_018e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0195: Expected O, but got Unknown
		int num = ((data.vertices != null) ? (data.vertices.Length / 3) : 0);
		if (num == 0 || num > 65000 || data.normals == null || data.normals.Length != num * 3 || data.uv == null || data.uv.Length != num * 2 || data.triangles == null || data.triangles.Length % 3 != 0)
		{
			throw new Exception("Malformed mesh: " + name);
		}
		int[] triangles = data.triangles;
		foreach (int num2 in triangles)
		{
			if (num2 < 0 || num2 >= num)
			{
				throw new Exception("Bad triangle index in " + name);
			}
		}
		Vector3[] array = (Vector3[])(object)new Vector3[num];
		Vector3[] array2 = (Vector3[])(object)new Vector3[num];
		Vector2[] array3 = (Vector2[])(object)new Vector2[num];
		for (int j = 0; j < num; j++)
		{
			array[j] = new Vector3(data.vertices[j * 3], data.vertices[j * 3 + 1], data.vertices[j * 3 + 2]);
			array2[j] = new Vector3(data.normals[j * 3], data.normals[j * 3 + 1], data.normals[j * 3 + 2]);
			array3[j] = new Vector2(data.uv[j * 2], data.uv[j * 2 + 1]);
		}
		Mesh val = new Mesh
		{
			name = name,
			vertices = array,
			normals = array2,
			uv = array3,
			triangles = data.triangles
		};
		val.RecalculateBounds();
		return val;
	}

	private static AudioClip LoadWav(string path, string name)
	{
		byte[] array = File.ReadAllBytes(path);
		if (array.Length < 44 || array[0] != 82 || array[8] != 87)
		{
			throw new Exception(Path.GetFileName(path) + " is not a WAV file.");
		}
		int i = 12;
		int num = 0;
		int num2 = 0;
		int num3 = 0;
		int num4;
		for (; i + 8 <= array.Length; i += 8 + num4 + (num4 & 1))
		{
			string text = Encoding.ASCII.GetString(array, i, 4);
			num4 = BitConverter.ToInt32(array, i + 4);
			if (num4 < 0)
			{
				break;
			}
			if (text == "fmt ")
			{
				num2 = BitConverter.ToInt16(array, i + 10);
				num = BitConverter.ToInt32(array, i + 12);
				num3 = BitConverter.ToInt16(array, i + 22);
			}
			else if (text == "data")
			{
				if (num2 != 1 || num3 != 16 || num <= 0 || num4 <= 0 || i + 8 + num4 > array.Length)
				{
					throw new Exception("Sound must be 16-bit mono PCM.");
				}
				float[] array2 = new float[num4 / 2];
				for (int j = 0; j < array2.Length; j++)
				{
					array2[j] = (float)BitConverter.ToInt16(array, i + 8 + j * 2) / 32768f;
				}
				AudioClip obj = AudioClip.Create(name, array2.Length, 1, num, false);
				obj.SetData(array2, 0);
				return obj;
			}
		}
		throw new Exception(Path.GetFileName(path) + " has no audio data.");
	}
}