3 using Microsoft.Xna.Framework;
5 using System.Collections.Generic;
8 using System.Threading;
13 static class SoundPlayer
16 private const float MusicLerpSpeed = 1.0f;
17 private const float UpdateMusicInterval = 5.0f;
19 const int MaxMusicChannels = 6;
21 private readonly
static BackgroundMusic[] currentMusic =
new BackgroundMusic[MaxMusicChannels];
23 private readonly
static BackgroundMusic[] targetMusic =
new BackgroundMusic[MaxMusicChannels];
24 private static IEnumerable<BackgroundMusic> musicClips => BackgroundMusic.BackgroundMusicPrefabs;
26 private static BackgroundMusic previousDefaultMusic;
28 private static float updateMusicTimer;
31 private static Sound waterAmbienceIn => SoundPrefab.WaterAmbienceIn.ActivePrefab.
Sound;
32 private static Sound waterAmbienceOut => SoundPrefab.WaterAmbienceOut.ActivePrefab.
Sound;
33 private static Sound waterAmbienceMoving => SoundPrefab.WaterAmbienceMoving.ActivePrefab.
Sound;
34 private static readonly HashSet<SoundChannel> waterAmbienceChannels =
new HashSet<SoundChannel>();
36 private static float ambientSoundTimer;
37 private static Vector2 ambientSoundInterval =
new Vector2(20.0f, 40.0f);
40 private static Hull hullSoundSource;
41 private static float hullSoundTimer;
42 private static Vector2 hullSoundInterval =
new Vector2(45.0f, 90.0f);
45 private static float[] targetFlowLeft, targetFlowRight;
46 public static IReadOnlyList<SoundPrefab> FlowSounds => SoundPrefab.FlowSounds;
47 public static IReadOnlyList<SoundPrefab> SplashSounds => SoundPrefab.SplashSounds;
49 private static float[] flowVolumeLeft;
50 private static float[] flowVolumeRight;
52 const float FlowSoundRange = 1500.0f;
53 const float MaxFlowStrength = 400.0f;
56 private static float[] fireVolumeLeft;
57 private static float[] fireVolumeRight;
59 const float FireSoundRange = 1000.0f;
60 const float FireSoundMediumLimit = 100.0f;
61 const float FireSoundLargeLimit = 200.0f;
62 const int fireSizes = 3;
63 private static string[] fireSoundTags =
new string[fireSizes] {
"fire",
"firemedium",
"firelarge" };
66 private static IEnumerable<DamageSound> damageSounds => DamageSound.DamageSoundPrefabs;
68 private static bool firstTimeInMainMenu =
true;
70 private static Sound startUpSound => SoundPrefab.StartupSound.ActivePrefab.
Sound;
72 public static Identifier OverrideMusicType
78 public static float? OverrideMusicDuration;
80 public static void Update(
float deltaTime)
82 UpdateMusic(deltaTime);
83 if (flowSoundChannels ==
null || flowSoundChannels.Length != FlowSounds.Count)
86 flowVolumeLeft =
new float[FlowSounds.Count];
87 flowVolumeRight =
new float[FlowSounds.Count];
88 targetFlowLeft =
new float[FlowSounds.Count];
89 targetFlowRight =
new float[FlowSounds.Count];
91 if (fireSoundChannels ==
null || fireSoundChannels.Length != fireSizes)
94 fireVolumeLeft =
new float[fireSizes];
95 fireVolumeRight =
new float[fireSizes];
99 if (
Submarine.MainSub ==
null || Screen.Selected != GameMain.GameScreen)
101 foreach (var chn
in waterAmbienceChannels.Concat(flowSoundChannels).Concat(fireSoundChannels))
105 fireVolumeLeft[0] = 0.0f; fireVolumeLeft[1] = 0.0f;
106 fireVolumeRight[0] = 0.0f; fireVolumeRight[1] = 0.0f;
108 hullSoundSource =
null;
112 float ambienceVolume = 0.8f;
115 AnimController animController =
Character.Controlled.AnimController;
116 if (animController.HeadInWater)
118 ambienceVolume = 1.0f;
119 float limbSpeed = animController.Limbs[0].LinearVelocity.Length();
120 if (MathUtils.IsValid(limbSpeed))
122 ambienceVolume += limbSpeed;
127 UpdateWaterAmbience(ambienceVolume, deltaTime);
128 UpdateWaterFlowSounds(deltaTime);
129 UpdateRandomAmbience(deltaTime);
130 UpdateHullSounds(deltaTime);
131 UpdateFireSounds(deltaTime);
134 private static void UpdateWaterAmbience(
float ambienceVolume,
float deltaTime)
136 if (GameMain.SoundManager.Disabled || GameMain.GameScreen?.Cam ==
null) {
return; }
139 float movementSoundVolume = 0.0f;
141 float insideSubFactor = 0.0f;
142 foreach (Submarine sub
in Submarine.Loaded)
144 if (sub ==
null || sub.Removed) {
continue; }
145 float movementFactor = (sub.Velocity == Vector2.Zero) ? 0.0f : sub.Velocity.Length() / 10.0f;
146 movementFactor = MathHelper.Clamp(movementFactor, 0.0f, 1.0f);
150 float dist = Vector2.Distance(GameMain.GameScreen.Cam.WorldViewCenter, sub.WorldPosition);
151 movementFactor /= Math.Max(dist / 1000.0f, 1.0f);
152 insideSubFactor = Math.Max(1.0f / Math.Max(dist / 1000.0f, 1.0f), insideSubFactor);
156 insideSubFactor = 1.0f;
162 insideSubFactor -=
Character.Controlled.PressureTimer / 100.0f;
165 movementSoundVolume = Math.Max(movementSoundVolume, movementFactor);
166 if (!MathUtils.IsValid(movementSoundVolume))
168 string errorMsg =
"Failed to update water ambience volume - submarine's movement value invalid (" + movementSoundVolume +
", sub velocity: " + sub.Velocity +
")";
169 DebugConsole.Log(errorMsg);
170 GameAnalyticsManager.AddErrorEventOnce(
"SoundPlayer.UpdateWaterAmbience:InvalidVolume", GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
171 movementSoundVolume = 0.0f;
173 if (!MathUtils.IsValid(insideSubFactor))
175 string errorMsg =
"Failed to update water ambience volume - inside sub value invalid (" + insideSubFactor +
")";
176 DebugConsole.Log(errorMsg);
177 GameAnalyticsManager.AddErrorEventOnce(
"SoundPlayer.UpdateWaterAmbience:InvalidVolume", GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
178 insideSubFactor = 0.0f;
182 void updateWaterAmbience(
Sound sound,
float volume)
184 SoundChannel chn = waterAmbienceChannels.FirstOrDefault(c => c.Sound == sound);
185 if (Level.Loaded !=
null)
187 volume *= Level.Loaded.GenerationParams.WaterAmbienceVolume;
191 if (volume < 0.01f) {
return; }
192 if (chn is not
null) { waterAmbienceChannels.Remove(chn); }
193 chn = sound.
Play(volume,
"waterambience");
195 waterAmbienceChannels.Add(chn);
199 chn.
Gain += deltaTime * Math.Sign(volume - chn.
Gain);
200 if (chn.
Gain < 0.01f)
216 updateWaterAmbience(waterAmbienceIn, ambienceVolume * (1.0f - movementSoundVolume) * insideSubFactor);
217 updateWaterAmbience(waterAmbienceMoving, ambienceVolume * movementSoundVolume * insideSubFactor);
218 updateWaterAmbience(waterAmbienceOut, 1.0f - insideSubFactor);
221 private static void UpdateWaterFlowSounds(
float deltaTime)
223 if (FlowSounds.Count == 0) {
return; }
225 for (
int i = 0; i < targetFlowLeft.Length; i++)
227 targetFlowLeft[i] = 0.0f;
228 targetFlowRight[i] = 0.0f;
231 Vector2 listenerPos =
new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y);
232 foreach (Gap gap
in Gap.GapList)
234 Vector2 diff = gap.WorldPosition - listenerPos;
235 if (Math.Abs(diff.X) < FlowSoundRange && Math.Abs(diff.Y) < FlowSoundRange)
237 if (gap.Open < 0.01f || gap.LerpedFlowForce.LengthSquared() < 100.0f) {
continue; }
238 float gapFlow = Math.Abs(gap.LerpedFlowForce.X) + Math.Abs(gap.LerpedFlowForce.Y) * 2.5f;
239 if (!gap.IsRoomToRoom) { gapFlow *= 2.0f; }
240 if (gapFlow < 10.0f) {
continue; }
242 if (gap.linkedTo.Count == 2 && gap.linkedTo[0] is Hull hull1 && gap.linkedTo[1] is Hull hull2)
245 if (hull1.linkedTo.Contains(hull2)) {
continue; }
246 if (hull1.linkedTo.Any(h => h.linkedTo.Contains(hull1) && h.linkedTo.Contains(hull2))) {
continue; }
247 if (hull2.linkedTo.Any(h => h.linkedTo.Contains(hull1) && h.linkedTo.Contains(hull2))) {
continue; }
250 int flowSoundIndex = (int)Math.Floor(MathHelper.Clamp(gapFlow / MaxFlowStrength, 0, FlowSounds.Count));
251 flowSoundIndex = Math.Min(flowSoundIndex, FlowSounds.Count - 1);
253 float dist = diff.Length();
254 float distFallOff = dist / FlowSoundRange;
255 if (distFallOff >= 0.99f) {
continue; }
257 float gain = MathHelper.Clamp(gapFlow / 100.0f, 0.0f, 1.0f);
262 targetFlowLeft[flowSoundIndex] += gain - distFallOff;
266 targetFlowRight[flowSoundIndex] += gain - distFallOff;
271 if (
Character.Controlled?.CharacterHealth?.GetAffliction(
"psychosis") is AfflictionPsychosis psychosis)
273 if (psychosis.CurrentFloodType == AfflictionPsychosis.FloodType.Minor)
275 targetFlowLeft[0] = Math.Max(targetFlowLeft[0], 1.0f);
276 targetFlowRight[0] = Math.Max(targetFlowRight[0], 1.0f);
278 else if (psychosis.CurrentFloodType == AfflictionPsychosis.FloodType.Major)
280 targetFlowLeft[FlowSounds.Count - 1] = Math.Max(targetFlowLeft[FlowSounds.Count - 1], 1.0f);
281 targetFlowRight[FlowSounds.Count - 1] = Math.Max(targetFlowRight[FlowSounds.Count - 1], 1.0f);
285 for (
int i = 0; i < FlowSounds.Count; i++)
287 flowVolumeLeft[i] = (targetFlowLeft[i] < flowVolumeLeft[i]) ?
288 Math.Max(targetFlowLeft[i], flowVolumeLeft[i] - deltaTime) :
289 Math.Min(targetFlowLeft[i], flowVolumeLeft[i] + deltaTime * 10.0f);
290 flowVolumeRight[i] = (targetFlowRight[i] < flowVolumeRight[i]) ?
291 Math.Max(targetFlowRight[i], flowVolumeRight[i] - deltaTime) :
292 Math.Min(targetFlowRight[i], flowVolumeRight[i] + deltaTime * 10.0f);
294 if (flowVolumeLeft[i] < 0.05f && flowVolumeRight[i] < 0.05f)
296 if (flowSoundChannels[i] !=
null)
298 flowSoundChannels[i].
Dispose();
299 flowSoundChannels[i] =
null;
304 if (FlowSounds[i]?.
Sound ==
null) {
continue; }
305 Vector2 soundPos =
new Vector2(GameMain.SoundManager.ListenerPosition.X + (flowVolumeRight[i] - flowVolumeLeft[i]) * 100, GameMain.SoundManager.ListenerPosition.Y);
306 if (flowSoundChannels[i] ==
null || !flowSoundChannels[i].IsPlaying)
308 flowSoundChannels[i] = FlowSounds[i].
Sound.
Play(1.0f, FlowSoundRange, soundPos);
309 flowSoundChannels[i].
Looping =
true;
311 flowSoundChannels[i].
Gain = Math.Max(flowVolumeRight[i], flowVolumeLeft[i]);
312 flowSoundChannels[i].
Position =
new Vector3(soundPos, 0.0f);
317 private static void UpdateFireSounds(
float deltaTime)
319 for (
int i = 0; i < fireVolumeLeft.Length; i++)
321 fireVolumeLeft[i] = 0.0f;
322 fireVolumeRight[i] = 0.0f;
325 Vector2 listenerPos =
new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y);
326 foreach (Hull hull
in Hull.HullList)
328 foreach (FireSource fs
in hull.FireSources)
332 foreach (FireSource fs
in hull.FakeFireSources)
338 for (
int i = 0; i < fireVolumeLeft.Length; i++)
340 if (fireVolumeLeft[i] < 0.05f && fireVolumeRight[i] < 0.05f)
342 if (fireSoundChannels[i] !=
null)
345 fireSoundChannels[i] =
null;
350 Vector2 soundPos =
new Vector2(GameMain.SoundManager.ListenerPosition.X + (fireVolumeRight[i] - fireVolumeLeft[i]) * 100, GameMain.SoundManager.ListenerPosition.Y);
351 if (fireSoundChannels[i] ==
null || !fireSoundChannels[i].IsPlaying)
353 fireSoundChannels[i] = GetSound(fireSoundTags[i])?.Play(1.0f, FlowSoundRange, soundPos);
354 if (fireSoundChannels[i] ==
null) {
continue; }
355 fireSoundChannels[i].
Looping =
true;
357 fireSoundChannels[i].
Gain = Math.Max(fireVolumeRight[i], fireVolumeLeft[i]);
358 fireSoundChannels[i].
Position =
new Vector3(soundPos, 0.0f);
362 void AddFireVolume(FireSource fs)
364 Vector2 diff = fs.WorldPosition + fs.Size / 2 - listenerPos;
365 if (Math.Abs(diff.X) < FireSoundRange && Math.Abs(diff.Y) < FireSoundRange)
367 Vector2 diffLeft = (fs.WorldPosition +
new Vector2(fs.Size.X, fs.Size.Y / 2)) - listenerPos;
368 if (Math.Abs(diff.X) < fs.Size.X / 2.0f) { diffLeft.X = 0.0f; }
371 float distFallOffLeft = diffLeft.Length() / FireSoundRange;
372 if (distFallOffLeft < 0.99f)
374 fireVolumeLeft[0] += (1.0f - distFallOffLeft);
375 if (fs.Size.X > FireSoundLargeLimit)
377 fireVolumeLeft[2] += (1.0f - distFallOffLeft) * ((fs.Size.X - FireSoundLargeLimit) / FireSoundLargeLimit);
379 else if (fs.Size.X > FireSoundMediumLimit)
381 fireVolumeLeft[1] += (1.0f - distFallOffLeft) * ((fs.Size.X - FireSoundMediumLimit) / FireSoundMediumLimit);
386 Vector2 diffRight = (fs.WorldPosition +
new Vector2(0.0f, fs.Size.Y / 2)) - listenerPos;
387 if (Math.Abs(diff.X) < fs.Size.X / 2.0f) { diffRight.X = 0.0f; }
388 if (diffRight.X >= 0)
390 float distFallOffRight = diffRight.Length() / FireSoundRange;
391 if (distFallOffRight < 0.99f)
393 fireVolumeRight[0] += 1.0f - distFallOffRight;
394 if (fs.Size.X > FireSoundLargeLimit)
396 fireVolumeRight[2] += (1.0f - distFallOffRight) * ((fs.Size.X - FireSoundLargeLimit) / FireSoundLargeLimit);
398 else if (fs.Size.X > FireSoundMediumLimit)
400 fireVolumeRight[1] += (1.0f - distFallOffRight) * ((fs.Size.X - FireSoundMediumLimit) / FireSoundMediumLimit);
408 private static void UpdateRandomAmbience(
float deltaTime)
410 if (ambientSoundTimer > 0.0f)
412 ambientSoundTimer -= deltaTime;
418 new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y) + Rand.Vector(100.0f),
419 Rand.Range(0.5f, 1.0f),
422 ambientSoundTimer = Rand.Range(ambientSoundInterval.X, ambientSoundInterval.Y);
426 private static void UpdateHullSounds(
float deltaTime)
428 if (hullSoundChannel !=
null && hullSoundChannel.
IsPlaying && hullSoundSource !=
null)
430 hullSoundChannel.
Position =
new Vector3(hullSoundSource.WorldPosition, 0.0f);
431 hullSoundChannel.
Gain = GetHullSoundVolume(hullSoundSource.Submarine);
434 if (hullSoundTimer > 0.0f)
436 hullSoundTimer -= deltaTime;
440 if (!Level.IsLoadedFriendlyOutpost &&
Character.Controlled?.CurrentHull?.Submarine is Submarine sub &&
441 sub.Info !=
null && !sub.Info.IsOutpost)
443 hullSoundSource =
Character.Controlled.CurrentHull;
444 hullSoundChannel = PlaySound(
"hull", hullSoundSource.WorldPosition, volume: GetHullSoundVolume(sub), range: 1500.0f);
445 hullSoundTimer = Rand.Range(hullSoundInterval.X, hullSoundInterval.Y);
449 hullSoundTimer = 5.0f;
453 static float GetHullSoundVolume(Submarine sub)
455 var depth = Level.Loaded ==
null ? 0.0f : Math.Abs(sub.Position.Y - Level.Loaded.Size.Y) * Physics.DisplayToRealWorldRatio;
456 return Math.Clamp((depth - 800.0f) / 1500.0f, 0.4f, 1.0f);
460 public static Sound GetSound(
string soundTag)
462 var matchingSounds = SoundPrefab.Prefabs.Where(p => p.ElementName == soundTag);
463 if (!matchingSounds.Any())
return null;
465 return matchingSounds.GetRandomUnsynced().
Sound;
471 public static SoundChannel PlaySound(
string soundTag,
float volume = 1.0f)
473 var sound = GetSound(soundTag);
474 return sound?.Play(volume);
480 public static SoundChannel PlaySound(
string soundTag, Vector2 position,
float? volume =
null,
float? range =
null, Hull hullGuess =
null)
482 var sound = GetSound(soundTag);
483 if (sound ==
null) {
return null; }
484 return PlaySound(sound, position, volume ?? sound.BaseGain, range ?? sound.BaseFar, 1.0f, hullGuess);
487 public static SoundChannel PlaySound(
Sound sound, Vector2 position,
float? volume =
null,
float? range =
null,
float? freqMult =
null, Hull hullGuess =
null,
bool ignoreMuffling =
false)
491 string errorMsg =
"Error in SoundPlayer.PlaySound (sound was null)\n" + Environment.StackTrace.CleanupStackTrace();
492 GameAnalyticsManager.AddErrorEventOnce(
"SoundPlayer.PlaySound:SoundNull" + Environment.StackTrace.CleanupStackTrace(), GameAnalyticsManager.ErrorSeverity.Error, errorMsg);
496 float far = range ?? sound.
BaseFar;
498 if (Vector2.DistanceSquared(
new Vector2(GameMain.SoundManager.ListenerPosition.X, GameMain.SoundManager.ListenerPosition.Y), position) > far * far)
502 bool muffle = !ignoreMuffling && ShouldMuffleSound(
Character.Controlled, position, far, hullGuess);
503 return sound.
Play(volume ?? sound.
BaseGain, far, freqMult ?? 1.0f, position, muffle: muffle);
506 public static void DisposeDisabledMusic()
508 bool musicDisposed =
false;
509 for (
int i = 0; i < currentMusic.Length; i++)
511 var music = currentMusic[i];
512 if (music is
null) {
continue; }
514 if (!SoundPrefab.Prefabs.Contains(music))
517 musicDisposed =
true;
518 currentMusic[i] =
null;
522 for (
int i = 0; i < targetMusic.Length; i++)
524 var music = targetMusic[i];
525 if (music is
null) {
continue; }
527 if (!SoundPrefab.Prefabs.Contains(music))
529 targetMusic[i] =
null;
533 if (musicDisposed) { Thread.Sleep(60); }
536 public static void ForceMusicUpdate()
538 updateMusicTimer = 0.0f;
541 private static void UpdateMusic(
float deltaTime)
543 if (musicClips ==
null || (GameMain.SoundManager?.Disabled ??
true)) {
return; }
545 if (OverrideMusicType !=
null && OverrideMusicDuration.HasValue)
547 OverrideMusicDuration -= deltaTime;
548 if (OverrideMusicDuration <= 0.0f)
550 OverrideMusicType = Identifier.Empty;
551 OverrideMusicDuration =
null;
555 int noiseLoopIndex = 1;
557 updateMusicTimer -= deltaTime;
558 if (updateMusicTimer <= 0.0f)
561 Identifier currentMusicType = GetCurrentMusicType();
562 float currentIntensity = GameMain.GameSession?.EventManager !=
null ?
563 GameMain.GameSession.EventManager.MusicIntensity * 100.0f : 0.0f;
565 IEnumerable<BackgroundMusic> suitableMusic = GetSuitableMusicClips(currentMusicType, currentIntensity);
566 int mainTrackIndex = 0;
567 if (suitableMusic.None())
569 targetMusic[mainTrackIndex] =
null;
572 else if (targetMusic[mainTrackIndex] ==
null || currentMusic[mainTrackIndex] ==
null || !currentMusic[mainTrackIndex].IsPlaying() || !suitableMusic.Any(m => m == currentMusic[mainTrackIndex]))
574 if (currentMusicType ==
"default")
576 if (previousDefaultMusic ==
null)
578 targetMusic[mainTrackIndex] = previousDefaultMusic = suitableMusic.GetRandomUnsynced();
582 targetMusic[mainTrackIndex] = previousDefaultMusic;
587 targetMusic[mainTrackIndex] = suitableMusic.GetRandomUnsynced();
591 if (Level.Loaded !=
null && (Level.Loaded.Type == LevelData.LevelType.LocationConnection || Level.Loaded.GenerationParams.PlayNoiseLoopInOutpostLevel))
593 Identifier biome = Level.Loaded.LevelData.Biome.Identifier;
594 if (Level.Loaded.IsEndBiome && GameMain.GameSession?.Campaign is CampaignMode campaign)
597 if (!campaign.Map.EndLocations.Contains(Level.Loaded.StartLocation))
599 biome = Level.Loaded.StartLocation.Biome.Identifier;
604 IEnumerable<BackgroundMusic> suitableNoiseLoops = Screen.Selected == GameMain.GameScreen ?
605 GetSuitableMusicClips(biome, currentIntensity) :
606 Enumerable.
Empty<BackgroundMusic>();
607 if (suitableNoiseLoops.Count() == 0)
609 targetMusic[noiseLoopIndex] =
null;
612 else if (targetMusic[noiseLoopIndex] ==
null || currentMusic[noiseLoopIndex] ==
null || !suitableNoiseLoops.Any(m => m == currentMusic[noiseLoopIndex]))
614 targetMusic[noiseLoopIndex] = suitableNoiseLoops.GetRandomUnsynced();
619 targetMusic[noiseLoopIndex] =
null;
622 IEnumerable<BackgroundMusic> suitableTypeAmbiences = GetSuitableMusicClips($
"{currentMusicType}ambience".ToIdentifier(), currentIntensity);
623 int typeAmbienceTrackIndex = 2;
624 if (suitableTypeAmbiences.None())
626 targetMusic[typeAmbienceTrackIndex] =
null;
629 else if (targetMusic[typeAmbienceTrackIndex] ==
null || currentMusic[typeAmbienceTrackIndex] ==
null || !currentMusic[typeAmbienceTrackIndex].IsPlaying() || suitableTypeAmbiences.None(m => m == currentMusic[typeAmbienceTrackIndex]))
631 targetMusic[typeAmbienceTrackIndex] = suitableTypeAmbiences.GetRandomUnsynced();
634 IEnumerable<BackgroundMusic> suitableIntensityMusic = Enumerable.Empty<BackgroundMusic>();
635 BackgroundMusic mainTrack = targetMusic[mainTrackIndex];
636 if (mainTrack is not { MuteIntensityTracks:
true } && Screen.Selected == GameMain.GameScreen)
638 float intensity = currentIntensity;
639 if (mainTrack?.ForceIntensityTrack !=
null)
641 intensity = mainTrack.ForceIntensityTrack.Value;
643 suitableIntensityMusic = GetSuitableMusicClips(
"intensity".ToIdentifier(), intensity);
646 int intensityTrackStartIndex = 3;
647 for (
int i = intensityTrackStartIndex; i < MaxMusicChannels; i++)
650 if (targetMusic[i] !=
null && !suitableIntensityMusic.Any(m => m == targetMusic[i]))
652 targetMusic[i] =
null;
656 foreach (BackgroundMusic intensityMusic
in suitableIntensityMusic)
659 if (targetMusic.Any(m => m !=
null && m == intensityMusic)) {
continue; }
661 for (
int i = intensityTrackStartIndex; i < MaxMusicChannels; i++)
663 if (targetMusic[i] ==
null)
665 targetMusic[i] = intensityMusic;
672 updateMusicTimer = UpdateMusicInterval;
675 int activeTrackCount = targetMusic.Count(m => m !=
null);
676 for (
int i = 0; i < MaxMusicChannels; i++)
679 if (targetMusic[i] ==
null)
681 if (musicChannel[i] !=
null && musicChannel[i].IsPlaying)
684 musicChannel[i].Gain = MathHelper.Lerp(musicChannel[i].Gain, 0.0f, MusicLerpSpeed * deltaTime);
685 if (musicChannel[i].Gain < 0.01f) { DisposeMusicChannel(i); }
689 else if (!musicClips.Any(mc => mc == targetMusic[i]))
691 targetMusic[i] = GetSuitableMusicClips(targetMusic[i].Type, 0.0f).GetRandomUnsynced();
694 else if (currentMusic[i] ==
null || targetMusic[i] != currentMusic[i])
697 if (musicChannel[i] !=
null && musicChannel[i].IsPlaying)
699 musicChannel[i].Gain = MathHelper.Lerp(musicChannel[i].Gain, 0.0f, MusicLerpSpeed * deltaTime);
700 if (musicChannel[i].Gain < 0.01f) { DisposeMusicChannel(i); }
703 if (currentMusic[i] ==
null || (musicChannel[i] ==
null || !musicChannel[i].IsPlaying))
705 DisposeMusicChannel(i);
707 currentMusic[i] = targetMusic[i];
708 musicChannel[i] = currentMusic[i].Sound.Play(0.0f, i == noiseLoopIndex ?
"default" :
"music");
709 if (targetMusic[i].ContinueFromPreviousTime)
711 musicChannel[i].StreamSeekPos = targetMusic[i].PreviousTime;
713 else if (targetMusic[i].StartFromRandomTime)
715 musicChannel[i].StreamSeekPos =
716 (int)(musicChannel[i].MaxStreamSeekPos * Rand.Range(0.0f, 1.0f, Rand.RandSync.Unsynced));
718 musicChannel[i].Looping =
true;
724 if (musicChannel[i] ==
null || !musicChannel[i].IsPlaying)
726 musicChannel[i]?.Dispose();
727 musicChannel[i] = currentMusic[i].Sound.Play(0.0f, i == noiseLoopIndex ?
"default" :
"music");
728 musicChannel[i].Looping =
true;
730 float targetGain = targetMusic[i].Volume;
731 if (targetMusic[i].DuckVolume)
733 targetGain *= (float)Math.Sqrt(1.0f / activeTrackCount);
735 musicChannel[i].Gain = MathHelper.Lerp(musicChannel[i].Gain, targetGain, MusicLerpSpeed * deltaTime);
740 private static double lastMusicLogTime;
741 const double MusicLogInterval = 60.0;
742 private static void LogCurrentMusic()
744 if (Screen.Selected != GameMain.GameScreen) {
return; }
745 if (Timing.TotalTime < lastMusicLogTime + MusicLogInterval) {
return; }
746 for (
int i = 0; i < musicChannel.Length; i++)
748 if (musicChannel[i] !=
null &&
749 musicChannel[i].IsPlaying &&
750 musicChannel[i].
Sound?.Filename !=
null)
752 GameAnalyticsManager.AddDesignEvent(
754 Path.GetFileNameWithoutExtension(musicChannel[i].Sound.Filename.Replace(
":",
string.Empty).Replace(
" ",
string.Empty)));
757 lastMusicLogTime = Timing.TotalTime;
760 private static void DisposeMusicChannel(
int index)
762 var clip = musicClips.FirstOrDefault(m => m.Sound == musicChannel[index]?.Sound);
765 if (clip.ContinueFromPreviousTime) { clip.PreviousTime = musicChannel[index].StreamSeekPos; }
768 musicChannel[index]?.Dispose(); musicChannel[index] =
null;
769 currentMusic[index] =
null;
772 private static IEnumerable<BackgroundMusic> GetSuitableMusicClips(Identifier musicType,
float currentIntensity)
774 return musicClips.Where(music => IsSuitableMusicClip(music, musicType, currentIntensity));
777 private static bool IsSuitableMusicClip(BackgroundMusic music, Identifier musicType,
float currentIntensity)
781 music.Type == musicType &&
782 currentIntensity >= music.IntensityRange.X &&
783 currentIntensity <= music.IntensityRange.Y;
786 private static Identifier GetCurrentMusicType()
788 if (OverrideMusicType !=
null) {
return OverrideMusicType; }
790 if (Screen.Selected ==
null) {
return "menu".ToIdentifier(); }
792 if (Screen.Selected is { IsEditor: true } || GameMain.GameSession?.GameMode is TestGameMode || Screen.Selected == GameMain.NetLobbyScreen)
794 return "editor".ToIdentifier();
797 if (Screen.Selected != GameMain.GameScreen)
799 previousDefaultMusic =
null;
800 return (firstTimeInMainMenu ?
"menu" :
"default").ToIdentifier();
803 firstTimeInMainMenu =
false;
805 if (GameMain.GameSession !=
null)
807 foreach (var mission
in GameMain.GameSession.Missions)
809 var missionMusic = mission.GetOverrideMusicType();
810 if (!missionMusic.IsEmpty) {
return missionMusic; }
816 if (Level.Loaded !=
null && Level.Loaded.Ruins !=
null &&
817 Level.Loaded.Ruins.Any(r => r.Area.Contains(
Character.Controlled.WorldPosition)))
819 return "ruins".ToIdentifier();
822 if (
Character.Controlled.Submarine?.Info?.IsWreck ??
false)
824 return "wreck".ToIdentifier();
827 if (Level.IsLoadedOutpost)
830 var locationType = Level.Loaded.StartLocation?.Type?.Identifier;
831 if (locationType.HasValue && locationType != Identifier.Empty && musicClips.Any(c => c.Type == locationType))
833 return locationType.Value;
838 if (Level.Loaded is { IsEndBiome: true })
840 return "endlevel".ToIdentifier();
844 if (targetSubmarine !=
null && targetSubmarine.AtDamageDepth)
846 return "deep".ToIdentifier();
848 if (GameMain.GameScreen !=
null && Screen.Selected == GameMain.GameScreen &&
Submarine.MainSub !=
null &&
849 Level.Loaded !=
null && Level.Loaded.GetRealWorldDepth(GameMain.GameScreen.Cam.Position.Y) >
Submarine.MainSub.RealWorldCrushDepth)
851 return "deep".ToIdentifier();
854 if (targetSubmarine !=
null)
856 float floodedArea = 0.0f;
857 float totalArea = 0.0f;
858 foreach (Hull hull
in Hull.HullList)
860 if (hull.Submarine != targetSubmarine) {
continue; }
861 floodedArea += hull.WaterVolume;
862 totalArea += hull.Volume;
865 if (totalArea > 0.0f && floodedArea / totalArea > 0.25f) {
return "flooded".ToIdentifier(); }
868 float intensity = (GameMain.GameSession?.EventManager?.MusicIntensity ?? 0) * 100.0f;
869 bool anyMonsterMusicAvailable =
870 musicClips.Any(m => IsSuitableMusicClip(m,
"monster".ToIdentifier(), intensity) || IsSuitableMusicClip(m,
"monsterambience".ToIdentifier(), intensity));
872 if (anyMonsterMusicAvailable)
874 float enemyDistThreshold = 5000.0f;
875 if (targetSubmarine !=
null)
877 enemyDistThreshold = Math.Max(enemyDistThreshold, Math.Max(targetSubmarine.Borders.Width, targetSubmarine.Borders.Height) * 2.0f);
879 foreach (Character character
in Character.CharacterList)
881 if (character.IsDead || !character.Enabled) {
continue; }
882 if (character.AIController is not EnemyAIController { Enabled:
true } enemyAI) {
continue; }
883 if (!enemyAI.AttackHumans && !enemyAI.AttackRooms) {
continue; }
885 if (targetSubmarine !=
null)
887 if (Vector2.DistanceSquared(character.WorldPosition, targetSubmarine.WorldPosition) < enemyDistThreshold * enemyDistThreshold)
889 return "monster".ToIdentifier();
894 if (Vector2.DistanceSquared(character.WorldPosition,
Character.Controlled.WorldPosition) < enemyDistThreshold * enemyDistThreshold)
896 return "monster".ToIdentifier();
903 if (GameMain.GameSession !=
null)
907 return "levelend".ToIdentifier();
909 if (GameMain.GameSession.RoundDuration < 120.0 &&
910 Level.Loaded?.Type == LevelData.LevelType.LocationConnection)
912 return "start".ToIdentifier();
916 return "default".ToIdentifier();
919 public static bool ShouldMuffleSound(Character listener, Vector2 soundWorldPos,
float range, Hull hullGuess)
921 if (listener ==
null)
return false;
923 float lowpassHFGain = 1.0f;
924 AnimController animController = listener.AnimController;
925 if (animController.HeadInWater)
927 lowpassHFGain = 0.2f;
929 lowpassHFGain *=
Character.Controlled.LowPassMultiplier;
930 if (lowpassHFGain < 0.5f)
return true;
932 Hull targetHull = Hull.FindHull(soundWorldPos, hullGuess,
true);
933 if (listener.CurrentHull ==
null || targetHull ==
null)
935 return listener.CurrentHull != targetHull;
937 Vector2 soundPos = soundWorldPos;
938 if (targetHull.Submarine !=
null)
940 soundPos += -targetHull.Submarine.WorldPosition + targetHull.Submarine.HiddenSubPosition;
942 return listener.CurrentHull.GetApproximateDistance(listener.Position, soundPos, targetHull, range) > range;
945 public static void PlaySplashSound(Vector2 worldPosition,
float strength)
947 if (SplashSounds.Count == 0) {
return; }
948 int splashIndex = MathHelper.Clamp((
int)(strength + Rand.Range(-2.0f, 2.0f)), 0, SplashSounds.Count - 1);
949 float range = 800.0f;
950 SplashSounds[splashIndex].Sound?.Play(1.0f, range, worldPosition, muffle: ShouldMuffleSound(
Character.Controlled, worldPosition, range,
null));
953 public static void PlayDamageSound(
string damageType,
float damage, PhysicsBody body)
955 Vector2 bodyPosition = body.DrawPosition;
956 PlayDamageSound(damageType, damage, bodyPosition, 800.0f);
959 public static void PlayDamageSound(
string damageType,
float damage, Vector2 position,
float range = 2000.0f, IEnumerable<Identifier> tags =
null)
961 var suitableSounds = damageSounds.Where(s =>
962 s.DamageType == damageType &&
963 (s.RequiredTag.IsEmpty || (tags ==
null ? s.RequiredTag.IsEmpty : tags.Contains(s.RequiredTag))));
966 if (suitableSounds.All(d => damage < d.DamageRange.X)) {
return; }
970 float randomizedDamage = MathHelper.Clamp(damage + Rand.Range(-10.0f, 10.0f), 0.0f, 100.0f);
971 suitableSounds = suitableSounds.Where(s =>
972 s.DamageRange == Vector2.Zero || (randomizedDamage >= s.DamageRange.X && randomizedDamage <= s.DamageRange.Y));
974 var damageSound = suitableSounds.GetRandomUnsynced();
975 damageSound?.Sound?.Play(1.0f, range, position, muffle: !damageSound.IgnoreMuffling && ShouldMuffleSound(
Character.Controlled, position, range,
null));
980 GUISound.GUISoundPrefabs
981 .Where(s => s.Type == soundType)
982 .GetRandomUnsynced()?.Sound?.Play(
null,
"ui");
987 if (soundType.HasValue)
989 PlayUISound(soundType.Value);
float FrequencyMultiplier
float frequencyMultiplier
Sound(SoundManager owner, string filename, bool stream, bool streamsReliably, ContentXElement xElement=null, bool getFullPath=true)
virtual SoundChannel Play(float gain, float range, Vector2 position, bool muffle=false)