Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,17 @@ private struct ReusedPfx
public ParticleSystem[] Systems;
}

private const string _clipSourceName = "_AnimationSfx";

private readonly Transform _boneRoot;
private readonly Transform _stepOrigin;
private readonly AudioSource _sound;
private readonly bool _isSoundShared;
// The volume the given source had: Gothic's volume of each sound is applied on top of it.
private readonly float _soundBaseVolume;
private readonly bool _isReusingPfx;
// Plays the *eventSFX clips: the given source, or an own one next to it if that's shared (see GetClipSource).
private AudioSource _clipSource;

// One-off mode: effects with an index, until their *eventPFXStop.
private readonly Dictionary<int, GameObject> _activePfx = new();
Expand All @@ -63,13 +70,20 @@ private struct ReusedPfx
/// </param>
/// <param name="stepOrigin">Where a step sound (*eventSFXGrnd) asks for the ground below.</param>
/// <param name="sound">Plays the *eventSFX sounds (one at a time, like the engine's model sound).</param>
/// <param name="isSoundShared">Others play on the source too (an NPC's NpcSound): its clips get an own source
/// next to it, see GetClipSource().</param>
/// <param name="isReusingPfx">Build each effect once and replay it (mobs), see class summary.</param>
public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isReusingPfx)
public AnimationEffectPlayer(Transform boneRoot, Transform stepOrigin, AudioSource sound, bool isSoundShared,
bool isReusingPfx)
{
_boneRoot = boneRoot;
_stepOrigin = stepOrigin;
_sound = sound;
_isSoundShared = isSoundShared;
_soundBaseVolume = sound != null ? sound.volume : 1f;
_isReusingPfx = isReusingPfx;
if (!isSoundShared)
_clipSource = sound;
}

/// <summary>
Expand All @@ -91,21 +105,58 @@ public bool ApplySfxEvents(AnimationTrackInstance trackInstance)
continue;
var stepName = _groundSoundService.GetSoundName(
sfx.Name.Substring(GroundSoundDomain.GroundEventPrefix.Length), _stepOrigin.position);
var stepClip = _audioService.GetRandomSoundClip(stepName);
var stepClip = _audioService.GetRandomSoundClip(stepName, out var stepVolume);
if (stepClip != null)
_sound.PlayOneShot(stepClip);
_sound.PlayOneShot(stepClip, stepVolume * _audioService.SoundVolume);
continue;
}

var clip = _audioService.GetRandomSoundClip(sfx.Name);
_sound.clip = clip;
_sound.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter());
_sound.Play();
// Gothic's volume of the sound (Forge_Sharpen 40 of 127) and the player's sound volume, which a
// long clip (FORGE_FIRE) follows while it plays. Its source plays one clip at a time.
var clip = _audioService.GetRandomSoundClip(sfx.Name, out var volume);
var clipSource = GetClipSource();
clipSource.clip = clip;
_audioService.SetSfxVolume(clipSource, _soundBaseVolume * volume);
clipSource.maxDistance = _audioService.GetSfxRangeMeters(sfx.Name, sfx.Range.ToMeter());
clipSource.Play();
}

return sfxEvents.Count > 0;
}

/// <summary>
/// The source of the *eventSFX clips. An NPC's NpcSound is shared - hits, weapon draws and steps play on it as
/// one-shots, which a clip's volume (Gothic's of each sound) would turn down, and so would its range. Its clips
/// get an own source next to it instead, created on the first one with NpcSound's settings.
/// </summary>
private AudioSource GetClipSource()
{
if (_clipSource != null || !_isSoundShared)
return _clipSource;

var existing = _sound.transform.Find(_clipSourceName);
if (existing != null && existing.TryGetComponent(out _clipSource))
return _clipSource;

var clipGo = new GameObject(_clipSourceName);
clipGo.transform.SetParent(_sound.transform, false);
_clipSource = clipGo.AddComponent<AudioSource>();
_clipSource.playOnAwake = false;
_clipSource.outputAudioMixerGroup = _sound.outputAudioMixerGroup;
_clipSource.spatialBlend = _sound.spatialBlend;
_clipSource.priority = _sound.priority;
_clipSource.dopplerLevel = _sound.dopplerLevel;
_clipSource.spread = _sound.spread;
_clipSource.reverbZoneMix = _sound.reverbZoneMix;
_clipSource.rolloffMode = _sound.rolloffMode;
_clipSource.minDistance = _sound.minDistance;
_clipSource.maxDistance = _sound.maxDistance;
if (_sound.rolloffMode == AudioRolloffMode.Custom)
_clipSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff,
_sound.GetCustomCurve(AudioSourceCurveType.CustomRolloff));
return _clipSource;
}

