using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ComputerysModdingUtilities;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("CombatSounds")]
[assembly: AssemblyDescription("Your own hit, head hit, kill and melee kill sounds, and gun volume.")]
[assembly: StraftatMod(true)]
[assembly: AssemblyVersion("1.1.9.0")]
namespace CombatSounds;
[BepInPlugin("dorsth.straftat.combatsounds", "CombatSounds", "1.1.9")]
public sealed class CombatSoundsPlugin : BaseUnityPlugin
{
public const string Guid = "dorsth.straftat.combatsounds";
public const string Name = "CombatSounds";
public const string Version = "1.1.9";
internal static ManualLogSource Log;
internal static SoundSlot Hit;
internal static SoundSlot HeadHit;
internal static SoundSlot Kill;
internal static SoundSlot MeleeKill;
internal static ConfigEntry<int> GunVolume;
private void Awake()
{
//IL_0176: Unknown result type (might be due to invalid IL or missing references)
//IL_0180: Expected O, but got Unknown
//IL_018a: Unknown result type (might be due to invalid IL or missing references)
//IL_0190: Expected O, but got Unknown
Log = ((BaseUnityPlugin)this).Logger;
Log.LogInfo((object)"CombatSounds 1.1.9 loaded. Dorsth was here.");
SceneManager.sceneLoaded += delegate
{
GunSounds.Prune();
};
string text = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
if (string.Equals(Path.GetFullPath(text).TrimEnd('\\', '/'), Path.GetFullPath(Paths.PluginPath).TrimEnd('\\', '/'), StringComparison.OrdinalIgnoreCase))
{
text = Path.Combine(text, "CombatSounds");
}
string folder = Path.Combine(text, "KillSounds");
Hit = new SoundSlot(((BaseUnityPlugin)this).Config, SoundKind.Hit, "Hit Sound", Path.Combine(text, "HitSounds"), "When you hit a player.");
HeadHit = new SoundSlot(((BaseUnityPlugin)this).Config, SoundKind.HeadHit, "Head Hit Sound", Path.Combine(text, "HeadHitSounds"), "When you hit a head.", Hit, "Same as Hit");
Kill = new SoundSlot(((BaseUnityPlugin)this).Config, SoundKind.Kill, "Kill Sound", folder, "When you kill a player.");
MeleeKill = new SoundSlot(((BaseUnityPlugin)this).Config, SoundKind.MeleeKill, "Melee Kill Sound", Path.Combine(text, "MeleeKillSounds"), "When you kill with a melee weapon.", Kill, "Same as Kill");
GunVolume = ((BaseUnityPlugin)this).Config.Bind<int>("Guns", "Gun Sound Volume", 100, new ConfigDescription("Shots, reloads, empty clicks and casings, yours and others'. 100 is normal.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
Harmony harmony = new Harmony("dorsth.straftat.combatsounds");
try
{
Hooks.Install(harmony);
}
catch (Exception ex)
{
Log.LogError((object)("Couldn't hook the game's hit sounds, so the mod is off. (" + ex.Message + ")"));
}
try
{
GunSounds.Install(harmony);
}
catch (Exception ex2)
{
Log.LogError((object)("Couldn't hook the gun sounds, so Gun Sound Volume is off. (" + ex2.Message + ")"));
}
}
}
internal enum SoundKind
{
Hit,
HeadHit,
Kill,
MeleeKill
}
internal sealed class SoundSlot
{
private const string Default = "Default";
private const string None = "None";
private static GameObject _speaker;
private readonly ConfigEntry<string> _choice;
private readonly ConfigEntry<int> _volume;
private readonly Dictionary<string, string> _files = new Dictionary<string, string>();
private readonly string _name;
private readonly SoundKind _kind;
private readonly SoundSlot _hit;
private readonly string _same;
private AudioSource _source;
private AudioClip _clip;
private AudioClip _louder;
private AudioClip _louderOf;
private string _sound;
private bool _none;
private bool _following;
private int _loadId;
private int _louderVolume;
private float _nextPreview;
private AudioClip _gameA;
private AudioClip _gameB;
private SoundSlot Pick
{
get
{
if (!_following)
{
return this;
}
return _hit.Pick;
}
}
internal bool ReplacesGameSound
{
get
{
SoundSlot pick = Pick;
if (!((Object)(object)pick._clip != (Object)null))
{
return pick._none;
}
return true;
}
}
internal bool HasSound => (Object)(object)Pick._clip != (Object)null;
internal SoundSlot(ConfigFile config, SoundKind kind, string name, string folder, string description, SoundSlot follows = null, string same = null)
{
//IL_0181: Unknown result type (might be due to invalid IL or missing references)
//IL_018b: Expected O, but got Unknown
//IL_01b9: Unknown result type (might be due to invalid IL or missing references)
//IL_01c3: Expected O, but got Unknown
_kind = kind;
_name = name;
_hit = follows;
_same = same;
List<string> list = new List<string> { "Default", "None" };
if (follows != null)
{
list.Add(same);
}
try
{
Directory.CreateDirectory(folder);
string[] files = Directory.GetFiles(folder);
Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
string[] array = files;
foreach (string text in array)
{
string text2 = Path.GetExtension(text).ToLowerInvariant();
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text);
if ((!(text2 != ".wav") || !(text2 != ".ogg") || !(text2 != ".mp3")) && !list.Contains(fileNameWithoutExtension))
{
list.Add(fileNameWithoutExtension);
_files[fileNameWithoutExtension] = text;
}
}
}
catch (Exception ex)
{
CombatSoundsPlugin.Log.LogWarning((object)("Couldn't read " + folder + ": " + ex.Message));
}
string text3 = (folder.StartsWith(Paths.GameRootPath, StringComparison.OrdinalIgnoreCase) ? folder.Substring(Paths.GameRootPath.Length).TrimStart('\\', '/') : folder);
_choice = config.Bind<string>("Sounds", name, (follows != null) ? same : "Default", new ConfigDescription(description + " Default is the game's own. Add your own sounds in " + text3 + ".", (AcceptableValueBase)(object)new AcceptableValueList<string>(list.ToArray()), Array.Empty<object>()));
_volume = config.Bind<int>("Sounds", name + " Volume", 100, new ConfigDescription("100 is normal, 200 is twice as loud.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
_choice.SettingChanged += delegate
{
Load(preview: true);
};
_volume.SettingChanged += delegate
{
if (!(Time.unscaledTime < _nextPreview))
{
_nextPreview = Time.unscaledTime + 0.3f;
Preview();
}
};
Load(preview: false);
}
internal bool PlayGame(AudioSource audio, AudioClip clip)
{
int value = _volume.Value;
if (value == 100 || (Object)(object)audio == (Object)null || (Object)(object)clip == (Object)null)
{
return false;
}
if (value > 0)
{
audio.PlayOneShot(clip, (float)value / 100f);
}
return true;
}
private void Preview()
{
if ((Object)(object)Pick._clip != (Object)null)
{
Play();
}
else
{
if (Pick._none)
{
return;
}
if ((Object)(object)_gameA == (Object)null)
{
Weapon[] array = Resources.FindObjectsOfTypeAll<Weapon>();
foreach (Weapon val in array)
{
if (!((Object)(object)val == (Object)null) && _kind == SoundKind.MeleeKill == val is MeleeWeapon)
{
_gameA = ((_kind == SoundKind.HeadHit) ? val.headHitClip : ((_kind == SoundKind.Hit) ? val.bodyHitClip : val.deathClip));
_gameB = ((_kind == SoundKind.HeadHit) ? val.bodyHitClip : null);
if ((Object)(object)_gameA != (Object)null)
{
break;
}
}
}
}
AudioClip gameA = _gameA;
AudioClip gameB = _gameB;
if (!((Object)(object)gameA == (Object)null))
{
if ((Object)(object)_source == (Object)null)
{
_source = NewSource();
}
float num = Mathf.Min((float)_volume.Value / 100f, 1f);
_source.Stop();
_source.PlayOneShot(gameA, num);
if ((Object)(object)gameB != (Object)null)
{
_source.PlayOneShot(gameB, num);
}
}
}
}
internal bool SameSound(SoundSlot other)
{
if (other != null)
{
return string.Equals(Pick._sound, other.Pick._sound, StringComparison.OrdinalIgnoreCase);
}
return false;
}
internal void Play()
{
AudioClip clip = Pick._clip;
if (!((Object)(object)clip == (Object)null))
{
if ((Object)(object)_source == (Object)null)
{
_source = NewSource();
}
int value = _volume.Value;
_source.clip = ((value > 100) ? Louder(clip, value) : clip);
_source.volume = ((value > 100) ? 1f : ((float)value / 100f));
_source.Play();
}
}
internal void Stop()
{
if ((Object)(object)_source != (Object)null)
{
_source.Stop();
}
}
private static AudioSource NewSource()
{
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_0024: Expected O, but got Unknown
if ((Object)(object)_speaker == (Object)null)
{
_speaker = new GameObject("CombatSounds")
{
hideFlags = (HideFlags)61
};
Object.DontDestroyOnLoad((Object)(object)_speaker);
}
AudioSource obj = _speaker.AddComponent<AudioSource>();
obj.playOnAwake = false;
obj.spatialBlend = 0f;
obj.priority = 0;
bool flag = (obj.bypassReverbZones = true);
bool bypassEffects = (obj.bypassListenerEffects = flag);
obj.bypassEffects = bypassEffects;
return obj;
}
private AudioClip Louder(AudioClip clip, int volume)
{
if (_louderVolume == volume && (Object)(object)_louderOf == (Object)(object)clip)
{
return _louder ?? clip;
}
_louderVolume = volume;
_louderOf = clip;
DropLouder();
try
{
float[] array = new float[clip.samples * clip.channels];
if (!clip.GetData(array, 0))
{
return clip;
}
float num = (float)volume / 100f;
for (int i = 0; i < array.Length; i++)
{
array[i] = Mathf.Clamp(array[i] * num, -1f, 1f);
}
_louder = AudioClip.Create(((Object)clip).name + " (louder)", clip.samples, clip.channels, clip.frequency, false);
_louder.SetData(array, 0);
return _louder;
}
catch (Exception ex)
{
CombatSoundsPlugin.Log.LogWarning((object)("Couldn't make " + ((Object)clip).name + " louder, so it plays at 100. (" + ex.Message + ")"));
DropLouder();
return clip;
}
}
private void DropLouder()
{
if ((Object)(object)_louder != (Object)null)
{
Object.Destroy((Object)(object)_louder);
}
_louder = null;
}
private void Load(bool preview)
{
//IL_0105: Unknown result type (might be due to invalid IL or missing references)
//IL_0112: Unknown result type (might be due to invalid IL or missing references)
int id = ++_loadId;
string choice = _choice.Value;
_none = choice == "None";
_following = _hit != null && choice == _same;
if ((Object)(object)_clip != (Object)null)
{
Object.Destroy((Object)(object)_clip);
}
_clip = null;
_sound = null;
DropLouder();
_louderVolume = 0;
if (!_files.TryGetValue(choice, out var file))
{
if (preview)
{
Preview();
}
return;
}
string text = Path.GetExtension(file).ToLowerInvariant();
AudioType val = (AudioType)((text == ".ogg") ? 14 : ((text == ".mp3") ? 13 : 20));
UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(new Uri(file), val);
((AsyncOperation)request.SendWebRequest()).completed += delegate
{
try
{
AudioClip val2 = (string.IsNullOrEmpty(request.error) ? DownloadHandlerAudioClip.GetContent(request) : null);
if (id != _loadId)
{
if ((Object)(object)val2 != (Object)null)
{
Object.Destroy((Object)(object)val2);
}
}
else if ((Object)(object)val2 == (Object)null || val2.samples == 0)
{
CombatSoundsPlugin.Log.LogWarning((object)("Couldn't load " + Path.GetFileName(file) + " (" + (request.error ?? "not a sound Unity can play") + "), so the game's own " + _name.ToLowerInvariant() + " plays."));
}
else
{
((Object)val2).name = choice;
_clip = val2;
_sound = choice;
if (preview)
{
Preview();
}
}
}
catch (Exception ex)
{
CombatSoundsPlugin.Log.LogWarning((object)("Couldn't load " + Path.GetFileName(file) + ": " + ex.Message));
}
finally
{
request.Dispose();
}
};
}
}
internal static class Hooks
{
private static int _frame = -1;
private static SoundSlot _hit;
private static SoundSlot _kill;
private static int _headLayerFrame = -1;
private static int _meleeKillFrame = -1;
private static bool _errorLogged;
internal static void Install(Harmony harmony)
{
//IL_0028: Unknown result type (might be due to invalid IL or missing references)
//IL_0035: Expected O, but got Unknown
//IL_005e: Unknown result type (might be due to invalid IL or missing references)
//IL_006b: Expected O, but got Unknown
//IL_0094: Unknown result type (might be due to invalid IL or missing references)
//IL_00a1: Expected O, but got Unknown
//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Expected O, but got Unknown
harmony.Patch((MethodBase)AccessTools.Method(typeof(Settings), "IncreaseBodyshotsAmount", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Hooks), "HitPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(Settings), "IncreaseHeadshotsAmount", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Hooks), "HeadHitPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(Settings), "IncreaseKillsAmount", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Hooks), "KillPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
HarmonyMethod val = new HarmonyMethod(typeof(Hooks), "GameSoundPrefix", (Type[])null);
Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Weapon).Assembly);
foreach (Type type in typesFromAssembly)
{
if (typeof(Weapon).IsAssignableFrom(type))
{
MethodInfo method = type.GetMethod("LocalSound", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[1] { typeof(int) }, null);
if (method != null)
{
harmony.Patch((MethodBase)method, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
}
}
private static void HitPostfix()
{
Play(CombatSoundsPlugin.Hit, kill: false);
}
private static void HeadHitPostfix()
{
Play(CombatSoundsPlugin.HeadHit, kill: false);
}
private static void KillPostfix()
{
Play((_meleeKillFrame == Time.frameCount) ? CombatSoundsPlugin.MeleeKill : CombatSoundsPlugin.Kill, kill: true);
}
private static void Play(SoundSlot slot, bool kill)
{
try
{
int frameCount = Time.frameCount;
if (frameCount != _frame)
{
_frame = frameCount;
_hit = (_kill = null);
}
if (kill)
{
if (_kill == null)
{
_kill = slot;
if (slot.HasSound && !slot.SameSound(_hit))
{
slot.Play();
}
}
}
else if (_hit != slot && _hit != CombatSoundsPlugin.HeadHit)
{
if (_hit != null)
{
_hit.Stop();
}
_hit = slot;
if (slot.HasSound && !slot.SameSound(_kill))
{
slot.Play();
}
}
}
catch (Exception e)
{
LogOnce(e);
}
}
private static void LogOnce(Exception e)
{
if (!_errorLogged)
{
_errorLogged = true;
CombatSoundsPlugin.Log.LogError((object)("Error (further errors are not logged): " + e));
}
}
private static bool GameSoundPrefix(Weapon __instance, int __0)
{
SoundSlot soundSlot;
AudioClip clip;
switch (__0)
{
case 0:
_headLayerFrame = Time.frameCount;
soundSlot = CombatSoundsPlugin.HeadHit;
clip = (((Object)(object)__instance != (Object)null) ? __instance.headHitClip : null);
break;
case 1:
{
bool num2 = _headLayerFrame == Time.frameCount;
_headLayerFrame = -1;
soundSlot = (num2 ? CombatSoundsPlugin.HeadHit : CombatSoundsPlugin.Hit);
clip = (((Object)(object)__instance != (Object)null) ? __instance.bodyHitClip : null);
break;
}
case 2:
{
bool num = __instance is MeleeWeapon;
if (num)
{
_meleeKillFrame = Time.frameCount;
}
soundSlot = (num ? CombatSoundsPlugin.MeleeKill : CombatSoundsPlugin.Kill);
clip = (((Object)(object)__instance != (Object)null) ? __instance.deathClip : null);
break;
}
default:
return true;
}
try
{
if (soundSlot.ReplacesGameSound)
{
return false;
}
return !soundSlot.PlayGame(((Object)(object)__instance != (Object)null) ? __instance.audio : null, clip);
}
catch (Exception e)
{
LogOnce(e);
return true;
}
}
}
internal static class GunSounds
{
private static readonly Dictionary<AudioSource, float> Noted = new Dictionary<AudioSource, float>();
private static FieldRef<SetEffectVolume, AudioSource> _effectFrom;
private static FieldRef<SetEffectVolume, AudioSource> _effectTo;
private static FieldRef<SetPlayerVolume, AudioSource> _playerFrom;
private static FieldRef<SetPlayerVolume, AudioSource> _playerTo;
private static bool _errorLogged;
private static int _pruneAt = 256;
private static readonly List<AudioSource> Gone = new List<AudioSource>();
private static float Scale => (float)CombatSoundsPlugin.GunVolume.Value / 100f;
internal static void Install(Harmony harmony)
{
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_0052: Expected O, but got Unknown
//IL_00da: Unknown result type (might be due to invalid IL or missing references)
//IL_00e7: Expected O, but got Unknown
//IL_010f: Unknown result type (might be due to invalid IL or missing references)
//IL_011d: Expected O, but got Unknown
//IL_0145: Unknown result type (might be due to invalid IL or missing references)
//IL_0153: Expected O, but got Unknown
_effectFrom = AccessTools.FieldRefAccess<SetEffectVolume, AudioSource>("source");
_effectTo = AccessTools.FieldRefAccess<SetEffectVolume, AudioSource>("audio");
_playerFrom = AccessTools.FieldRefAccess<SetPlayerVolume, AudioSource>("source");
_playerTo = AccessTools.FieldRefAccess<SetPlayerVolume, AudioSource>("audio");
HarmonyMethod val = new HarmonyMethod(typeof(GunSounds), "GunMadePostfix", (Type[])null);
Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Weapon).Assembly);
foreach (Type type in typesFromAssembly)
{
if (typeof(Weapon).IsAssignableFrom(type))
{
MethodInfo methodInfo = AccessTools.DeclaredMethod(type, "Awake___UserLogic", (Type[])null, (Type[])null);
if (methodInfo != null)
{
harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
}
}
}
harmony.Patch((MethodBase)AccessTools.Method(typeof(EjectedCaseScript), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(GunSounds), "CasingMadePostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(SetEffectVolume), "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(GunSounds), "EffectVolumePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
harmony.Patch((MethodBase)AccessTools.Method(typeof(SetPlayerVolume), "Update", (Type[])null, (Type[])null), new HarmonyMethod(typeof(GunSounds), "PlayerVolumePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
CombatSoundsPlugin.GunVolume.SettingChanged += delegate
{
ApplyAll();
};
}
private static void GunMadePostfix(Weapon __instance)
{
try
{
if ((Object)(object)__instance != (Object)null)
{
Note(__instance.audio);
}
}
catch (Exception e)
{
LogOnce(e);
}
}
private static void CasingMadePostfix(EjectedCaseScript __instance)
{
try
{
if ((Object)(object)__instance != (Object)null)
{
Note(((Component)__instance).GetComponent<AudioSource>());
}
}
catch (Exception e)
{
LogOnce(e);
}
}
private static void Note(AudioSource source)
{
if (!((Object)(object)source == (Object)null) && !Noted.ContainsKey(source))
{
if (Noted.Count >= _pruneAt)
{
Prune();
_pruneAt = Mathf.Max(256, Noted.Count * 2);
}
float volume = source.volume;
Noted[source] = volume;
source.volume = volume * Scale;
}
}
internal static void Prune()
{
foreach (AudioSource key in Noted.Keys)
{
if ((Object)(object)key == (Object)null)
{
Gone.Add(key);
}
}
foreach (AudioSource item in Gone)
{
Noted.Remove(item);
}
Gone.Clear();
}
private static void ApplyAll()
{
try
{
Prune();
float scale = Scale;
foreach (KeyValuePair<AudioSource, float> item in Noted)
{
item.Key.volume = item.Value * scale;
}
}
catch (Exception e)
{
LogOnce(e);
}
}
private static bool EffectVolumePrefix(SetEffectVolume __instance)
{
AudioSource to = _effectTo.Invoke(__instance);
AudioSource val = _effectFrom.Invoke(__instance);
return Follow(to, val);
}
private static bool PlayerVolumePrefix(SetPlayerVolume __instance)
{
AudioSource to = _playerTo.Invoke(__instance);
AudioSource val = _playerFrom.Invoke(__instance);
return Follow(to, val);
}
private static bool Follow(AudioSource to, AudioSource from)
{
if ((Object)(object)to == (Object)null || (Object)(object)from == (Object)null || !Noted.ContainsKey(to))
{
return true;
}
Noted[to] = from.volume;
float num = from.volume * Scale;
if (to.volume != num)
{
to.volume = num;
}
return false;
}
private static void LogOnce(Exception e)
{
if (!_errorLogged)
{
_errorLogged = true;
CombatSoundsPlugin.Log.LogError((object)("Gun sound volume error (further errors are not logged): " + e));
}
}
}