Decompiled source of PatronAmbient v1.0.1

AmbientSwap.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AmbientSwap")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("AmbientSwap")]
[assembly: AssemblyTitle("AmbientSwap")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AmbientSwap
{
	[BepInPlugin("user.repo.ambientswap", "Ambient Swap", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private readonly List<AudioClip> clips = new List<AudioClip>();

		private readonly HashSet<int> volumeDone = new HashSet<int>();

		private ConfigEntry<string> keywords;

		private ConfigEntry<string> mixers;

		private ConfigEntry<float> volume;

		private ConfigEntry<bool> debug;

		private ConfigEntry<float> interval;

		private ConfigEntry<float> minDelay;

		private ConfigEntry<float> maxDelay;

		private readonly List<AudioSource> tracked = new List<AudioSource>();

		private void Awake()
		{
			mixers = ((BaseUnityPlugin)this).Config.Bind<string>("General", "MixerGroups", "Ambience", "Через запятую. Заменяются все AudioSource, чья микшер-группа называется так (в R.E.P.O. атмосфера уровня идёт через группу Ambience).");
			keywords = ((BaseUnityPlugin)this).Config.Bind<string>("General", "ExtraKeywords", "", "Через запятую, по желанию. Дополнительно заменять источники, у которых слово есть в пути объекта или имени клипа (например: cauldron,humming).");
			volume = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Volume", 1f, "Множитель громкости заменённых источников (1 = как в игре).");
			interval = ((BaseUnityPlugin)this).Config.Bind<float>("General", "ScanInterval", 0.5f, "Как часто (сек) искать новые источники звука.");
			minDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Timing", "MinDelaySeconds", 30f, "Минимальная пауза между проигрываниями звука.");
			maxDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Timing", "MaxDelaySeconds", 180f, "Максимальная пауза между проигрываниями звука.");
			debug = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "LogSources", false, "Писать в лог все найденные зацикленные AudioSource (чтобы подобрать Keywords).");
			((MonoBehaviour)this).StartCoroutine(Run());
		}

		private IEnumerator Run()
		{
			string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			foreach (string path in from f in Directory.GetFiles(directoryName, "*.wav")
				orderby f
				select f)
			{
				UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip("file:///" + path.Replace('\\', '/'), (AudioType)20);
				try
				{
					yield return req.SendWebRequest();
					if ((int)req.result != 1)
					{
						((BaseUnityPlugin)this).Logger.LogError((object)("Не удалось загрузить " + path + ": " + req.error));
						continue;
					}
					AudioClip content = DownloadHandlerAudioClip.GetContent(req);
					((Object)content).name = "AmbientSwap_" + Path.GetFileNameWithoutExtension(path);
					clips.Add(content);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Звук загружен: " + Path.GetFileName(path) + ", " + content.length.ToString("F1") + " c"));
				}
				finally
				{
					((IDisposable)req)?.Dispose();
				}
			}
			if (clips.Count == 0)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"В папке плагина нет .wav файлов.");
				yield break;
			}
			WaitForSeconds wait = new WaitForSeconds(Mathf.Max(0.5f, interval.Value));
			string[] keys = (from k in keywords.Value.Split(',')
				select k.Trim().ToLowerInvariant() into k
				where k.Length > 0
				select k).ToArray();
			string[] mix = (from k in mixers.Value.Split(',')
				select k.Trim().ToLowerInvariant() into k
				where k.Length > 0
				select k).ToArray();
			((MonoBehaviour)this).StartCoroutine(Player());
			while (true)
			{
				AudioSource[] array = Object.FindObjectsByType<AudioSource>((FindObjectsSortMode)0);
				foreach (AudioSource val in array)
				{
					if ((Object)(object)val == (Object)null || ((Object)(object)val.clip != (Object)null && clips.Contains(val.clip)))
					{
						continue;
					}
					if (debug.Value && val.loop)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("loop: " + HierPath(val) + " | clip=" + (Object.op_Implicit((Object)(object)val.clip) ? ((Object)val.clip).name : "null") + " | mixer=" + (Object.op_Implicit((Object)(object)val.outputAudioMixerGroup) ? ((Object)val.outputAudioMixerGroup).name : "none")));
					}
					if (IsAmbient(val, keys, mix))
					{
						val.Stop();
						val.clip = clips[0];
						val.loop = false;
						if (!tracked.Contains(val))
						{
							tracked.Add(val);
						}
						if (volumeDone.Add(((Object)val).GetInstanceID()))
						{
							val.volume *= volume.Value;
						}
					}
				}
				yield return wait;
			}
		}

		private IEnumerator Player()
		{
			while (true)
			{
				float num = Mathf.Max(1f, Mathf.Min(minDelay.Value, maxDelay.Value));
				float num2 = Mathf.Max(num, maxDelay.Value);
				float num3 = Random.Range(num, num2);
				if (debug.Value)
				{
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Следующий звук через " + num3.ToString("F0") + " c"));
				}
				yield return (object)new WaitForSeconds(num3);
				tracked.RemoveAll((AudioSource a) => (Object)(object)a == (Object)null);
				List<AudioSource> list = tracked.Where((AudioSource a) => ((Behaviour)a).isActiveAndEnabled && (Object)(object)a.clip != (Object)null && clips.Contains(a.clip)).ToList();
				if (list.Count != 0)
				{
					AudioSource obj = list[Random.Range(0, list.Count)];
					obj.clip = clips[Random.Range(0, clips.Count)];
					obj.loop = false;
					obj.Play();
				}
			}
		}

		private static string HierPath(AudioSource s)
		{
			string text = ((Object)s).name;
			Transform parent = ((Component)s).transform.parent;
			while ((Object)(object)parent != (Object)null)
			{
				text = ((Object)parent).name + "/" + text;
				parent = parent.parent;
			}
			return text;
		}

		private static bool IsAmbient(AudioSource s, string[] keys, string[] mix)
		{
			if (Object.op_Implicit((Object)(object)s.outputAudioMixerGroup))
			{
				string m = ((Object)s.outputAudioMixerGroup).name.ToLowerInvariant();
				if (mix.Any((string x) => m == x || m.Contains(x)))
				{
					return true;
				}
			}
			if (keys.Length == 0)
			{
				return false;
			}
			string text = HierPath(s).ToLowerInvariant();
			if (Object.op_Implicit((Object)(object)s.clip))
			{
				text = text + "|" + ((Object)s.clip).name.ToLowerInvariant();
			}
			return keys.Any(text.Contains);
		}
	}
}