/// <summary>
/// *eventPFX (frame, index, name, bone, ATTACH) creates the effect at the
/// bone (following it if attached), *eventPFXStop (frame, index) lets it fade out. Joint smoke, bubbles, ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ private void Start()
_initialMeshBonePos = _bones.Select(i => i.localPosition).ToArray();
_initialMeshBoneRot = _bones.Select(i => i.localRotation).ToArray();

_effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound, isReusingPfx: false)
.Inject();
_effectPlayer = new AnimationEffectPlayer(Go.transform, transform, PrefabProps.NpcSound,
isSoundShared: true, isReusingPfx: false).Inject();

CreateGraph();
ResizeRootCollider();
Expand Down
3 changes: 2 additions & 1 deletion Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ public void Init(VobContainer mob, AnimationSkeleton skeleton)
_sound.spatialBlend = 1f;
_sound.rolloffMode = AudioRolloffMode.Linear;
_sound.minDistance = 0f;
_effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isReusingPfx: true).Inject();
_effectPlayer = new AnimationEffectPlayer(transform, transform, _sound, isSoundShared: false,
isReusingPfx: true).Inject();

Rest(isSoundStopped: true);
}
Expand Down
4 changes: 4 additions & 0 deletions Assets/Gothic-Core/Scripts/Const/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ public static class IniNames
public const string IniSectionSound = "SOUND";
public const int FootstepSoundsDefaultValue = 1;

// Gothic's own [SOUND] 0..1, the options' sound effects slider (AudioService.SoundVolume).
public const string SoundVolume = "soundVolume";
public const float SoundVolumeDefaultValue = 0.75f; // Gothic's own volume (AudioService)

// [VIDEO] 0..1, vanilla 0.5 = neutral (the menu's Brightness slider).
public const string VideoBrightness = "zVidBrightness";
public const float VideoBrightnessDefaultValue = 0.5f;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,8 @@ private GameObject CreateSoundDaytime(SoundDaytime vob, GameObject parent)
private void PrepareAudioSource(AudioSource source, Sound soundData, string soundName)
{
source.maxDistance = soundData.Radius / 100f; // Gothic's values are in cm, Unity's in m.
source.volume = soundData.Volume / 100f; // Gothic's volume is 0...100, Unity's is 0...1.
// Gothic's volume is 0...100, Unity's is 0...1. Times the player's sound volume, a loop follows the slider.
_audioService.SetSfxVolume(source, soundData.Volume / 100f);

// Random sounds shouldn't play initially, but after certain time.
source.playOnAwake = soundData.InitiallyPlaying && soundData.Mode != SoundMode.Random;
Expand Down
29 changes: 25 additions & 4 deletions Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,13 @@ public class SfxModel
// TODO - Injecting in a Model wasn't intended. Try to use it without injecting.
[Inject] private readonly GameStateService _gameStateService;

// C_SFX_DEF vol is 0..127 (the prototype's default 127).
private const float _maxGothicVolume = 127f;

private string soundKey;
private SoundEffectInstance[] _soundEffects;
// Gothic's volume of each instance (vol, 0..1), same index as _soundEffects.
private float[] _volumes;

public int Count => _soundEffects.Length;

Expand All @@ -45,16 +50,27 @@ public SoundEffectInstance GetFirstSound()

[CanBeNull]
public SoundEffectInstance GetRandomSound()
{
return GetRandomSound(out _);
}

/// <summary>
/// Like GetRandomSound(), with Gothic's volume of the picked instance (vol as 0..1): a random variant
/// (BreathBubbles_A1) has its own. 1 if there's none.
/// </summary>
[CanBeNull]
public SoundEffectInstance GetRandomSound(out float volume)
{
if (_soundEffects == null)
LoadSoundEffects();

volume = 1f;
if (_soundEffects.IsEmpty())
return null;
else if (_soundEffects!.Length == 1)
return _soundEffects.First();
else
return _soundEffects.GetRandom();

var index = _soundEffects!.Length == 1 ? 0 : UnityEngine.Random.Range(0, _soundEffects.Length);
volume = _volumes[index];
return _soundEffects[index];
}

private void LoadSoundEffects()
Expand All @@ -71,6 +87,7 @@ private void LoadSoundEffects()
// SFX symbol missing from Gothic's SFX scripts — expected for some broken VOBs (e.g. Wood_Night2 was never defined).
Logger.LogWarning($"SFX symbol not found in VM: '{soundKey}' — no sound will play.", LogCat.Audio);
_soundEffects = Array.Empty<SoundEffectInstance>();
_volumes = Array.Empty<float>();
return;
}

