Decompiled source of AutoMute v1.3.0

AutoMute.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AutoMute")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoMute")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("4b2c8cf7-fb91-4b71-b98c-6c209e9bdb68")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.3.0.0")]
[module: UnverifiableCode]
namespace AutoMute;

internal class IngameUI
{
	private static GameObject group;

	private static InputField filterInput;

	private static Text muteInfoText;

	private static UIToggle filterMuteOnlyToggle;

	private static UIComboBox audioComboBox;

	private static Text audioClipPath;

	private static UIToggle audioEnableToggle;

	private static Button playAudioButton;

	private static Text playAutoButtonText;

	private static bool filterMuteOnly = false;

	private static string searchStr = "";

	private static AudioProto audioProto = null;

	private static VFAudio vFAudio = null;

	[HarmonyPrefix]
	[HarmonyPatch(typeof(VFListener), "SetPassFilter")]
	public static bool SetPassFilter_Block()
	{
		if ((Object)(object)vFAudio != (Object)null && vFAudio.isPlaying)
		{
			((Behaviour)VFListener.lowPassFilter).enabled = false;
			((Behaviour)VFListener.highPassFilter).enabled = false;
			return false;
		}
		return true;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "_OnOpen")]
	public static void Init(UIOptionWindow __instance)
	{
		//IL_007d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_0101: Unknown result type (might be due to invalid IL or missing references)
		//IL_0152: Unknown result type (might be due to invalid IL or missing references)
		//IL_0177: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0213: Unknown result type (might be due to invalid IL or missing references)
		//IL_0281: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_03bc: Expected O, but got Unknown
		//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_0446: Unknown result type (might be due to invalid IL or missing references)
		//IL_04af: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_04f1: Unknown result type (might be due to invalid IL or missing references)
		//IL_04fb: Expected O, but got Unknown
		if (!((Object)(object)group == (Object)null))
		{
			return;
		}
		Plugin.Log.LogDebug((object)"init");
		try
		{
			GameObject val = GameObject.Find("UI Root/Overlay Canvas/Top Windows/Option Window/details/content-2");
			GameObject gameObject = ((Component)((Component)__instance.fullscreenComp).transform.parent).gameObject;
			GameObject gameObject2 = ((Component)((Component)__instance.resolutionComp).transform).gameObject;
			GameObject gameObject3 = ((Component)UIRoot.instance.uiGame.planetGlobe.nameInput).gameObject;
			GameObject gameObject4 = ((Component)__instance.revertButtons[0]).gameObject;
			group = new GameObject("AutoMute_Group");
			group.transform.SetParent(val.transform);
			group.transform.localPosition = new Vector3(-100f, 320f);
			group.transform.localScale = Vector3.one;
			GameObject val2 = Object.Instantiate<GameObject>(gameObject3, group.transform);
			((Object)val2).name = "AudioName Filter";
			val2.transform.localPosition = new Vector3(-2f, -30f, 0f);
			filterInput = val2.GetComponent<InputField>();
			filterInput.text = "";
			((UnityEvent<string>)(object)filterInput.onValueChanged).AddListener((UnityAction<string>)OnInputValueChanged);
			val2.GetComponent<RectTransform>().sizeDelta = new Vector2(203f, 30f);
			((Graphic)val2.GetComponent<Image>()).color = new Color(0f, 0f, 0f, 0.5f);
			val2.SetActive(true);
			val2 = Object.Instantiate<GameObject>(gameObject, group.transform);
			((Object)val2).name = "Filter Mute Only Toggle";
			val2.transform.localPosition = new Vector3(240f, -30f, 0f);
			Object.Destroy((Object)(object)val2.GetComponent<Localizer>());
			muteInfoText = val2.GetComponent<Text>();
			muteInfoText.text = "";
			filterMuteOnlyToggle = val2.GetComponentInChildren<UIToggle>();
			((Component)filterMuteOnlyToggle).transform.localPosition = new Vector3(-40f, 5f, 0f);
			filterMuteOnlyToggle.isOn = filterMuteOnly;
			((UnityEvent<bool>)(object)filterMuteOnlyToggle.toggle.onValueChanged).AddListener((UnityAction<bool>)OnFilterMuteOnlyToggleChange);
			val2 = Object.Instantiate<GameObject>(gameObject2, group.transform, false);
			((Object)val2).name = "Audio ComboBox";
			val2.transform.localPosition = new Vector3(0f, -60f, 0f);
			Transform val3 = val2.transform.Find("Dropdown List ScrollBox/Mask/Content Panel/");
			for (int num = val3.childCount - 1; num >= 0; num--)
			{
				if (((Object)val3.GetChild(num)).name == "Item Button(Clone)")
				{
					Object.Destroy((Object)(object)((Component)val3.GetChild(num)).gameObject);
				}
			}
			audioComboBox = val2.GetComponentInChildren<UIComboBox>();
			((UnityEventBase)audioComboBox.onItemIndexChange).RemoveAllListeners();
			RefreshAudioComboBox();
			audioComboBox.m_Text.supportRichText = true;
			audioComboBox.m_EmptyItemRes.supportRichText = true;
			((Component)audioComboBox.m_ListItemRes).GetComponentInChildren<Text>().supportRichText = true;
			foreach (Button itemButton in audioComboBox.ItemButtons)
			{
				((Component)itemButton).GetComponentInChildren<Text>().supportRichText = true;
			}
			audioComboBox.DropDownCount = 20;
			audioComboBox.itemIndex = 0;
			audioComboBox.m_Input.text = "<i>(Select Audio)</i>";
			((UnityEvent)audioComboBox.onItemIndexChange).AddListener(new UnityAction(OnComboBoxIndexChange));
			val2 = Object.Instantiate<GameObject>(gameObject, group.transform);
			((Object)val2).name = "Audio Enable Toggle";
			val2.transform.localPosition = new Vector3(240f, -60f, 0f);
			Object.Destroy((Object)(object)val2.GetComponent<Localizer>());
			audioClipPath = val2.GetComponent<Text>();
			audioClipPath.text = "(Audio ClipPath)";
			audioEnableToggle = val2.GetComponentInChildren<UIToggle>();
			((Component)audioEnableToggle).transform.localPosition = new Vector3(-40f, 5f, 0f);
			audioEnableToggle.isOn = true;
			((UnityEvent<bool>)(object)audioEnableToggle.toggle.onValueChanged).AddListener((UnityAction<bool>)OnAudioEnableToggleChange);
			val2 = Object.Instantiate<GameObject>(gameObject4, group.transform);
			((Object)val2).name = "Play Audio Button";
			val2.transform.localPosition = new Vector3(210f, -130f, 0f);
			val2.GetComponent<RectTransform>().sizeDelta = new Vector2(90f, 30f);
			playAudioButton = val2.GetComponent<Button>();
			((UnityEvent)playAudioButton.onClick).AddListener(new UnityAction(PlayAudio));
			playAutoButtonText = val2.GetComponentInChildren<Text>();
			playAutoButtonText.text = Localization.Translate("Play Audio");
			Object.Destroy((Object)(object)val2.GetComponent<UIButton>());
			Object.Destroy((Object)(object)val2.GetComponentInChildren<Localizer>());
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)"UI component initial fail!");
			Plugin.Log.LogWarning((object)ex);
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "_OnClose")]
	public static void OnClose()
	{
		VFAudio obj = vFAudio;
		if (obj != null)
		{
			obj.Stop();
		}
		vFAudio = null;
	}

	public static void OnDestory()
	{
		VFAudio obj = vFAudio;
		if (obj != null)
		{
			obj.Stop();
		}
		vFAudio = null;
		Object.Destroy((Object)(object)group);
		group = null;
	}

	private static void PlayAudio()
	{
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		if (audioProto != null)
		{
			Plugin.Log.LogDebug((object)("PlayAudio: " + ((Proto)audioProto).name));
			if ((Object)(object)vFAudio != (Object)null)
			{
				vFAudio.Stop();
			}
			vFAudio = VFAudio.Create(((Proto)audioProto).name, (Transform)null, Vector3.zero, false, 0, -1, -1L);
			vFAudio.Play();
		}
	}

	private static void OnFilterMuteOnlyToggleChange(bool value)
	{
		filterMuteOnlyToggle.isOn = value;
		filterMuteOnly = value;
		RefreshAudioComboBox();
		OnComboBoxIndexChange();
	}

	private static void OnAudioEnableToggleChange(bool value)
	{
		audioEnableToggle.isOn = value;
		if (audioProto == null)
		{
			return;
		}
		if (value)
		{
			if (Plugin.AudioVolumes.TryGetValue(((Proto)audioProto).name, out var value2))
			{
				audioProto.Volume = value2;
				Plugin.AudioVolumes.Remove(((Proto)audioProto).name);
				playAutoButtonText.text = Localization.Translate("Play Audio");
			}
		}
		else if (!Plugin.AudioVolumes.ContainsKey(((Proto)audioProto).name))
		{
			Plugin.AudioVolumes.Add(((Proto)audioProto).name, audioProto.Volume);
			audioProto.Volume = 0f;
			playAutoButtonText.text = Localization.Translate("Muted");
		}
		audioComboBox.m_Input.text = GetRichText(((Proto)audioProto).name);
		Plugin.Log.LogDebug((object)$"[{((Proto)audioProto).name}]: {audioProto.Volume}");
		StringBuilder stringBuilder = new StringBuilder();
		foreach (string key in Plugin.AudioVolumes.Keys)
		{
			stringBuilder.Append(key);
			stringBuilder.Append(' ');
		}
		Plugin.Instance.MuteList.Value = stringBuilder.ToString();
		Plugin.IsDirty = true;
		RefreshAudioComboBox();
	}

	public static void OnComboBoxIndexChange()
	{
		if (audioComboBox.itemIndex >= 0 && audioComboBox.itemIndex < audioComboBox.Items.Count)
		{
			int num = audioComboBox.ItemsData[audioComboBox.itemIndex];
			audioProto = ((ProtoSet<AudioProto>)(object)LDB.audios).dataArray[num];
			audioClipPath.text = audioProto.ClipPath;
			bool flag = Plugin.AudioVolumes.ContainsKey(((Proto)audioProto).name);
			audioEnableToggle.isOn = !flag;
			playAutoButtonText.text = (flag ? Localization.Translate("Muted") : Localization.Translate("Play Audio"));
		}
		else
		{
			audioProto = null;
			audioComboBox.m_Input.text = "";
			audioClipPath.text = "";
			audioEnableToggle.isOn = false;
			playAutoButtonText.text = Localization.Translate("No Audio");
		}
		if ((Object)(object)vFAudio != (Object)null)
		{
			vFAudio.Stop();
			vFAudio = null;
		}
	}

	private static void OnInputValueChanged(string value)
	{
		searchStr = value;
		RefreshAudioComboBox();
		if (audioComboBox.Items.Count > 0)
		{
			audioComboBox.itemIndex = 0;
		}
		OnComboBoxIndexChange();
	}

	private static void RefreshAudioComboBox()
	{
		audioComboBox.Items.Clear();
		audioComboBox.ItemsData.Clear();
		int num = 0;
		for (int i = 0; i < ((ProtoSet<AudioProto>)(object)LDB.audios).dataArray.Length; i++)
		{
			string name = ((Proto)((ProtoSet<AudioProto>)(object)LDB.audios).dataArray[i]).name;
			if (Plugin.AudioVolumes.ContainsKey(name))
			{
				num++;
			}
			else if (filterMuteOnly)
			{
				continue;
			}
			if (string.IsNullOrEmpty(searchStr) || name.IndexOf(searchStr, 0, StringComparison.OrdinalIgnoreCase) != -1)
			{
				audioComboBox.ItemsData.Add(i);
				audioComboBox.Items.Add(GetRichText(name));
			}
		}
		muteInfoText.text = $"{audioComboBox.Items.Count}/{((ProtoSet<AudioProto>)(object)LDB.audios).dataArray.Length}";
		if (filterMuteOnly)
		{
			Text obj = muteInfoText;
			obj.text += " (mute only)";
		}
		else
		{
			Text obj2 = muteInfoText;
			obj2.text += $" ({num} muted)";
		}
	}

	private static string GetRichText(string audioName)
	{
		if (Plugin.AudioVolumes.ContainsKey(audioName))
		{
			return "<color=#ff9900ff>" + audioName + "</color>";
		}
		return audioName;
	}
}
[BepInPlugin("starfi5h.plugin.AutoMute", "AutoMute", "1.3.0")]
public class Plugin : BaseUnityPlugin
{
	public const string GUID = "starfi5h.plugin.AutoMute";

