Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of RuneheimMusic v1.1.4
plugins/RuneheimMusic.dll
Decompiled a day agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using RuneheimCore; using UnityEngine; using UnityEngine.Networking; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8.1", FrameworkDisplayName = ".NET Framework 4.8.1")] [assembly: AssemblyCompany("Daytreee")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2026 Daytreee. All rights reserved. Not open source: no reuse, decompiling or redistribution without permission.")] [assembly: AssemblyFileVersion("1.1.4.0")] [assembly: AssemblyInformationalVersion("1.1.4+39cf10375f7cfabc6a2046bb143ff48a53fbce63")] [assembly: AssemblyProduct("Runeheim Music")] [assembly: AssemblyTitle("RuneheimMusic")] [assembly: AssemblyVersion("1.1.4.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; } } } internal static class RhSafe { private static class Holder<F> { public static F Value; } private static ManualLogSource _log; private static readonly HashSet<string> _said = new HashSet<string>(); private const int MaxReports = 300; private static ManualLogSource Log { get { if (_log == null) { _log = Logger.CreateLogSource(typeof(RhSafe).Assembly.GetName().Name + " (checks)"); } return _log; } } private static void Warn(string key, string text) { try { lock (_said) { if (_said.Count >= 300 || !_said.Add(key)) { return; } } Log.LogWarning((object)text); } catch { } } private static string Where(string file, int line) { return Path.GetFileName(file) + ":" + line; } public static void Swallowed(Exception e, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0, [CallerMemberName] string member = "") { string text = Where(file, line); object obj; if (e == null) { obj = null; } else { string? stackTrace = e.StackTrace; obj = ((stackTrace == null) ? null : stackTrace.Split(new char[1] { '\n' })[0]?.Trim()); } if (obj == null) { obj = ""; } string text2 = (string)obj; Warn("catch " + text, "Handled error in " + member + " (" + text + "): " + e?.GetType().Name + ": " + e?.Message + " " + text2); } private static ref F Dummy<T, F>(T instance) { return ref Holder<F>.Value; } private static ref F DummyStatic<F>() { return ref Holder<F>.Value; } public static FieldRef<T, F> FieldRef<T, F>(string name, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { try { return AccessTools.FieldRefAccess<T, F>(name); } catch (Exception ex) { Warn("field " + typeof(T).FullName + "." + name, typeof(T).Name + "." + name + " (as " + typeof(F).Name + ") can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off."); return Dummy<T, F>; } } public static FieldRef<T, F> FieldRef<T, F>(FieldInfo field, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { try { if (field != null) { return AccessTools.FieldRefAccess<T, F>(field); } } catch (Exception ex) { Warn("field " + field?.DeclaringType?.FullName + "." + field?.Name, field?.DeclaringType?.Name + "." + field?.Name + " can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off."); return Dummy<T, F>; } Warn("field null " + Where(file, line), "A field looked up at " + Where(file, line) + " wasn't found. What uses it is switched off."); return Dummy<T, F>; } public static FieldRef<F> StaticFieldRef<F>(Type type, string name, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { try { FieldInfo fieldInfo = ((type != null) ? AccessTools.Field(type, name) : null); if (fieldInfo != null) { return AccessTools.StaticFieldRefAccess<F>(fieldInfo); } Warn("static " + type?.FullName + "." + name, type?.Name + "." + name + " wasn't found (" + Where(file, line) + "). What uses it is switched off."); } catch (Exception ex) { Warn("static " + type?.FullName + "." + name, type?.Name + "." + name + " (as " + typeof(F).Name + ") can't be read (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off."); } return DummyStatic<F>; } public static D MethodDelegate<D>(MethodInfo method, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) where D : Delegate { try { if (method != null) { return AccessTools.MethodDelegate<D>(method, (object)null, true); } Warn("method null " + Where(file, line), "A method looked up at " + Where(file, line) + " wasn't found. What uses it is switched off."); } catch (Exception ex) { Warn("method " + method?.DeclaringType?.FullName + "." + method?.Name, method?.DeclaringType?.Name + "." + method?.Name + " can't be called (" + Where(file, line) + "): " + ex.GetBaseException().Message + ". What uses it is switched off."); } return null; } } namespace RuneheimMusic { public static class Library { public enum Group { Story, Day, Biomes, Fights, Places, Bosses } private static readonly Dictionary<string, Group> Groups = new Dictionary<string, Group> { ["menu"] = Group.Story, ["intro"] = Group.Story, ["credits"] = Group.Story, ["morning"] = Group.Day, ["evening"] = Group.Day, ["meadows"] = Group.Biomes, ["blackforest"] = Group.Biomes, ["swamp"] = Group.Biomes, ["mountain"] = Group.Biomes, ["plains"] = Group.Biomes, ["mistlands"] = Group.Biomes, ["ashlands"] = Group.Biomes, ["sailing"] = Group.Biomes, ["ocean"] = Group.Biomes, ["sailing_ashlands"] = Group.Biomes, ["home"] = Group.Biomes, ["combat"] = Group.Fights, ["CombatEventL1"] = Group.Fights, ["CombatEventL2"] = Group.Fights, ["CombatEventL3"] = Group.Fights, ["CombatEventL4"] = Group.Fights, ["forestcrypt"] = Group.Places, ["frostcaves"] = Group.Places, ["forestcrypthildir"] = Group.Places, ["frostcaveshildir"] = Group.Places, ["plainstower"] = Group.Places, ["location_forest"] = Group.Places, ["location_haldor"] = Group.Places, ["location_dvergrtower"] = Group.Places, ["location_dvergrexc"] = Group.Places, ["location_ashlands_ruins"] = Group.Places, ["boss_eikthyr"] = Group.Bosses, ["boss_gdking"] = Group.Bosses, ["boss_bonemass"] = Group.Bosses, ["boss_moder"] = Group.Bosses, ["boss_goblinking"] = Group.Bosses, ["boss_queen"] = Group.Bosses, ["boss_queen_ambience"] = Group.Bosses, ["boss_fader"] = Group.Bosses }; private static readonly Dictionary<string, string> SameAs = new Dictionary<string, string> { ["ocean"] = "sailing" }; private static readonly HashSet<string> Calm = new HashSet<string> { "morning", "evening", "meadows", "blackforest", "swamp", "mountain", "plains", "mistlands", "ashlands", "deepnorth", "home", "sailing", "ocean", "sailing_ashlands" }; private static string dir; private static readonly Dictionary<string, List<string>> files = new Dictionary<string, List<string>>(); private static readonly Dictionary<string, string> chosen = new Dictionary<string, string>(); private static readonly Dictionary<string, AudioClip> loaded = new Dictionary<string, AudioClip>(); private static readonly HashSet<string> loading = new HashSet<string>(); private static readonly HashSet<string> failed = new HashSet<string>(); private static readonly Dictionary<string, float> gains = new Dictionary<string, float>(); public static int Count => files.Count; public static string Folder => dir; public static IEnumerable<string> Names { get { foreach (string key in files.Keys) { yield return key; } foreach (KeyValuePair<string, string> sameA in SameAs) { if (files.ContainsKey(sameA.Value)) { yield return sameA.Key; } } } } public static string PresetFolder(Plugin.Soundtrack s) { return s switch { Plugin.Soundtrack.Vanilla => "Valheim", Plugin.Soundtrack.Custom => "Custom", Plugin.Soundtrack.RuneheimI => "Runeheim I", _ => "Runeheim II", }; } public static void Init(string musicRoot, Plugin.Soundtrack preset) { files.Clear(); chosen.Clear(); gains.Clear(); failed.Clear(); foreach (AudioClip value2 in loaded.Values) { if ((Object)(object)value2 != (Object)null) { Object.Destroy((Object)(object)value2); } } loaded.Clear(); if (preset == Plugin.Soundtrack.Vanilla) { dir = null; Plugin.Log.LogInfo((object)"Soundtrack: Valheim's own music"); return; } dir = Path.Combine(musicRoot, PresetFolder(preset)); if (preset == Plugin.Soundtrack.Custom && !Directory.Exists(dir)) { try { Directory.CreateDirectory(dir); } catch (Exception e) { RhSafe.Swallowed(e, "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Library.cs", 65, "Init"); } } if (!HasSongs(dir) && preset == Plugin.Soundtrack.RuneheimII) { if (HasSongs(musicRoot)) { dir = musicRoot; } else if (HasSongs(Path.GetDirectoryName(musicRoot))) { dir = Path.GetDirectoryName(musicRoot); } } if (!Directory.Exists(dir)) { Plugin.Log.LogWarning((object)("No music folder at " + dir)); return; } string[] array = Directory.GetFiles(dir); foreach (string text in array) { switch (Path.GetExtension(text).ToLowerInvariant()) { case ".mp3": case ".ogg": case ".wav": if (!Path.GetFileName(text).StartsWith("RuneheimMusic")) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); Match match = Regex.Match(fileNameWithoutExtension, "^(.+)_([2-9])$"); string key = (match.Success ? match.Groups[1].Value : fileNameWithoutExtension); if (!files.TryGetValue(key, out var value)) { value = (files[key] = new List<string>()); } if (match.Success) { value.Add(text); } else { value.Insert(0, text); } } break; } } ReadLevels(Path.Combine(dir, "levels.json"), null); int count = files.Count; if (preset == Plugin.Soundtrack.RuneheimII) { string text2 = Path.Combine(musicRoot, PresetFolder(Plugin.Soundtrack.RuneheimI)); HashSet<string> hashSet = new HashSet<string>(); if (Directory.Exists(text2)) { array = Directory.GetFiles(text2); foreach (string text3 in array) { switch (Path.GetExtension(text3).ToLowerInvariant()) { case ".mp3": case ".ogg": case ".wav": { string fileNameWithoutExtension2 = Path.GetFileNameWithoutExtension(text3); if (!Regex.IsMatch(fileNameWithoutExtension2, "_[2-9]$") && !files.ContainsKey(fileNameWithoutExtension2)) { files[fileNameWithoutExtension2] = new List<string> { text3 }; hashSet.Add(fileNameWithoutExtension2); } break; } } } } ReadLevels(Path.Combine(text2, "levels.json"), hashSet); } Plugin.Log.LogInfo((object)($"Soundtrack '{PresetFolder(preset)}': {count} songs" + ((files.Count > count) ? $", {files.Count - count} more from Runeheim I" : ""))); } private static bool HasSongs(string d) { if (!Directory.Exists(d)) { return false; } string[] array = Directory.GetFiles(d); for (int i = 0; i < array.Length; i++) { switch (Path.GetExtension(array[i]).ToLowerInvariant()) { case ".mp3": case ".ogg": case ".wav": return true; } } return false; } public static void Reroll(string name) { string text = FileKey(name); if (text != null && files.TryGetValue(text, out var value) && value.Count >= 2) { chosen[text] = value[Random.Range(0, value.Count)]; } } private static string PathOf(string key) { if (!files.TryGetValue(key, out var value) || value.Count == 0) { return null; } if (!chosen.TryGetValue(key, out var value2) || !value.Contains(value2)) { value2 = (chosen[key] = value[Random.Range(0, value.Count)]); } return value2; } private static void ReadLevels(string path, HashSet<string> only) { if (!File.Exists(path)) { return; } try { string text = File.ReadAllText(path); int num = text.IndexOf("\"gain\""); if (num < 0) { return; } foreach (Match item in Regex.Matches(text.Substring(num), "\"([^\"]+)\"\\s*:\\s*([0-9.]+)")) { if (only == null || only.Contains(item.Groups[1].Value)) { gains[item.Groups[1].Value] = float.Parse(item.Groups[2].Value, CultureInfo.InvariantCulture); } } } catch (Exception ex) { Plugin.Log.LogWarning((object)("levels.json: " + ex.Message)); } } public static bool IsCalm(string name) { if (name != null) { return Calm.Contains(name); } return false; } private static string FileKey(string name) { if (name == null || !SameAs.TryGetValue(name, out var value)) { return name; } return value; } public static bool Covers(string name) { if (!Plugin.Enabled.Value || name == null || !files.ContainsKey(FileKey(name))) { return false; } if (!Groups.TryGetValue(name, out var value)) { return true; } return value switch { Group.Story => Plugin.GroupStory.Value, Group.Day => Plugin.GroupDay.Value, Group.Biomes => Plugin.GroupBiomes.Value, Group.Fights => Plugin.GroupFights.Value, Group.Places => Plugin.GroupPlaces.Value, _ => Plugin.GroupBosses.Value, }; } public static float Gain(string name) { string text = PathOf(FileKey(name) ?? ""); if (text == null || !gains.TryGetValue(Path.GetFileNameWithoutExtension(text), out var value)) { return 1f; } return value; } public static AudioClip Get(string name) { string text = FileKey(name); if (text == null || !Covers(name)) { return null; } string text2 = PathOf(text); if (text2 == null) { return null; } if (loaded.TryGetValue(text2, out var value) && (Object)(object)value != (Object)null) { return value; } if (!failed.Contains(text2) && loading.Add(text2)) { ((MonoBehaviour)Plugin.Instance).StartCoroutine(Load(text2, text2)); } return null; } public static bool Loading(string name) { string text = PathOf(FileKey(name) ?? ""); if (text != null) { return loading.Contains(text); } return false; } public static void Warm(string name) { if (Covers(name)) { Get(name); } } private static IEnumerator Load(string key, string path) { string text = Path.GetExtension(path).ToLowerInvariant(); AudioType val = (AudioType)((text == ".ogg") ? 14 : ((text == ".wav") ? 20 : 13)); UnityWebRequest req = UnityWebRequestMultimedia.GetAudioClip(new Uri(path).AbsoluteUri, val); try { DownloadHandlerAudioClip dh = (DownloadHandlerAudioClip)req.downloadHandler; dh.compressed = true; dh.streamAudio = false; yield return req.SendWebRequest(); loading.Remove(key); if ((int)req.result != 1) { failed.Add(key); Plugin.Log.LogWarning((object)("Couldn't load " + path + ": " + req.error)); yield break; } AudioClip audioClip = dh.audioClip; if ((Object)(object)audioClip == (Object)null) { failed.Add(key); Plugin.Log.LogWarning((object)("Couldn't read " + path)); yield break; } ((Object)audioClip).name = "Runeheim " + Path.GetFileNameWithoutExtension(key); loaded[key] = audioClip; } finally { ((IDisposable)req)?.Dispose(); } } } public static class MusicSettings { public static void Register(ConfigFile cfg) { Page obj = RhSettings.AddPage("rm_music", "Runeheim Music", "Mods", 120); Func<bool> func = () => Plugin.Enabled.Value; Func<bool> func2 = () => Plugin.Smooth.Value; obj.Info("A new soundtrack for every Valheim music slot. Valheim still decides what plays and when; your music volume slider applies as usual."); obj.Toggle(Plugin.Enabled, "Runeheim soundtrack", "Off: Valheim's own music.", (Func<bool>)null, false); obj.Choice<Plugin.Soundtrack>(Plugin.Preset, "Soundtrack preset", "Runeheim II: the dark Nordic soundtrack (default). Runeheim I: the first soundtrack. Custom: your own songs in the mod's music/Custom folder, named like the Runeheim ones (meadows.mp3; meadows_2.mp3 adds another version). Valheim: the game's own music.", (Func<Plugin.Soundtrack, string>)((Plugin.Soundtrack v) => v switch { Plugin.Soundtrack.Custom => "Custom", Plugin.Soundtrack.RuneheimI => "Runeheim I", Plugin.Soundtrack.RuneheimII => "Runeheim II", _ => "Valheim", }), (Func<Plugin.Soundtrack, string>)null, func); obj.Slider(Plugin.Level, "Soundtrack volume", (string)null, 20f, 150f, (Func<float, string>)((float v) => $"{v:0}%"), func, true, false); obj.Section("Songs"); obj.Toggle(Plugin.GroupStory, "Menu, intro and credits", (string)null, func, true); obj.Toggle(Plugin.GroupDay, "Morning and evening", (string)null, func, true); obj.Toggle(Plugin.GroupBiomes, "Biomes, base and sailing", (string)null, func, true); obj.Toggle(Plugin.GroupFights, "Combat and raids", (string)null, func, true); obj.Toggle(Plugin.GroupPlaces, "Dungeons and places", (string)null, func, true); obj.Toggle(Plugin.GroupBosses, "Bosses", (string)null, func, true); obj.Toggle(Plugin.CombatMusic, "Combat music", "Plays the combat song while enemies are fighting you.", (Func<bool>)null, false); obj.Slider(Plugin.CombatLinger, "Combat music lingers", (string)null, 4f, 60f, (Func<float, string>)S, (Func<bool>)(() => Plugin.CombatMusic.Value), true, false); obj.Section("Playback"); obj.Toggle(Plugin.Smooth, "Smooth playback", "One song at a time, every start and stop faded. Off: Valheim's own playback.", (Func<bool>)null, false); obj.Slider(Plugin.FadeIn, "Fade-in", (string)null, 0.5f, 12f, (Func<float, string>)S, func2, true, false); obj.Slider(Plugin.CalmFade, "Calm fade-out", (string)null, 1f, 15f, (Func<float, string>)S, func2, true, false); obj.Slider(Plugin.UrgentFade, "Fight fade-out", (string)null, 0.5f, 6f, (Func<float, string>)S, func2, true, false); obj.Slider(Plugin.EndFade, "Ending fade", (string)null, 0f, 15f, (Func<float, string>)S, func2, true, false); obj.Toggle(Plugin.LetCalmFinish, "Let calm songs finish", (string)null, func2, true); obj.Slider(Plugin.FinishWindow, "Finish if this close to the end", (string)null, 10f, 180f, (Func<float, string>)S, (Func<bool>)(() => Plugin.Smooth.Value && Plugin.LetCalmFinish.Value), true, false); obj.Toggle(Plugin.Resume, "Resume interrupted songs", (string)null, func2, true); obj.Slider(Plugin.ResumeWindow, "Remember for", (string)null, 30f, 900f, (Func<float, string>)S, (Func<bool>)(() => Plugin.Smooth.Value && Plugin.Resume.Value), true, false); obj.Slider(Plugin.PauseMin, "Quiet between songs (min)", "Only with Valheim's 'Continuous music' off.", 0f, 900f, (Func<float, string>)S, func, true, false); obj.Slider(Plugin.PauseMax, "Quiet between songs (max)", (string)null, 0f, 1200f, (Func<float, string>)S, func, true, false); static string S(float v) { return $"{v:0.#} s"; } } } [HarmonyPatch] public static class Playback { private static readonly FieldRef<MusicMan, NamedMusic> Queued = RhSafe.FieldRef<MusicMan, NamedMusic>("m_queuedMusic", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 23); private static readonly FieldRef<MusicMan, NamedMusic> Current = RhSafe.FieldRef<MusicMan, NamedMusic>("m_currentMusic", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 24); private static readonly FieldRef<MusicMan, bool> Stopping = RhSafe.FieldRef<MusicMan, bool>("m_stopMusic", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 25); private static readonly FieldRef<MusicMan, AudioSource> Source = RhSafe.FieldRef<MusicMan, AudioSource>("m_musicSource", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 26); private static readonly FieldRef<MusicMan, float> VanillaVol = RhSafe.FieldRef<MusicMan, float>("m_currentMusicVol", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 27); private static readonly FieldRef<MusicMan, float> VanillaMusicVol = RhSafe.FieldRef<MusicMan, float>("m_musicVolume", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 28); private static readonly FieldRef<MusicMan, float> CombatTimer = RhSafe.FieldRef<MusicMan, float>("m_combatTimer", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Playback.cs", 29); private static readonly MethodInfo StopMethod = AccessTools.Method(typeof(MusicMan), "StopMusic", (Type[])null, (Type[])null); private static float level; private static float fadeInTime = 4f; private static float gain = 1f; private static float waitSince = -1f; private static float gapUntil; private static bool forceChange; private static float lastFight = -999f; private static NamedMusic combat; private static readonly Dictionary<NamedMusic, (AudioClip clip, float pos, float when)> saved = new Dictionary<NamedMusic, (AudioClip, float, float)>(); private static AudioClip[] swappedClips; private static NamedMusic rolledFor; private static bool Smooth => Plugin.Smooth.Value; public static void Refresh() { forceChange = true; } [HarmonyPatch(typeof(MusicMan), "UpdateMusic")] [HarmonyPrefix] [HarmonyPriority(600)] private static bool UpdateMusic(MusicMan __instance, float dt, ref NamedMusic __state) { __state = null; if (Plugin.Enabled.Value) { __instance.m_randomMusicIntervalMin = Mathf.Min(Plugin.PauseMin.Value, Plugin.PauseMax.Value); __instance.m_randomMusicIntervalMax = Mathf.Max(Plugin.PauseMin.Value, Plugin.PauseMax.Value); } if (Queued.Invoke(__instance) != null) { Library.Warm(Queued.Invoke(__instance).m_name); } if (!Smooth) { NamedMusic val = Queued.Invoke(__instance); AudioClip val2 = ((val != null) ? Library.Get(val.m_name) : null); if ((Object)(object)val2 != (Object)null) { __state = val; swappedClips = val.m_clips; val.m_clips = (AudioClip[])(object)new AudioClip[1] { val2 }; } return true; } try { Play(__instance, dt); } catch (Exception ex) { Plugin.Log.LogWarning((object)("music: " + ex.Message)); return true; } return false; } [HarmonyPatch(typeof(MusicMan), "UpdateMusic")] [HarmonyPostfix] private static void UpdateMusicDone(NamedMusic __state) { if (__state != null && swappedClips != null) { __state.m_clips = swappedClips; swappedClips = null; } } private static void Play(MusicMan mm, float dt) { AudioSource val = Source.Invoke(mm); if ((Object)(object)val == (Object)null) { return; } NamedMusic val2 = Queued.Invoke(mm); NamedMusic val3 = Current.Invoke(mm); bool flag = val3 != null && val.isPlaying; if (forceChange) { forceChange = false; if (flag && val2 == null) { Queued.Invoke(mm) = val3; } val2 = Queued.Invoke(mm); } if (val2 != null || Stopping.Invoke(mm)) { if (!flag) { if (!(Time.unscaledTime < gapUntil)) { if (val2 != null) { Begin(mm, val, val2); return; } val.Stop(); Current.Invoke(mm) = null; Stopping.Invoke(mm) = false; level = 0f; } return; } bool flag2 = Library.IsCalm(val3.m_name) && (val2 == null || Library.IsCalm(val2.m_name)); float num = (((Object)(object)val.clip != (Object)null) ? (val.clip.length - val.time) : 0f); if (val2 != null && val2 == val3 && (Object)(object)WantedClip(val2) == (Object)(object)val.clip) { Queued.Invoke(mm) = null; Stopping.Invoke(mm) = false; Envelope(mm, val, val3, dt); return; } if (flag2 && val2 != null && Plugin.LetCalmFinish.Value && !val.loop && num <= Plugin.FinishWindow.Value) { Envelope(mm, val, val3, dt); return; } float num2 = (flag2 ? Plugin.CalmFade.Value : Plugin.UrgentFade.Value); level = Mathf.MoveTowards(level, 0f, dt / Mathf.Max(0.1f, num2)); Apply(mm, val, val3); if (level <= 0.0001f) { if (Plugin.Resume.Value && val2 != null && !Library.IsCalm(val2.m_name) && (val.loop || num > 15f)) { saved[val3] = (val.clip, val.time, Time.unscaledTime); } val.Stop(); Current.Invoke(mm) = null; if (val2 == null) { Stopping.Invoke(mm) = false; } gapUntil = Time.unscaledTime + (flag2 ? 1.2f : 0.15f); } } else if (flag) { Envelope(mm, val, val3, dt); } else if (val3 != null) { Current.Invoke(mm) = null; } } private static AudioClip WantedClip(NamedMusic m) { object obj = Library.Get(m.m_name); if (obj == null) { if (m.m_clips == null || m.m_clips.Length == 0) { return null; } obj = m.m_clips[0]; } return (AudioClip)obj; } private static void Begin(MusicMan mm, AudioSource src, NamedMusic music) { if (rolledFor != music) { rolledFor = music; if (!saved.ContainsKey(music)) { Library.Reroll(music.m_name); } } AudioClip val = Library.Get(music.m_name); if ((Object)(object)val == (Object)null && Library.Covers(music.m_name) && Library.Loading(music.m_name)) { if (waitSince < 0f) { waitSince = Time.unscaledTime; } if (Time.unscaledTime - waitSince < 5f) { return; } } waitSince = -1f; bool flag = (Object)(object)val != (Object)null; if ((Object)(object)val == (Object)null && Library.Covers(music.m_name) && Library.Loading(music.m_name)) { return; } if ((Object)(object)val == (Object)null) { if (music.m_clips == null || music.m_clips.Length == 0) { Queued.Invoke(mm) = null; return; } val = music.m_clips[Random.Range(0, music.m_clips.Length)]; } src.Stop(); src.clip = val; src.loop = music.m_loop; src.volume = 0f; src.time = 0f; if (saved.TryGetValue(music, out (AudioClip, float, float) value)) { saved.Remove(music); if ((Object)(object)value.Item1 == (Object)(object)val && Time.unscaledTime - value.Item3 < Plugin.ResumeWindow.Value && value.Item2 < val.length - 10f) { src.time = Mathf.Max(0f, value.Item2 - 1.5f); } } src.Play(); level = 0f; fadeInTime = (Library.IsCalm(music.m_name) ? Plugin.FadeIn.Value : Mathf.Min(Plugin.FadeIn.Value, 1.5f)); gain = (flag ? (Library.Gain(music.m_name) * Plugin.Level.Value / 100f) : 1f); Current.Invoke(mm) = music; Queued.Invoke(mm) = null; Stopping.Invoke(mm) = false; music.m_lastPlayedTime = Time.time; Plugin.Log.LogInfo((object)("Playing " + music.m_name + (flag ? "" : " (Valheim's)") + ((src.time > 0f) ? $" from {src.time:0} s" : ""))); } private static void Envelope(MusicMan mm, AudioSource src, NamedMusic cur, float dt) { float num = Mathf.Clamp01(mm.m_currentMusicVolMax); level = Mathf.MoveTowards(level, num, dt / Mathf.Max(0.1f, fadeInTime)); if ((Object)(object)src.clip != (Object)null && Plugin.EndFade.Value > 0f) { float num2 = src.clip.length - src.time; if (num2 < Plugin.EndFade.Value) { level = Mathf.Min(level, num2 / Plugin.EndFade.Value); } } Apply(mm, src, cur); } private static void Apply(MusicMan mm, AudioSource src, NamedMusic cur) { src.volume = Utils.SmoothStep(0f, 1f, level) * cur.m_volume * gain * MusicMan.m_masterMusicVolume; VanillaVol.Invoke(mm) = level; VanillaMusicVol.Invoke(mm) = cur.m_volume; } [HarmonyPatch(typeof(MusicMan), "UpdateCurrentMusic")] [HarmonyPrefix] private static void RepairFirst(MusicMan __instance) { Repair.Tick(__instance); } [HarmonyPatch(typeof(MusicMan), "UpdateCurrentMusic")] [HarmonyPostfix] private static void CombatMusic(MusicMan __instance) { if (!Plugin.Enabled.Value || !Plugin.CombatMusic.Value || (Object)(object)Game.instance == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null) { return; } if (CombatTimer.Invoke(__instance) > 0f) { lastFight = Time.time; } bool flag = Time.time - lastFight < Plugin.CombatLinger.Value; string text = (Stopping.Invoke(__instance) ? "" : (Queued.Invoke(__instance)?.m_name ?? Current.Invoke(__instance)?.m_name ?? "")); bool flag2 = text.Length > 0 && text != "combat" && !Library.IsCalm(text); if (flag && !flag2 && text != "combat") { combat = combat ?? __instance.m_music.Find((NamedMusic m) => m.m_name == "combat"); if (combat != null && combat.m_enabled) { Queued.Invoke(__instance) = combat; Stopping.Invoke(__instance) = false; } } else if (!flag && text == "combat") { StopMethod.Invoke(__instance, null); } } } [BepInPlugin("daytreee.runeheimmusic", "Runeheim Music", "1.1.4")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public enum Soundtrack { RuneheimII, RuneheimI, Custom, Vanilla } public const string Guid = "daytreee.runeheimmusic"; public const string ModName = "Runeheim Music"; public const string Version = "1.1.4"; internal static readonly string Notice = "Runeheim Music (c) 2026 Daytreee. All rights reserved. Not open source; no reuse of this code, by hand or by AI, without permission."; public static Plugin Instance; public static ManualLogSource Log; public static ConfigEntry<bool> Enabled; public static ConfigEntry<bool> Smooth; public static ConfigEntry<bool> LetCalmFinish; public static ConfigEntry<bool> Resume; public static ConfigEntry<bool> CombatMusic; public static ConfigEntry<Soundtrack> Preset; private static string musicRoot; public static ConfigEntry<bool> GroupStory; public static ConfigEntry<bool> GroupDay; public static ConfigEntry<bool> GroupBiomes; public static ConfigEntry<bool> GroupFights; public static ConfigEntry<bool> GroupPlaces; public static ConfigEntry<bool> GroupBosses; public static ConfigEntry<float> Level; public static ConfigEntry<float> CalmFade; public static ConfigEntry<float> UrgentFade; public static ConfigEntry<float> FadeIn; public static ConfigEntry<float> EndFade; public static ConfigEntry<float> FinishWindow; public static ConfigEntry<float> ResumeWindow; public static ConfigEntry<float> CombatLinger; public static ConfigEntry<float> PauseMin; public static ConfigEntry<float> PauseMax; private void Awake() { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Expected O, but got Unknown //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Expected O, but got Unknown //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Expected O, but got Unknown //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Expected O, but got Unknown //IL_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Expected O, but got Unknown //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Expected O, but got Unknown //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Expected O, but got Unknown //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_0390: Expected O, but got Unknown //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Expected O, but got Unknown //IL_0531: Unknown result type (might be due to invalid IL or missing references) Instance = this; Log = ((BaseUnityPlugin)this).Logger; RhLoc.AddFolder(Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "translations")); Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Runeheim soundtrack", true, "Plays the Runeheim soundtrack in place of Valheim's music. Off: Valheim's own music, played the way Valheim does."); Level = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Soundtrack volume (%)", 80f, new ConfigDescription("Loudness of the Runeheim songs against Valheim's own mix (the game's music volume still applies on top).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 150f), Array.Empty<object>())); GroupStory = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Menu, intro and credits", true, "The main menu, the opening and the end credits."); GroupDay = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Morning and evening", true, "The songs at sunrise and dusk."); GroupBiomes = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Biomes and sailing", true, "Each biome's music, your base by the fire, and sailing."); GroupFights = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Combat and raids", true, "Combat and the four raid levels."); GroupPlaces = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Dungeons and places", true, "Crypts, caves, Hildir's dungeons, Haldor, Dvergr sites, Ashlands ruins and the discovery sting."); GroupBosses = ((BaseUnityPlugin)this).Config.Bind<bool>("Songs", "Bosses", true, "Every boss fight and the Queen's lair."); Smooth = ((BaseUnityPlugin)this).Config.Bind<bool>("Playback", "Smooth playback", true, "One song at a time with soft fades on every start and stop, and the rules below. Off: Valheim's own playback (with the Runeheim songs if they're on)."); CalmFade = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Calm fade (s)", 6f, new ConfigDescription("Fade-out when the calm music changes (a new biome, dusk, your base).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f), Array.Empty<object>())); UrgentFade = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Fight fade (s)", 2f, new ConfigDescription("Fade-out when a fight, raid, boss or dungeon takes over.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 6f), Array.Empty<object>())); FadeIn = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Fade-in (s)", 4f, new ConfigDescription("Fade-in of every song.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 12f), Array.Empty<object>())); EndFade = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Ending fade (s)", 5f, new ConfigDescription("How long a song fades out as it reaches its end (and before it loops).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 15f), Array.Empty<object>())); LetCalmFinish = ((BaseUnityPlugin)this).Config.Bind<bool>("Playback", "Let calm songs finish", true, "When the calm music changes and the song playing is near its end, it plays out instead of fading early."); FinishWindow = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Finish if this close to the end (s)", 60f, new ConfigDescription("How near its end a calm song must be to play out.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 180f), Array.Empty<object>())); Resume = ((BaseUnityPlugin)this).Config.Bind<bool>("Playback", "Resume interrupted songs", true, "A song cut short by a fight, raid, boss or place carries on where it stopped afterwards."); ResumeWindow = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Resume within (s)", 240f, new ConfigDescription("How long an interrupted song is remembered.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(30f, 900f), Array.Empty<object>())); PauseMin = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Quiet between songs, min (s)", 300f, new ConfigDescription("With Valheim's 'Continuous music' off: the shortest silence before the next calm song (Valheim: 300).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 900f), Array.Empty<object>())); PauseMax = ((BaseUnityPlugin)this).Config.Bind<float>("Playback", "Quiet between songs, max (s)", 500f, new ConfigDescription("The longest silence before the next calm song (Valheim: 500).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1200f), Array.Empty<object>())); CombatMusic = ((BaseUnityPlugin)this).Config.Bind<bool>("Combat", "Combat music", true, "Plays the combat song while enemies are fighting you (Valheim no longer plays its own combat music)."); CombatLinger = ((BaseUnityPlugin)this).Config.Bind<float>("Combat", "Combat music lingers (s)", 12f, new ConfigDescription("How long the combat song keeps going after the last blow, so short pauses in a fight don't stop it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 60f), Array.Empty<object>())); Preset = ((BaseUnityPlugin)this).Config.Bind<Soundtrack>("General", "Soundtrack preset", Soundtrack.RuneheimII, "Which soundtrack plays. Runeheim II: the dark Nordic soundtrack (default). Runeheim I: the first soundtrack. Custom: your own songs in music/Custom (named like the Runeheim ones, e.g. meadows.mp3; meadows_2.mp3 adds another version). Valheim: the game's own music (the playback settings still apply)."); musicRoot = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "music"); Library.Init(musicRoot, Preset.Value); Preset.SettingChanged += delegate { Library.Init(musicRoot, Preset.Value); Playback.Refresh(); }; Enabled.SettingChanged += delegate { Playback.Refresh(); }; Smooth.SettingChanged += delegate { Playback.Refresh(); }; ConfigEntry<bool>[] array = new ConfigEntry<bool>[6] { GroupStory, GroupDay, GroupBiomes, GroupFights, GroupPlaces, GroupBosses }; for (int num = 0; num < array.Length; num++) { array[num].SettingChanged += delegate { Playback.Refresh(); }; } new Harmony("daytreee.runeheimmusic").PatchAll(); MusicSettings.Register(((BaseUnityPlugin)this).Config); Log.LogInfo((object)string.Format("{0} {1}: {2} songs", "Runeheim Music", "1.1.4", Library.Count)); } } public static class Repair { private static readonly FieldRef<MusicMan, Dictionary<int, NamedMusic>> Hashes = RhSafe.FieldRef<MusicMan, Dictionary<int, NamedMusic>>("m_musicHashes", "C:\\Users\\daytr\\Documents\\ValheimModding\\RuneheimMusic\\Repair.cs", 17); private static float next; private static AudioClip standIn; private static readonly HashSet<string> told = new HashSet<string>(); private static readonly Dictionary<string, (float vol, bool loop)> Defaults = new Dictionary<string, (float, bool)> { ["menu"] = (0.7f, true), ["intro"] = (0.6f, false), ["credits"] = (0.8f, false), ["morning"] = (0.45f, false), ["evening"] = (0.45f, false), ["meadows"] = (0.4f, true), ["blackforest"] = (0.4f, true), ["swamp"] = (0.6f, true), ["mountain"] = (0.65f, true), ["plains"] = (0.4f, true), ["mistlands"] = (0.65f, true), ["ashlands"] = (0.7f, true), ["sailing"] = (0.85f, true), ["ocean"] = (0.85f, true), ["sailing_ashlands"] = (0.5f, true), ["home"] = (0.45f, true), ["combat"] = (0.6f, true), ["location_forest"] = (0.4f, false) }; public static void Tick(MusicMan mm) { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown if (!Plugin.Enabled.Value || Time.unscaledTime < next) { return; } next = Time.unscaledTime + 2f; Dictionary<int, NamedMusic> dictionary = Hashes.Invoke(mm); if (dictionary == null || mm.m_music == null) { return; } foreach (string name in Library.Names) { if (Library.Covers(name)) { NamedMusic val = mm.m_music.Find((NamedMusic m) => m != null && m.m_name == name); bool flag = false; if (val == null) { (float, bool) value; (float, bool) tuple = (Defaults.TryGetValue(name, out value) ? value : (name.StartsWith("location_") ? 0.8f : 0.85f, !name.StartsWith("location_forest"))); val = new NamedMusic { m_name = name, m_volume = tuple.Item1, m_loop = tuple.Item2, m_resume = true, m_fadeInTime = 3f, m_ambientMusic = Library.IsCalm(name) }; mm.m_music.Add(val); flag = true; } if (val.m_clips == null || val.m_clips.Length == 0 || Array.Exists(val.m_clips, (AudioClip c) => (Object)(object)c == (Object)null)) { val.m_clips = (AudioClip[])(object)new AudioClip[1] { StandIn() }; flag = true; } if (!val.m_enabled) { val.m_enabled = true; flag = true; } int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (!dictionary.TryGetValue(stableHashCode, out var value2) || value2 != val) { dictionary[stableHashCode] = val; flag = true; } if (flag && told.Add(name)) { Plugin.Log.LogInfo((object)("Repaired the '" + name + "' music entry (another mod left it without a working song)")); } } } } private static AudioClip StandIn() { if ((Object)(object)standIn == (Object)null) { standIn = AudioClip.Create("Runeheim stand-in", 44100, 1, 44100, false); } return standIn; } } }