Expand Down Expand Up @@ -109,6 +126,10 @@ private void LoadSoundEffects()
}

_soundEffects = sounds.ToArray();

_volumes = new float[_soundEffects.Length];
for (var i = 0; i < _soundEffects.Length; i++)
_volumes[i] = UnityEngine.Mathf.Clamp01(_soundEffects[i].Volume / _maxGothicVolume);
}
}
}
98 changes: 95 additions & 3 deletions Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Gothic.Core.Const;
using Gothic.Core.Domain.Audio;
using Gothic.Core.Logging;
using Gothic.Core.Models.Container;
Expand Down Expand Up @@ -50,9 +51,23 @@ public class AudioService

private AudioSource _scriptSoundSource;

// Gothic.ini soundVolume, read on first use and again when the menu changes it. Stays unset while Gothic.ini
// isn't loaded (the player scene runs before a game was picked): the default would stick otherwise.
private float? _soundVolume;
// Sound effect sources that follow the slider (SetSfxVolume): their volume without it.
private readonly Dictionary<AudioSource, float> _sfxSources = new();
private readonly List<AudioSource> _destroyedSfxSources = new();

public SoundEffectInstance InvOpen => _vmCacheService.TryGetSfxData("INV_OPEN").GetFirstSound();
public SoundEffectInstance InvClose => _vmCacheService.TryGetSfxData("INV_CLOSE").GetFirstSound();


public AudioService()
{
GlobalEventDispatcher.PlayerPrefUpdated.AddListener(OnSoundOptionUpdated);
// The old world's sources are gone by now.
GlobalEventDispatcher.WorldSceneLoaded.AddListener(RemoveDestroyedSfxSources);
}

//
// Music
//
Expand Down Expand Up @@ -177,6 +192,73 @@ public void SetScriptSoundSource(AudioSource audioSource)
_scriptSoundSource = audioSource;
}

// The slider position that plays the sounds at Gothic's own volume: the slider's top end is louder (1/0.75).
private const float _ownVolumeSliderPosition = 0.75f;

/// <summary>
/// The player's sound effects gain (options slider, Gothic.ini [SOUND] soundVolume 0..1): the slider at 0.75
/// plays Gothic's own volume, the top end a third louder. Voices and music have their own.
/// </summary>
public float SoundVolume
{
get
{
if (_soundVolume.HasValue)
return _soundVolume.Value;

var slider = Mathf.Clamp01(_configService.GetGothicOption(Constants.IniNames.SoundVolume,
Constants.IniNames.SoundVolumeDefaultValue));
var volume = slider / _ownVolumeSliderPosition;
if (_configService.Gothic == null)
return volume;

_soundVolume = volume;
Logger.Log($"[SoundVolume] Sound effects slider {slider:0.##} (Gothic.ini soundVolume), gain " +
$"{volume:0.##}.",
LogCat.Audio);
return volume;
}
}

