Merge branch 'feat-trol-sounds'
This commit is contained in:
commit
b25548280c
5 changed files with 252 additions and 0 deletions
BIN
JotunnModStub/Audio/trolsbuilding.ogg
Normal file
BIN
JotunnModStub/Audio/trolsbuilding.ogg
Normal file
Binary file not shown.
BIN
JotunnModStub/Audio/trolsdeath.ogg
Normal file
BIN
JotunnModStub/Audio/trolsdeath.ogg
Normal file
Binary file not shown.
|
|
@ -76,6 +76,9 @@ namespace RacesOfValheim
|
|||
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
|
||||
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd1", TrolSounds.Death));
|
||||
CommandManager.Instance.AddConsoleCommand(new TrolSoundCommand("rovsnd2", TrolSounds.Building));
|
||||
StartCoroutine(TrolSounds.Load());
|
||||
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
|
||||
CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand());
|
||||
|
|
|
|||
|
|
@ -57,6 +57,7 @@
|
|||
manager has no extra folder to flatten. Loaded by name: PieceLook.LoadTexture("CookCloth_d.png"). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Assets\**\*.png" LogicalName="%(Filename)%(Extension)" />
|
||||
<EmbeddedResource Include="Audio\*.ogg" LogicalName="%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
248
JotunnModStub/Trol/TrolSounds.cs
Normal file
248
JotunnModStub/Trol/TrolSounds.cs
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Two rare Trol voice lines: one when a Trol dies, one when a Trol places a piece with Trol's
|
||||
/// Hammer. Each has a 1% chance by default.
|
||||
///
|
||||
/// The chance is Dota's pseudo-random distribution, not a plain roll: each try starts at a tiny
|
||||
/// chance C that grows by C after every miss and falls back to C after a hit. It averages the
|
||||
/// same chance, but long droughts and back-to-back repeats almost never happen, which suits a
|
||||
/// joke heard rarely. The miss counters live in memory and start over with the game.
|
||||
///
|
||||
/// The roll happens on the Trol's own client, which then sends the sound and the spot to every
|
||||
/// client; each one plays it there if its player is within reach.
|
||||
///
|
||||
/// A secret on purpose: no setting, and no word of it in the README, changelog or wiki. The
|
||||
/// chance and the volume are constants here for that reason.
|
||||
///
|
||||
/// The clips ship inside the DLL (Audio/*.ogg, embedded by the csproj), so no sound file sits in
|
||||
/// the plugins folder for a curious player to find. Unity can only decode Ogg from a file, so at
|
||||
/// startup each one is written to the game's temp cache under a random name, loaded, and deleted.
|
||||
/// </summary>
|
||||
public static class TrolSounds
|
||||
{
|
||||
public const string Death = "trolsdeath";
|
||||
public const string Building = "trolsbuilding";
|
||||
|
||||
private const string RpcName = "RoV_TrolSound";
|
||||
private const float Range = 20f; // metres: heard nearby, not across the base
|
||||
private const float Volume = 0.6f;
|
||||
public const float DeathChance = 1f; // percent
|
||||
public const float BuildingChance = 1f; // percent
|
||||
private const string MixerSource = "sfx_build_hammer_wood";
|
||||
|
||||
private static readonly string[] Clips = { Death, Building };
|
||||
private static readonly Dictionary<string, AudioClip> s_clips = new Dictionary<string, AudioClip>();
|
||||
private static readonly Dictionary<string, int> s_misses = new Dictionary<string, int>();
|
||||
|
||||
// --- loading ---
|
||||
|
||||
/// <summary>Loads both clips out of the DLL, by way of a file that lives only while it loads.</summary>
|
||||
public static IEnumerator Load()
|
||||
{
|
||||
foreach (string name in Clips)
|
||||
{
|
||||
byte[] bytes;
|
||||
using (Stream stream = typeof(TrolSounds).Assembly.GetManifestResourceStream(name + ".ogg"))
|
||||
{
|
||||
if (stream == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[TrolSounds] No embedded clip '{name}'.");
|
||||
continue;
|
||||
}
|
||||
bytes = new byte[stream.Length];
|
||||
int read = 0;
|
||||
while (read < bytes.Length) read += stream.Read(bytes, read, bytes.Length - read);
|
||||
}
|
||||
|
||||
string path = Path.Combine(Application.temporaryCachePath, System.Guid.NewGuid().ToString("N"));
|
||||
File.WriteAllBytes(path, bytes);
|
||||
using (UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip("file:///" + path.Replace('\\', '/'), AudioType.OGGVORBIS))
|
||||
{
|
||||
yield return request.SendWebRequest();
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
AudioClip clip = DownloadHandlerAudioClip.GetContent(request);
|
||||
clip.name = name;
|
||||
s_clips[name] = clip;
|
||||
}
|
||||
else
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[TrolSounds] Could not load '{name}': {request.error}");
|
||||
}
|
||||
}
|
||||
try { File.Delete(path); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
|
||||
// --- the roll ---
|
||||
|
||||
/// <summary>One try at a sound for the local Trol: plays it for everyone nearby on a hit.</summary>
|
||||
public static void Try(string sound, float percent, Vector3 position)
|
||||
{
|
||||
if (!Roll(sound, percent / 100f)) return;
|
||||
Broadcast(sound, position);
|
||||
}
|
||||
|
||||
private static bool Roll(string sound, float chance)
|
||||
{
|
||||
if (chance <= 0f) return false;
|
||||
if (chance >= 1f) return true;
|
||||
|
||||
s_misses.TryGetValue(sound, out int misses);
|
||||
if (Random.value < PrdConstant(chance) * (misses + 1))
|
||||
{
|
||||
s_misses[sound] = 0;
|
||||
return true;
|
||||
}
|
||||
s_misses[sound] = misses + 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static float s_constantFor = -1f, s_constant;
|
||||
|
||||
/// <summary>
|
||||
/// The step C whose growing chance (C, 2C, 3C... until a hit) averages the chance asked for.
|
||||
/// No formula gives C; it is found by halving, once per chance value (0.000156 for 1%).
|
||||
/// </summary>
|
||||
private static float PrdConstant(float chance)
|
||||
{
|
||||
if (Mathf.Approximately(chance, s_constantFor)) return s_constant;
|
||||
|
||||
double low = 0, high = chance;
|
||||
for (int i = 0; i < 50; i++)
|
||||
{
|
||||
double c = (low + high) / 2;
|
||||
if (AverageChance(c) > chance) high = c; else low = c;
|
||||
}
|
||||
s_constantFor = chance;
|
||||
s_constant = (float)((low + high) / 2);
|
||||
return s_constant;
|
||||
}
|
||||
|
||||
/// <summary>The average chance a step of c gives: one over the expected tries to a hit.</summary>
|
||||
private static double AverageChance(double c)
|
||||
{
|
||||
double expected = 0, missedSoFar = 1;
|
||||
for (int n = 1; missedSoFar > 1e-12; n++)
|
||||
{
|
||||
double hit = System.Math.Min(1, c * n);
|
||||
expected += n * missedSoFar * hit;
|
||||
missedSoFar *= 1 - hit;
|
||||
}
|
||||
return 1 / expected;
|
||||
}
|
||||
|
||||
// --- playing ---
|
||||
|
||||
public static void Broadcast(string sound, Vector3 position)
|
||||
{
|
||||
if (ZRoutedRpc.instance != null)
|
||||
ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, RpcName, sound, position);
|
||||
else
|
||||
Play(sound, position);
|
||||
}
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
ZRoutedRpc.instance?.Register<string, Vector3>(RpcName, (sender, sound, position) => Play(sound, position));
|
||||
}
|
||||
|
||||
/// <summary>Plays a clip at a spot, if the local player is within reach of it. Through the
|
||||
/// game's sound-effects mixer, so Valheim's own SFX slider turns it down too.</summary>
|
||||
public static void Play(string sound, Vector3 position)
|
||||
{
|
||||
if (!s_clips.TryGetValue(sound, out AudioClip clip) || clip == null) return;
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player != null && Vector3.Distance(player.transform.position, position) > Range) return;
|
||||
|
||||
GameObject go = new GameObject("RoV_" + sound);
|
||||
go.transform.position = position;
|
||||
AudioSource source = go.AddComponent<AudioSource>();
|
||||
source.clip = clip;
|
||||
source.volume = Volume;
|
||||
source.spatialBlend = 1f;
|
||||
source.rolloffMode = AudioRolloffMode.Linear;
|
||||
source.minDistance = 4f;
|
||||
source.maxDistance = Range;
|
||||
source.outputAudioMixerGroup = MixerGroup();
|
||||
source.Play();
|
||||
Object.Destroy(go, clip.length + 0.5f);
|
||||
}
|
||||
|
||||
private static UnityEngine.Audio.AudioMixerGroup s_mixer;
|
||||
|
||||
private static UnityEngine.Audio.AudioMixerGroup MixerGroup()
|
||||
{
|
||||
if (s_mixer != null) return s_mixer;
|
||||
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(MixerSource);
|
||||
AudioSource vanilla = sfx != null ? sfx.GetComponentInChildren<AudioSource>(true) : null;
|
||||
s_mixer = vanilla != null ? vanilla.outputAudioMixerGroup : null;
|
||||
return s_mixer;
|
||||
}
|
||||
|
||||
public static bool IsTrol(Player player) => FactionHostilityPatch.GetPlayerRace(player) == "Trol";
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Game), "Start")]
|
||||
public static class TrolSoundsRpcPatch
|
||||
{
|
||||
private static void Postfix() => TrolSounds.Register();
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Player), "OnDeath")]
|
||||
public static class TrolSoundsDeathPatch
|
||||
{
|
||||
private static void Prefix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer || !TrolSounds.IsTrol(__instance)) return;
|
||||
TrolSounds.Try(TrolSounds.Death, TrolSounds.DeathChance, __instance.transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Player), "PlacePiece")]
|
||||
public static class TrolSoundsBuildingPatch
|
||||
{
|
||||
private static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer || !TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
|
||||
if (!TrolSounds.IsTrol(__instance)) return;
|
||||
TrolSounds.Try(TrolSounds.Building, TrolSounds.BuildingChance, __instance.transform.position);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// rovsnd1 / rovsnd2: play one of the two sounds now, for everyone nearby, to try it out. The
|
||||
/// names and the help say nothing about what they play: the console's help lists every command.
|
||||
/// </summary>
|
||||
public class TrolSoundCommand : ConsoleCommand
|
||||
{
|
||||
private readonly string m_name;
|
||||
private readonly string m_sound;
|
||||
|
||||
public TrolSoundCommand(string name, string sound)
|
||||
{
|
||||
m_name = name;
|
||||
m_sound = sound;
|
||||
}
|
||||
|
||||
public override string Name => m_name;
|
||||
public override string Help => "[DEBUG] Sound test.";
|
||||
|
||||
public override void Run(string[] args)
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) { Console.instance.Print("No local player."); return; }
|
||||
TrolSounds.Broadcast(m_sound, player.transform.position);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue