using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Networking;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ErenshorNpcVoice;
internal static class PluginIdentity
{
internal const string Guid = "com.github.Jhenox.erenshornpcvoice";
}
[BepInPlugin("com.github.Jhenox.erenshornpcvoice", "Erenshor NPC Voice", "0.1.2")]
public class Plugin : BaseUnityPlugin
{
private enum VoiceGender
{
Unknown,
Male,
Female
}
private enum VoiceRole
{
General,
Caster,
Martial
}
private class VoiceProfile
{
public string Name;
public VoiceGender Gender;
public readonly List<AudioClip> Clips = new List<AudioClip>();
}
private static AudioClip OriginalHailSound;
private static ConfigEntry<bool> DetailedLogging;
private static readonly List<VoiceProfile> VoiceProfiles = new List<VoiceProfile>();
private static readonly Dictionary<string, VoiceGender> GenderOverrides = new Dictionary<string, VoiceGender>(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, VoiceGender> MeshGenderOverrides = new Dictionary<string, VoiceGender>(StringComparer.OrdinalIgnoreCase)
{
{
"Character_Peasant",
VoiceGender.Male
},
{
"SM_Chr_Rider_01",
VoiceGender.Female
},
{
"SM_Chr_Nun_01",
VoiceGender.Female
},
{
"Character_Warrior",
VoiceGender.Male
},
{
"Character_Knight",
VoiceGender.Male
},
{
"SM_Chr_Monk_01",
VoiceGender.Male
},
{
"SM_Chr_Merchant_01",
VoiceGender.Male
},
{
"SM_Chr_FortuneTeller_01",
VoiceGender.Female
},
{
"SM_Chr_Bartender_01",
VoiceGender.Male
},
{
"Character_Shopkeeper",
VoiceGender.Male
},
{
"Character_Ghost_01",
VoiceGender.Male
}
};
private static readonly HashSet<string> GhostMeshOverrides = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Character_Ghost_01" };
private static readonly Dictionary<string, int> LastClipByNpc = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> UnknownGenderLogged = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> AppearanceResearchLogged = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> ProfileChoiceLogged = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private static string PluginFolder => Path.GetDirectoryName(typeof(Plugin).Assembly.Location);
private static string VoiceFolder => Path.Combine(PluginFolder, "Voices");
private static string OverrideFile => Path.Combine(PluginFolder, "NpcVoiceOverrides.txt");
internal static bool DetailedLoggingEnabled
{
get
{
if (DetailedLogging != null)
{
return DetailedLogging.Value;
}
return false;
}
}
private void Awake()
{
//IL_003b: Unknown result type (might be due to invalid IL or missing references)
((BaseUnityPlugin)this).Logger.LogInfo((object)"Erenshor NPC Voice loaded.");
DetailedLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Logging", "EnableDetailedLogging", false, "Log per-NPC mesh details, voice choices, and interaction diagnostics.");
LoadGenderOverrides();
new Harmony("com.github.Jhenox.erenshornpcvoice").PatchAll();
((MonoBehaviour)this).StartCoroutine(LoadVoiceProfiles());
((MonoBehaviour)this).StartCoroutine(SilenceOriginalHailSound());
}
private void LoadGenderOverrides()
{
Directory.CreateDirectory(PluginFolder);
if (!File.Exists(OverrideFile))
{
File.WriteAllText(OverrideFile, "# Add one NPC per line, using this format:\r\n# NPC Name=Female\r\n# NPC Name=Male\r\n");
}
string[] array = File.ReadAllLines(OverrideFile);
for (int i = 0; i < array.Length; i++)
{
string text = array[i].Trim();
if (text.Length == 0 || text.StartsWith("#"))
{
continue;
}
int num = text.IndexOf('=');
if (num >= 1)
{
string key = text.Substring(0, num).Trim();
string text2 = text.Substring(num + 1).Trim();
if (text2.Equals("Female", StringComparison.OrdinalIgnoreCase))
{
GenderOverrides[key] = VoiceGender.Female;
}
else if (text2.Equals("Male", StringComparison.OrdinalIgnoreCase))
{
GenderOverrides[key] = VoiceGender.Male;
}
}
}
}
private IEnumerator SilenceOriginalHailSound()
{
while ((Object)(object)GameData.Misc == (Object)null || (Object)(object)GameData.Misc.HailSound == (Object)null)
{
yield return null;
}
int num = 4410;
AudioClip val = AudioClip.Create("SilentHailSound", num, 1, 44100, false);
val.SetData(new float[num], 0);
OriginalHailSound = GameData.Misc.HailSound;
GameData.Misc.HailSound = val;
GameData.Misc.ReplySound = val;
((BaseUnityPlugin)this).Logger.LogInfo((object)"Disabled the game's built-in Hail sound.");
}
private IEnumerator LoadVoiceProfiles()
{
if (!Directory.Exists(VoiceFolder))
{
((BaseUnityPlugin)this).Logger.LogError((object)("Voices folder not found: " + VoiceFolder));
yield break;
}
string[] directories = Directory.GetDirectories(VoiceFolder);
Array.Sort(directories, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
string[] array = directories;
foreach (string profileFolder in array)
{
string fileName = Path.GetFileName(profileFolder);
VoiceGender folderGender = GetFolderGender(fileName);
if (folderGender == VoiceGender.Unknown)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("Skipping voice folder because its name must include 'male' or 'female': " + fileName));
continue;
}
string[] files = Directory.GetFiles(profileFolder, "*.mp3");
Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase);
VoiceProfile profile = new VoiceProfile
{
Name = fileName,
Gender = folderGender
};
string[] array2 = files;
foreach (string file in array2)
{
string absoluteUri = new Uri(file).AbsoluteUri;
UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(absoluteUri, (AudioType)13);
try
{
yield return request.SendWebRequest();
if ((int)request.result != 1)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not load " + file + ": " + request.error));
continue;
}
AudioClip content = DownloadHandlerAudioClip.GetContent(request);
if ((Object)(object)content != (Object)null)
{
((Object)content).name = Path.GetFileNameWithoutExtension(file);
profile.Clips.Add(content);
}
}
finally
{
((IDisposable)request)?.Dispose();
}
}
if (profile.Clips.Count > 0)
{
VoiceProfiles.Add(profile);
LogDebug("Loaded voice profile " + profile.Name + " with " + profile.Clips.Count + " clips.");
}
else
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("No MP3 clips found in voice folder: " + profileFolder));
}
}
((BaseUnityPlugin)this).Logger.LogInfo((object)("Loaded " + VoiceProfiles.Count + " NPC voice profiles."));
}
internal static void LogDebug(string message)
{
if (DetailedLoggingEnabled)
{
Debug.Log((object)("[Erenshor NPC Voice] " + message));
}
}
private static VoiceGender GetFolderGender(string folderName)
{
string text = folderName.ToLowerInvariant();
if (text.Contains("female"))
{
return VoiceGender.Female;
}
if (text.Contains("male"))
{
return VoiceGender.Male;
}
return VoiceGender.Unknown;
}
internal static void PlayNpcVoice(NPC npc)
{
if ((Object)(object)npc == (Object)null)
{
return;
}
if (VoiceProfiles.Count == 0)
{
PlayOriginalHailSound();
return;
}
List<string> appearanceNames = GetAppearanceNames(npc);
VoiceGender npcGender = GetNpcGender(npc, appearanceNames);
VoiceRole npcRole = GetNpcRole(npc, appearanceNames);
if (DetailedLoggingEnabled && AppearanceResearchLogged.Add(npc.NPCName))
{
LogAppearanceResearch(npc, npcGender, npcRole, appearanceNames);
}
if (npcGender == VoiceGender.Unknown)
{
LogUnknownGender(npc, appearanceNames);
PlayOriginalHailSound();
return;
}
VoiceProfile voiceProfile = ChooseVoiceProfile(npc, npcGender, npcRole);
if (voiceProfile == null || voiceProfile.Clips.Count == 0)
{
return;
}
if (DetailedLoggingEnabled && ProfileChoiceLogged.Add(npc.NPCName))
{
LogDebug("Selected profile '" + voiceProfile.Name + "' for " + npc.NPCName + " (voice presentation=" + npcGender.ToString() + ", role=" + npcRole.ToString() + ")");
}
AudioClip randomClipForNpc = GetRandomClipForNpc(npc, voiceProfile);
if (!((Object)(object)randomClipForNpc == (Object)null))
{
NpcVoiceAudioSource npcVoiceAudioSource = ((Component)npc).GetComponent<NpcVoiceAudioSource>();
if ((Object)(object)npcVoiceAudioSource == (Object)null)
{
npcVoiceAudioSource = ((Component)npc).gameObject.AddComponent<NpcVoiceAudioSource>();
}
bool flag = IsGhostModel(appearanceNames);
if ((Object)(object)npcVoiceAudioSource.Reverb != (Object)null)
{
((Behaviour)npcVoiceAudioSource.Reverb).enabled = flag;
}
if ((Object)(object)npcVoiceAudioSource.Echo != (Object)null)
{
((Behaviour)npcVoiceAudioSource.Echo).enabled = flag;
}
if ((Object)(object)npcVoiceAudioSource.Source != (Object)null)
{
npcVoiceAudioSource.Source.pitch = (flag ? 0.92f : 1f);
npcVoiceAudioSource.Source.PlayOneShot(randomClipForNpc, GameData.SFXVol * GameData.MasterVol * 0.15f);
}
}
}
private static VoiceProfile ChooseVoiceProfile(NPC npc, VoiceGender gender, VoiceRole role)
{
List<VoiceProfile> list = new List<VoiceProfile>();
foreach (VoiceProfile voiceProfile in VoiceProfiles)
{
if (gender == VoiceGender.Unknown || voiceProfile.Gender == gender)
{
list.Add(voiceProfile);
}
}
if (list.Count == 0)
{
list.AddRange(VoiceProfiles);
}
List<VoiceProfile> list2 = new List<VoiceProfile>();
foreach (VoiceProfile item in list)
{
if (MatchesRoleStyle(item.Name, role))
{
list2.Add(item);
}
}
List<VoiceProfile> list3 = ((list2.Count > 0) ? list2 : list);
int index = StableHash(npc.NPCName + "|" + gender.ToString() + "|" + role) % list3.Count;
return list3[index];
}
private static bool MatchesRoleStyle(string profileName, VoiceRole role)
{
string text = profileName.ToLowerInvariant();
return role switch
{
VoiceRole.General => true,
VoiceRole.Caster => ContainsAny(text, "clear", "gentle", "soft", "smooth", "informative", "knowledgeable", "even", "warm", "mature", "breathy"),
VoiceRole.Martial => ContainsAny(text, "firm", "gravelly", "forward", "lively", "excitable", "upbeat", "bright", "casual"),
_ => true,
};
}
private static VoiceGender GetNpcGender(NPC npc, List<string> appearanceNames)
{
if (GenderOverrides.TryGetValue(npc.NPCName, out var value))
{
return value;
}
foreach (string appearanceName in appearanceNames)
{
if (MeshGenderOverrides.TryGetValue(appearanceName.Trim(), out var value2))
{
return value2;
}
}
bool flag = false;
bool flag2 = false;
foreach (string appearanceName2 in appearanceNames)
{
string text = appearanceName2.ToLowerInvariant();
if (text.Contains("_female"))
{
flag2 = true;
}
else if (text.Contains("_male"))
{
flag = true;
}
}
if (flag2 && !flag)
{
return VoiceGender.Female;
}
if (flag && !flag2)
{
return VoiceGender.Male;
}
return VoiceGender.Unknown;
}
private static bool IsGhostModel(List<string> appearanceNames)
{
foreach (string appearanceName in appearanceNames)
{
if (GhostMeshOverrides.Contains(appearanceName.Trim()))
{
return true;
}
}
return false;
}
private static VoiceRole GetNpcRole(NPC npc, List<string> appearanceNames)
{
Stats component = ((Component)npc).GetComponent<Stats>();
if ((Object)(object)component != (Object)null && (Object)(object)component.CharacterClass != (Object)null)
{
string text = component.CharacterClass.ClassName.ToLowerInvariant();
if (ContainsAny(text, "arcanist", "druid", "stormcaller"))
{
return VoiceRole.Caster;
}
if (ContainsAny(text, "duelist", "paladin", "reaver"))
{
return VoiceRole.Martial;
}
}
string text2 = npc.NPCName.ToLowerInvariant();
foreach (string appearanceName in appearanceNames)
{
text2 = text2 + " " + appearanceName.ToLowerInvariant();
}
if (ContainsAny(text2, "mage", "wizard", "sorcer", "arcanist", "druid", "stormcaller", "priest", "nun", "fortune teller", "cleric"))
{
return VoiceRole.Caster;
}
if (ContainsAny(text2, "warrior", "soldier", "guard", "knight", "duelist", "paladin", "reaver", "fighter", "sergeant", "headsman", "monk"))
{
return VoiceRole.Martial;
}
return VoiceRole.General;
}
private static List<string> GetAppearanceNames(NPC npc)
{
List<string> list = new List<string>();
Component[] componentsInChildren = ((Component)npc).GetComponentsInChildren<Component>(true);
SkinnedMeshRenderer[] array2;
foreach (Component val in componentsInChildren)
{
if ((Object)(object)val == (Object)null || ((object)val).GetType().FullName != "MTAssets.SkinnedMeshCombiner.CombinedMeshesManager")
{
continue;
}
FieldInfo fieldInfo = AccessTools.Field(((object)val).GetType(), "sourceMeshes");
if (fieldInfo == null || !(fieldInfo.GetValue(val) is SkinnedMeshRenderer[] array))
{
continue;
}
array2 = array;
foreach (SkinnedMeshRenderer val2 in array2)
{
if (!((Object)(object)val2 == (Object)null))
{
AddName(list, ((Object)val2).name);
if ((Object)(object)val2.sharedMesh != (Object)null)
{
AddName(list, ((Object)val2.sharedMesh).name);
}
}
}
}
array2 = ((Component)npc).GetComponentsInChildren<SkinnedMeshRenderer>(true);
foreach (SkinnedMeshRenderer val3 in array2)
{
if (!((Object)(object)val3 == (Object)null) && ((Renderer)val3).enabled && ((Component)val3).gameObject.activeInHierarchy)
{
AddName(list, ((Object)val3).name);
if ((Object)(object)val3.sharedMesh != (Object)null)
{
AddName(list, ((Object)val3.sharedMesh).name);
}
}
}
return list;
}
private static void AddName(List<string> names, string name)
{
if (!string.IsNullOrEmpty(name) && !names.Contains(name))
{
names.Add(name);
}
}
private static void LogUnknownGender(NPC npc, List<string> appearanceNames)
{
if (DetailedLoggingEnabled && UnknownGenderLogged.Add(npc.NPCName))
{
string text = ((appearanceNames.Count > 0) ? string.Join(", ", appearanceNames.ToArray()) : "(no mesh names found)");
LogDebug("Could not determine voice presentation for NPC '" + npc.NPCName + "'. Add an override in " + OverrideFile + ". Model details: " + text);
}
}
private static void LogAppearanceResearch(NPC npc, VoiceGender gender, VoiceRole role, List<string> appearanceNames)
{
Stats component = ((Component)npc).GetComponent<Stats>();
string text = "(none)";
if ((Object)(object)component != (Object)null && (Object)(object)component.CharacterClass != (Object)null)
{
text = component.CharacterClass.ClassName;
}
string text2 = ((appearanceNames.Count > 0) ? string.Join(", ", appearanceNames.ToArray()) : "(no mesh names found)");
LogDebug("Appearance research: NPC='" + npc.NPCName + "', Gender=" + gender.ToString() + ", Class=" + text + ", Role=" + role.ToString() + ", Meshes=[" + text2 + "]");
}
private static AudioClip GetRandomClipForNpc(NPC npc, VoiceProfile profile)
{
int count = profile.Clips.Count;
if (count == 0)
{
return null;
}
string nPCName = npc.NPCName;
int num = Random.Range(0, count);
if (count > 1 && LastClipByNpc.TryGetValue(nPCName, out var value) && num == value)
{
num = (num + Random.Range(1, count)) % count;
}
LastClipByNpc[nPCName] = num;
return profile.Clips[num];
}
private static bool ContainsAny(string text, params string[] values)
{
foreach (string value in values)
{
if (text.Contains(value))
{
return true;
}
}
return false;
}
private static int StableHash(string text)
{
uint num = 2166136261u;
foreach (char c in text)
{
num ^= c;
num *= 16777619;
}
return (int)(num & 0x7FFFFFFF);
}
private static void PlayOriginalHailSound()
{
if (!((Object)(object)OriginalHailSound == (Object)null) && !((Object)(object)GameData.PlayerAud == (Object)null))
{
GameData.PlayerAud.PlayOneShot(OriginalHailSound, GameData.PlayerAud.volume * 0.5f * GameData.SFXVol * GameData.MasterVol);
}
}
}
[HarmonyPatch(typeof(NPCDialogManager), "GenericHail")]
internal static class GenericHailPatch
{
private static void Postfix(NPCDialogManager __instance)
{
Plugin.LogDebug("GenericHail patch fired on " + (((Object)(object)__instance != (Object)null) ? ((Object)((Component)__instance).gameObject).name : "(null manager)"));
if (!((Object)(object)__instance == (Object)null))
{
NPC val = ((Component)__instance).GetComponent<NPC>();
if ((Object)(object)val == (Object)null)
{
val = ((Component)__instance).GetComponentInParent<NPC>();
}
if ((Object)(object)val == (Object)null)
{
val = ((Component)__instance).GetComponentInChildren<NPC>(true);
}
if ((Object)(object)val == (Object)null)
{
Debug.LogWarning((object)("[Erenshor NPC Voice] GenericHail ran, but no NPC component was found on or near " + ((Object)((Component)__instance).gameObject).name));
return;
}
Plugin.LogDebug("Found NPC=" + val.NPCName + ", SimPlayer=" + val.SimPlayer);
Plugin.PlayNpcVoice(val);
}
}
}
public class NpcVoiceAudioSource : MonoBehaviour
{
public AudioSource Source { get; private set; }
public AudioReverbFilter Reverb { get; private set; }
public AudioEchoFilter Echo { get; private set; }
private void Awake()
{
Source = ((Component)this).gameObject.AddComponent<AudioSource>();
Source.playOnAwake = false;
Source.spatialBlend = 1f;
Source.volume = 1f;
Source.minDistance = 3f;
Source.maxDistance = 25f;
Source.rolloffMode = (AudioRolloffMode)1;
Reverb = ((Component)this).gameObject.AddComponent<AudioReverbFilter>();
Reverb.reverbPreset = (AudioReverbPreset)9;
((Behaviour)Reverb).enabled = false;
Echo = ((Component)this).gameObject.AddComponent<AudioEchoFilter>();
Echo.delay = 140f;
Echo.decayRatio = 0.12f;
Echo.dryMix = 1f;
Echo.wetMix = 0.08f;
((Behaviour)Echo).enabled = false;
}
}
[HarmonyPatch(typeof(TypeText), "Update")]
internal static class SimPlayerHailPatch
{
private static void Prefix(out bool __state)
{
__state = IsHailInput();
}
private static void Postfix(bool __state)
{
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_0052: Unknown result type (might be due to invalid IL or missing references)
if (!__state || (Object)(object)GameData.PlayerControl == (Object)null || (Object)(object)GameData.PlayerControl.CurrentTarget == (Object)null)
{
return;
}
Character currentTarget = GameData.PlayerControl.CurrentTarget;
if (!((Object)(object)((Component)currentTarget).GetComponent<NPCDialogManager>() != (Object)null) && !(Vector3.Distance(((Component)GameData.PlayerControl).transform.position, ((Component)currentTarget).transform.position) >= 5f) && !((Object)(object)((Component)currentTarget).GetComponent<SimPlayer>() == (Object)null))
{
NPC component = ((Component)currentTarget).GetComponent<NPC>();
if ((Object)(object)component == (Object)null)
{
Debug.LogWarning((object)("[Erenshor NPC Voice] SimPlayer hail target has no NPC component: " + ((Object)currentTarget).name));
return;
}
Plugin.LogDebug("Playing voice for hailed SimPlayer: " + component.NPCName);
Plugin.PlayNpcVoice(component);
}
}
private static bool IsHailInput()
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
if (GameData.PlayerTyping || (Object)(object)GameData.PlayerControl == (Object)null)
{
return false;
}
bool keyDown = Input.GetKeyDown(InputManager.Greeting);
bool flag = GameData.PlayerControl.usingGamepad && Input.GetKeyDown((KeyCode)331) && (Object)(object)GameData.HighlightedItem == (Object)null && !Input.GetKey((KeyCode)334);
if (keyDown || flag)
{
return Input.GetAxis("RTrigger") < 0.1f;
}
return false;
}
}
[HarmonyPatch(typeof(NPCDialogManager), "ParseText")]
internal static class KeywordResponsePatch
{
private static void Postfix(NPCDialogManager __instance, string __0)
{
if ((Object)(object)__instance == (Object)null || string.IsNullOrEmpty(__0))
{
return;
}
NPC component = ((Component)__instance).GetComponent<NPC>();
if ((Object)(object)component == (Object)null || (Object)(object)component.CurrentAggroTarget != (Object)null)
{
return;
}
NPCDialog[] myDialogOptions = __instance.MyDialogOptions;
if (myDialogOptions == null)
{
return;
}
string text = __0.ToLowerInvariant();
NPCDialog[] array = myDialogOptions;
foreach (NPCDialog val in array)
{
if ((Object)(object)val == (Object)null || val.KeywordToActivate == null || ((Object)(object)val.RequireQuestComplete != (Object)null && !GameData.CompletedQuests.Contains(val.RequireQuestComplete.DBName)))
{
continue;
}
foreach (string item in val.KeywordToActivate)
{
if (!string.IsNullOrEmpty(item) && text.Contains(item.ToLowerInvariant()))
{
Plugin.LogDebug("Keyword response for " + component.NPCName + ": " + item);
Plugin.PlayNpcVoice(component);
return;
}
}
}
}
}