/// <summary>
/// Sets a sound effect source's volume: the sound's own (Gothic's, 0..1) times the player's SoundVolume. The
/// source follows the slider from now on - a loop that plays (a VOB's campfire, the forge fire) changes at
/// once. Call it again when the source plays another sound with another volume.
/// </summary>
public void SetSfxVolume(AudioSource source, float soundVolume)
{
_sfxSources[source] = soundVolume;
source.volume = soundVolume * SoundVolume;
}

private void OnSoundOptionUpdated(string key, object value)
{
if (key != Constants.IniNames.SoundVolume)
return;

_soundVolume = null;
var volume = SoundVolume;
foreach (var (source, soundVolume) in _sfxSources)
{
if (source != null)
source.volume = soundVolume * volume;
}
RemoveDestroyedSfxSources();
}

private void RemoveDestroyedSfxSources()
{
foreach (var (source, _) in _sfxSources)
{
if (source == null)
_destroyedSfxSources.Add(source);
}

foreach (var source in _destroyedSfxSources)
_sfxSources.Remove(source);
_destroyedSfxSources.Clear();
}

/// <summary>
/// Range (m) in which an animation sound (*eventSFX) is audible: the override of the few sounds that carry
/// further than Gothic's range, else Gothic's own.
Expand All @@ -201,7 +283,7 @@ public void PlaySound2D(string soundName)

var clip = GetRandomSoundClip(soundName);
if (clip != null)
_scriptSoundSource.PlayOneShot(clip);
_scriptSoundSource.PlayOneShot(clip, SoundVolume);
}

[CanBeNull]
Expand Down Expand Up @@ -254,8 +336,18 @@ public Task<AudioClip> CreateAudioClipAsync(string fileName)
/// This method caches the AudioClips itself automatically. No performance penalty when re-running this method.
/// </summary>
public AudioClip GetRandomSoundClip(string soundName)
{
return GetRandomSoundClip(soundName, out _);
}

/// <summary>
/// Like GetRandomSoundClip(), with Gothic's volume of the picked sound (its C_SFX_DEF vol as 0..1 - a random
/// variant _A1, _A2 has its own, Forge_Sharpen is quiet). A .wav file name has none: 1.
/// </summary>
public AudioClip GetRandomSoundClip(string soundName, out float volume)
{
AudioClip clip;
volume = 1f;

if (soundName.EqualsIgnoreCase(NoSoundName))
{
Expand All @@ -279,7 +371,7 @@ public AudioClip GetRandomSoundClip(string soundName)
if (sfxContainer.GetFirstSound() == null || sfxContainer.GetFirstSound()!.File.EqualsIgnoreCase(NoSoundName))
return null;

clip = CreateAudioClip(sfxContainer.GetRandomSound());
clip = CreateAudioClip(sfxContainer.GetRandomSound(out volume));
}

return clip;
Expand Down
3 changes: 1 addition & 2 deletions Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,8 +114,7 @@ public List<string> InventoryCategories
"MENUITEM_GRA_TEXQUAL", "MENUITEM_GRA_TEXQUAL_SLIDER",
"MENUITEM_GRA_MODEL_DETAIL", "MENUITEM_GRA_MODEL_DETAIL_SLIDER",
"MENUITEM_GRA_SKY_EFFECTS", "MENUITEM_GRA_SKY_EFFECTS_CHOICE",
// Parts of AUDIO menu
"MENUITEM_AUDIO_SFXVOL", "MENUITEM_AUDIO_SFXVOL_SLIDER",
// Parts of AUDIO menu (the sound effects volume works: AudioService.SoundVolume)
"MENUITEM_AUDIO_PROVIDER", "MENUITEM_AUDIO_PROVIDER_CHOICE",
"MENUITEM_AUDIO_SPEEKER", "MENUITEM_AUDIO_SPEEKER_CHOICE",
"MENUITEM_AUDIO_REVERB", "MENUITEM_AUDIO_REVERB_CHOICE",
Expand Down
Loading