	public const string NAME = "AutoMute";

	public const string VERSION = "1.3.0";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal Harmony harmony;

	internal ConfigEntry<string> MuteBuildingIds;

	internal ConfigEntry<string> MuteList;

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

	private static readonly Dictionary<int, float> ModelVolumes = new Dictionary<int, float>();

	internal static bool IsDirty = true;

	public void BindConfig()
	{
		MuteBuildingIds = ((BaseUnityPlugin)this).Config.Bind<string>("- General -", "Mute Building Ids", "", "The ids of building to mute, separated by white spaces.\n消除指定建筑的音讯。输入:建筑物品id, 以空白分隔。");
		MuteList = ((BaseUnityPlugin)this).Config.Bind<string>("- General -", "MuteList", "vc-broadcast-4 vc-broadcast-5 vc-broadcast-6 vc-broadcast-7 vc-broadcast-8 vc-broadcast-22", "The list of audio name to mute, separated by white spaces. Check mod page wiki for available names.\n消除指定的音讯。输入:音讯名称, 以空白分隔(名称可以在mod页面wiki查询)");
	}

	internal void Awake()
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_008e: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		BindConfig();
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		harmony = new Harmony("starfi5h.plugin.AutoMute");
		harmony.PatchAll(typeof(Plugin));
		harmony.PatchAll(typeof(IngameUI));
		MethodInfo methodInfo = AccessTools.Method(typeof(UIMechaMoveTip), "OnForgeTaskDelivery", (Type[])null, (Type[])null);
		if (methodInfo != null)
		{
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(Plugin), "Suppress", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}
	}

	private static bool Suppress()
	{
		return false;
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(UIOptionWindow), "OnApplyClick")]
	internal static void OnApplyClick()
	{
		((BaseUnityPlugin)Instance).Config.Reload();
		ApplySettings();
		if (IsDirty)
		{
			AudioData.LoadStatic();
			IsDirty = false;
		}
	}

	[HarmonyPostfix]
	[HarmonyPatch(typeof(VFPreload), "InvokeOnLoadWorkEnded")]
	[HarmonyAfter(new string[] { "me.xiaoye97.plugin.Dyson.LDBTool" })]
	internal static void ApplySettings()
	{
		ChangeAudioVolumes();
		ChangeBuildingVolumes();
		if (AudioVolumes.Count + ModelVolumes.Count > 0)
		{
			((BaseUnityPlugin)Instance).Logger.LogDebug((object)$"Mute {AudioVolumes.Count} audios and {ModelVolumes.Count} buildings.");
		}
	}

	private static void ChangeAudioVolumes()
	{
		foreach (KeyValuePair<string, float> audioVolume in AudioVolumes)
		{
			AudioProto val = LDB.audios[audioVolume.Key];
			if (val != null)
			{
				val.Volume = audioVolume.Value;
			}
		}
		AudioVolumes.Clear();
		string[] array = Instance.MuteList.Value.Split(' ', ',', '\n');
		foreach (string text in array)
		{
			if (!Utility.IsNullOrWhiteSpace(text))
			{
				AudioProto val2 = LDB.audios[text];
				if (val2 != null)
				{
					AudioVolumes.Add(text, val2.Volume);
					val2.Volume = 0f;
				}
				else
				{
					((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Can't find audio name: " + text));
				}
			}
		}
	}

	private static void ChangeBuildingVolumes()
	{
		foreach (KeyValuePair<int, float> modelVolume in ModelVolumes)
		{
			ModelProto val = ((ProtoSet<ModelProto>)(object)LDB.models).Select(modelVolume.Key);
			if (val != null)
			{
				val.prefabDesc.audioVolume = modelVolume.Value;
			}
		}
		ModelVolumes.Clear();
		string[] array = Instance.MuteBuildingIds.Value.Split(' ', ',');
		foreach (string text in array)
		{
			if (Utility.IsNullOrWhiteSpace(text))
			{
				continue;
			}
			if (int.TryParse(text, out var result))
			{
				ItemProto obj = ((ProtoSet<ItemProto>)(object)LDB.items).Select(result);
				if (obj == null)
				{
					((BaseUnityPlugin)Instance).Logger.LogWarning((object)$"Can't find item {result}");
				}
				_ = ((Proto)obj).Name;
				int modelIndex = obj.ModelIndex;
				ModelProto val2 = ((ProtoSet<ModelProto>)(object)LDB.models).Select(modelIndex);
				if (val2 != null)
				{
					ModelVolumes.Add(modelIndex, val2.prefabDesc.audioVolume);
					val2.prefabDesc.audioVolume = 0f;
				}
			}
			else
			{
				((BaseUnityPlugin)Instance).Logger.LogWarning((object)("Can't parse \"" + text + "\" to int"));
			}
		}
	}
}