diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs index e0833ef99..b151d2ba2 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationEffectPlayer.cs @@ -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 _activePfx = new(); @@ -63,13 +70,20 @@ private struct ReusedPfx /// /// Where a step sound (*eventSFXGrnd) asks for the ground below. /// Plays the *eventSFX sounds (one at a time, like the engine's model sound). + /// Others play on the source too (an NPC's NpcSound): its clips get an own source + /// next to it, see GetClipSource(). /// Build each effect once and replay it (mobs), see class summary. - 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; } /// @@ -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; } + /// + /// 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. + /// + 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(); + _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; + } + /// /// *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, ... diff --git a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs index c3b20f852..f330c8fa4 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Animations/AnimationSystem.cs @@ -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(); diff --git a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs index 06ce24153..ae24d30af 100644 --- a/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs +++ b/Assets/Gothic-Core/Scripts/Adapters/Vob/MobAnimator.cs @@ -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); } diff --git a/Assets/Gothic-Core/Scripts/Const/Constants.cs b/Assets/Gothic-Core/Scripts/Const/Constants.cs index be0547dfb..30b9aad27 100644 --- a/Assets/Gothic-Core/Scripts/Const/Constants.cs +++ b/Assets/Gothic-Core/Scripts/Const/Constants.cs @@ -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; diff --git a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs index beb1ff979..7b8347a88 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Vobs/VobInitializerDomain.cs @@ -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; diff --git a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs index f6105f5c3..a690095b6 100644 --- a/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs +++ b/Assets/Gothic-Core/Scripts/Models/Audio/SfxModel.cs @@ -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; @@ -45,16 +50,27 @@ public SoundEffectInstance GetFirstSound() [CanBeNull] public SoundEffectInstance GetRandomSound() + { + return GetRandomSound(out _); + } + + /// + /// 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. + /// + [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() @@ -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(); + _volumes = Array.Empty(); return; } @@ -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); } } } diff --git a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs index 306e5d4e4..c9b003179 100644 --- a/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Audio/AudioService.cs @@ -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; @@ -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 _sfxSources = new(); + private readonly List _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 // @@ -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; + + /// + /// 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. + /// + 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; + } + } + + /// + /// 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. + /// + 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(); + } + /// /// 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. @@ -201,7 +283,7 @@ public void PlaySound2D(string soundName) var clip = GetRandomSoundClip(soundName); if (clip != null) - _scriptSoundSource.PlayOneShot(clip); + _scriptSoundSource.PlayOneShot(clip, SoundVolume); } [CanBeNull] @@ -254,8 +336,18 @@ public Task CreateAudioClipAsync(string fileName) /// This method caches the AudioClips itself automatically. No performance penalty when re-running this method. /// public AudioClip GetRandomSoundClip(string soundName) + { + return GetRandomSoundClip(soundName, out _); + } + + /// + /// 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. + /// + public AudioClip GetRandomSoundClip(string soundName, out float volume) { AudioClip clip; + volume = 1f; if (soundName.EqualsIgnoreCase(NoSoundName)) { @@ -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; diff --git a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs index 6234f3a0d..dc587ddc8 100644 --- a/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Vm/VmService.cs @@ -114,8 +114,7 @@ public List 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", diff --git a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs index 8caa17e7b..d6ac3c223 100644 --- a/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs +++ b/Assets/Gothic-VR/Scripts/Adapters/Vob/VobItem/VRMouth.cs @@ -90,7 +90,7 @@ private void OnTriggerEnter(Collider other) Logger.Log($"Eating item: {go.name}", LogCat.VR); var destroyTime = 1f; - if (TryExtractSfx(item, out var clip)) + if (TryExtractSfx(item, out var clip, out var volume)) destroyTime = clip.length; else Logger.LogWarning("No SFX for eating/drinking item found. Removing item anyways after 1 second.", LogCat.VR); @@ -98,7 +98,7 @@ private void OnTriggerEnter(Collider other) _objectsInDestroyGracePeriod.Add(rootGo); // Smoking: a drag first, then the sound and the smoke (_smokeStartDelay). var startDelay = IsSmokable(item) ? Mathf.Max(0f, _smokeStartDelay) : 0f; - StartCoroutine(ConsumeObject(rootGo, clip, destroyTime, startDelay)); + StartCoroutine(ConsumeObject(rootGo, clip, volume, destroyTime, startDelay)); if (IsSmokable(item)) StartCoroutine(ExhaleSmoke(item, destroyTime, startDelay)); @@ -196,9 +196,11 @@ private bool TryGetItemToEat(GameObject go, out ItemInstance item) return true; } - private bool TryExtractSfx(ItemInstance item, out AudioClip clip) + /// Gothic's volume of the sound (SMOKE_JOINT 20 of 127), 0..1. + private bool TryExtractSfx(ItemInstance item, out AudioClip clip, out float volume) { clip = null; + volume = 1f; var animationName = string.Format(_animationSchemeWithSfx, item.SchemeName); var anim = TryGetUseAnimation(item); @@ -226,7 +228,7 @@ private bool TryExtractSfx(ItemInstance item, out AudioClip clip) return false; } - clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound()); + clip = _audioService.CreateAudioClip(sfxContainer.GetRandomSound(out volume)); if (clip == null) return false; @@ -241,13 +243,13 @@ private IAnimation TryGetUseAnimation(ItemInstance item) return mds?.Animations.FirstOrDefault(i => i.Name.EqualsIgnoreCase(animationName)); } - private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float destroyDelay, + private IEnumerator ConsumeObject(GameObject go, [CanBeNull] AudioClip clip, float volume, float destroyDelay, float startDelay = 0f) { if (startDelay > 0f) yield return new WaitForSeconds(startDelay); if (clip != null) - _mouthAudio.PlayOneShot(clip); + _mouthAudio.PlayOneShot(clip, volume * _audioService.SoundVolume); yield return new WaitForSeconds(destroyDelay);