/
s_sound.cpp
2633 lines (2329 loc) · 68.2 KB
/
s_sound.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------
//
// Copyright 1993-1996 id Software
// Copyright 1999-2016 Randy Heit
// Copyright 2002-2016 Christoph Oelckers
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
//
//-----------------------------------------------------------------------------
//
// DESCRIPTION: none
//
//-----------------------------------------------------------------------------
/* For code that originates from ZDoom the following applies:
**
**---------------------------------------------------------------------------
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include <stdio.h>
#include <stdlib.h>
#ifdef _WIN32
#include <io.h>
#endif
#include "i_system.h"
#include "i_sound.h"
#include "i_music.h"
#include "s_sound.h"
#include "s_sndseq.h"
#include "s_playlist.h"
#include "c_dispatch.h"
#include "m_random.h"
#include "w_wad.h"
#include "p_local.h"
#include "doomstat.h"
#include "cmdlib.h"
#include "v_video.h"
#include "v_text.h"
#include "a_sharedglobal.h"
#include "gstrings.h"
#include "gi.h"
#include "po_man.h"
#include "serializer.h"
#include "d_player.h"
#include "g_levellocals.h"
#include "vm.h"
#include "g_game.h"
#include "atterm.h"
// MACROS ------------------------------------------------------------------
#ifdef NeXT
// NeXT doesn't need a binary flag in open call
#define O_BINARY 0
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#define NORM_PITCH 128
#define NORM_PRIORITY 64
#define NORM_SEP 0
#define S_PITCH_PERTURB 1
#define S_STEREO_SWING 0.75
// TYPES -------------------------------------------------------------------
enum
{
SOURCE_None, // Sound is always on top of the listener.
SOURCE_Actor, // Sound is coming from an actor.
SOURCE_Sector, // Sound is coming from a sector.
SOURCE_Polyobj, // Sound is coming from a polyobject.
SOURCE_Unattached, // Sound is not attached to any particular emitter.
};
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
extern float S_GetMusicVolume (const char *music);
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
void I_CloseSound();
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
static void S_LoadSound3D(sfxinfo_t *sfx, FSoundLoadBuffer *pBuffer);
static bool S_CheckSoundLimit(sfxinfo_t *sfx, const FVector3 &pos, int near_limit, float limit_range, AActor *actor, int channel);
static bool S_IsChannelUsed(AActor *actor, int channel, int *seen);
static void S_ActivatePlayList(bool goBack);
static void CalcPosVel(FSoundChan *chan, FVector3 *pos, FVector3 *vel);
static void CalcPosVel(int type, const AActor *actor, const sector_t *sector, const FPolyObj *poly,
const float pt[3], int channel, int chanflags, FVector3 *pos, FVector3 *vel);
static void CalcSectorSoundOrg(const DVector3 &listenpos, const sector_t *sec, int channum, FVector3 &res);
static void CalcPolyobjSoundOrg(const DVector3 &listenpos, const FPolyObj *poly, FVector3 &res);
static FSoundChan *S_StartSound(AActor *mover, const sector_t *sec, const FPolyObj *poly,
const FVector3 *pt, int channel, FSoundID sound_id, float volume, float attenuation, FRolloffInfo *rolloff, float spitch);
static void S_SetListener(SoundListener &listener, AActor *listenactor);
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static bool SoundPaused; // whether sound is paused
static int RestartEvictionsAt; // do not restart evicted channels before this time
// PUBLIC DATA DEFINITIONS -------------------------------------------------
int sfx_empty;
FSoundChan *Channels;
FSoundChan *FreeChannels;
FRolloffInfo S_Rolloff;
TArray<uint8_t> S_SoundCurve;
FBoolCVar noisedebug ("noise", false, 0); // [RH] Print sound debugging info?
CUSTOM_CVAR (Int, snd_channels, 128, CVAR_ARCHIVE|CVAR_GLOBALCONFIG) // number of channels available
{
if (self < 64) self = 64;
}
CVAR(Bool, snd_waterreverb, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG)
// CODE --------------------------------------------------------------------
//==========================================================================
//
// S_NoiseDebug
//
// [RH] Print sound debug info. Called by status bar.
//==========================================================================
void S_NoiseDebug (void)
{
FSoundChan *chan;
FVector3 listener;
FVector3 origin;
int y, color;
y = 32 * CleanYfac;
screen->DrawText (NewConsoleFont, CR_YELLOW, 0, y, "*** SOUND DEBUG INFO ***", TAG_DONE);
y += NewConsoleFont->GetHeight();
screen->DrawText (NewConsoleFont, CR_GOLD, 0, y, "name", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 70, y, "x", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 120, y, "y", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 170, y, "z", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 220, y, "vol", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 260, y, "dist", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 300, y, "chan", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 340, y, "pri", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 380, y, "flags", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 460, y, "aud", TAG_DONE);
screen->DrawText (NewConsoleFont, CR_GOLD, 520, y, "pos", TAG_DONE);
y += NewConsoleFont->GetHeight();
if (Channels == NULL)
{
return;
}
listener = players[consoleplayer].camera->SoundPos();
// Display the oldest channel first.
for (chan = Channels; chan->NextChan != NULL; chan = chan->NextChan)
{ }
while (y < SCREENHEIGHT - 16)
{
char temp[32];
CalcPosVel(chan, &origin, NULL);
color = (chan->ChanFlags & CHAN_LOOP) ? CR_BROWN : CR_GREY;
// Name
Wads.GetLumpName (temp, S_sfx[chan->SoundID].lumpnum);
temp[8] = 0;
screen->DrawText (NewConsoleFont, color, 0, y, temp, TAG_DONE);
if (!(chan->ChanFlags & CHAN_IS3D))
{
screen->DrawText(NewConsoleFont, color, 70, y, "---", TAG_DONE); // X
screen->DrawText(NewConsoleFont, color, 120, y, "---", TAG_DONE); // Y
screen->DrawText(NewConsoleFont, color, 170, y, "---", TAG_DONE); // Z
screen->DrawText(NewConsoleFont, color, 260, y, "---", TAG_DONE); // Distance
}
else
{
// X coordinate
mysnprintf(temp, countof(temp), "%.0f", origin.X);
screen->DrawText(NewConsoleFont, color, 70, y, temp, TAG_DONE);
// Y coordinate
mysnprintf(temp, countof(temp), "%.0f", origin.Z);
screen->DrawText(NewConsoleFont, color, 120, y, temp, TAG_DONE);
// Z coordinate
mysnprintf(temp, countof(temp), "%.0f", origin.Y);
screen->DrawText(NewConsoleFont, color, 170, y, temp, TAG_DONE);
// Distance
if (chan->DistanceScale > 0)
{
mysnprintf(temp, countof(temp), "%.0f", (origin - listener).Length());
screen->DrawText(NewConsoleFont, color, 260, y, temp, TAG_DONE);
}
else
{
screen->DrawText(NewConsoleFont, color, 260, y, "---", TAG_DONE);
}
}
// Volume
mysnprintf(temp, countof(temp), "%.2g", chan->Volume);
screen->DrawText(NewConsoleFont, color, 220, y, temp, TAG_DONE);
// Channel
mysnprintf(temp, countof(temp), "%d", chan->EntChannel);
screen->DrawText(NewConsoleFont, color, 300, y, temp, TAG_DONE);
// Priority
mysnprintf(temp, countof(temp), "%d", chan->Priority);
screen->DrawText(NewConsoleFont, color, 340, y, temp, TAG_DONE);
// Flags
mysnprintf(temp, countof(temp), "%s3%sZ%sU%sM%sN%sA%sL%sE%sV",
(chan->ChanFlags & CHAN_IS3D) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_LISTENERZ) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_UI) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_MAYBE_LOCAL) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_NOPAUSE) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_AREA) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_LOOP) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_EVICTED) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK,
(chan->ChanFlags & CHAN_VIRTUAL) ? TEXTCOLOR_GREEN : TEXTCOLOR_BLACK);
screen->DrawText(NewConsoleFont, color, 380, y, temp, TAG_DONE);
// Audibility
mysnprintf(temp, countof(temp), "%.4f", GSnd->GetAudibility(chan));
screen->DrawText(NewConsoleFont, color, 460, y, temp, TAG_DONE);
// Position
mysnprintf(temp, countof(temp), "%u", GSnd->GetPosition(chan));
screen->DrawText(NewConsoleFont, color, 520, y, temp, TAG_DONE);
y += NewConsoleFont->GetHeight();
if (chan->PrevChan == &Channels)
{
break;
}
chan = (FSoundChan *)((size_t)chan->PrevChan - myoffsetof(FSoundChan, NextChan));
}
}
static FString LastLocalSndInfo;
static FString LastLocalSndSeq;
void S_AddLocalSndInfo(int lump);
//==========================================================================
//
// S_Init
//
// Initializes sound stuff, including volume. Sets channels, SFX and
// music volume, allocates channel buffer, and sets S_sfx lookup.
//==========================================================================
void S_Init ()
{
int curvelump;
atterm(S_Shutdown);
// Heretic and Hexen have sound curve lookup tables. Doom does not.
curvelump = Wads.CheckNumForName ("SNDCURVE");
if (curvelump >= 0)
{
S_SoundCurve.Resize(Wads.LumpLength (curvelump));
Wads.ReadLump(curvelump, S_SoundCurve.Data());
}
else
{
S_SoundCurve.Clear();
}
// Free all channels for use.
while (Channels != NULL)
{
S_ReturnChannel(Channels);
}
}
//==========================================================================
//
// S_InitData
//
//==========================================================================
void S_InitData ()
{
LastLocalSndInfo = LastLocalSndSeq = "";
S_ParseSndInfo (false);
S_ParseSndSeq (-1);
}
//==========================================================================
//
// S_Shutdown
//
//==========================================================================
void S_Shutdown ()
{
FSoundChan *chan, *next;
chan = Channels;
while (chan != NULL)
{
next = chan->NextChan;
S_StopChannel(chan);
chan = next;
}
GSnd->UpdateSounds();
for (chan = FreeChannels; chan != NULL; chan = next)
{
next = chan->NextChan;
delete chan;
}
FreeChannels = NULL;
}
//==========================================================================
//
// S_Start
//
// Per level startup code. Kills playing sounds at start of level
// and starts new music.
//==========================================================================
void S_Start ()
{
if (GSnd)
{
// kill all playing sounds at start of level (trust me - a good idea)
S_StopAllChannels();
// Check for local sound definitions. Only reload if they differ
// from the previous ones.
FString LocalSndInfo;
FString LocalSndSeq;
// To be certain better check whether level is valid!
if (primaryLevel->info)
{
LocalSndInfo = primaryLevel->info->SoundInfo;
LocalSndSeq = primaryLevel->info->SndSeq;
}
bool parse_ss = false;
// This level uses a different local SNDINFO
if (LastLocalSndInfo.CompareNoCase(LocalSndInfo) != 0 || !primaryLevel->info)
{
// First delete the old sound list
for(unsigned i = 1; i < S_sfx.Size(); i++)
{
S_UnloadSound(&S_sfx[i]);
}
// Parse the global SNDINFO
S_ParseSndInfo(true);
if (LocalSndInfo.IsNotEmpty())
{
// Now parse the local SNDINFO
int j = Wads.CheckNumForFullName(LocalSndInfo, true);
if (j>=0) S_AddLocalSndInfo(j);
}
// Also reload the SNDSEQ if the SNDINFO was replaced!
parse_ss = true;
}
else if (LastLocalSndSeq.CompareNoCase(LocalSndSeq) != 0)
{
parse_ss = true;
}
if (parse_ss)
{
S_ParseSndSeq(LocalSndSeq.IsNotEmpty()? Wads.CheckNumForFullName(LocalSndSeq, true) : -1);
}
LastLocalSndInfo = LocalSndInfo;
LastLocalSndSeq = LocalSndSeq;
}
}
//==========================================================================
//
// S_PrecacheLevel
//
// Like R_PrecacheLevel, but for sounds.
//
//==========================================================================
void S_PrecacheLevel (FLevelLocals *Level)
{
unsigned int i;
if (GSnd && Level == primaryLevel)
{
for (i = 0; i < S_sfx.Size(); ++i)
{
S_sfx[i].bUsed = false;
}
AActor *actor;
auto iterator = Level->GetThinkerIterator<AActor>();
// Precache all sounds known to be used by the currently spawned actors.
while ( (actor = iterator.Next()) != NULL )
{
IFVIRTUALPTR(actor, AActor, MarkPrecacheSounds)
{
VMValue params[1] = { actor };
VMCall(func, params, 1, nullptr, 0);
}
}
for (auto snd : gameinfo.PrecachedSounds)
{
FSoundID(snd).MarkUsed();
}
// Precache all extra sounds requested by this map.
for (auto snd : primaryLevel->info->PrecacheSounds)
{
FSoundID(snd).MarkUsed();
}
// Don't unload sounds that are playing right now.
for (FSoundChan *chan = Channels; chan != NULL; chan = chan->NextChan)
{
chan->SoundID.MarkUsed();
}
for (i = 1; i < S_sfx.Size(); ++i)
{
if (S_sfx[i].bUsed)
{
S_CacheSound (&S_sfx[i]);
}
}
for (i = 1; i < S_sfx.Size(); ++i)
{
if (!S_sfx[i].bUsed && S_sfx[i].link == sfxinfo_t::NO_LINK)
{
S_UnloadSound (&S_sfx[i]);
}
}
}
}
//==========================================================================
//
// S_CacheSound
//
//==========================================================================
void S_CacheSound (sfxinfo_t *sfx)
{
if (GSnd)
{
if (sfx->bPlayerReserve)
{
return;
}
sfxinfo_t *orig = sfx;
while (!sfx->bRandomHeader && sfx->link != sfxinfo_t::NO_LINK)
{
sfx = &S_sfx[sfx->link];
}
if (sfx->bRandomHeader)
{
S_CacheRandomSound(sfx);
}
else
{
// Since we do not know in what format the sound will be used, we have to cache both.
FSoundLoadBuffer SoundBuffer;
S_LoadSound(sfx, &SoundBuffer);
S_LoadSound3D(sfx, &SoundBuffer);
sfx->bUsed = true;
}
}
}
//==========================================================================
//
// S_UnloadSound
//
//==========================================================================
void S_UnloadSound (sfxinfo_t *sfx)
{
if (sfx->data3d.isValid() && sfx->data != sfx->data3d)
GSnd->UnloadSound(sfx->data3d);
if (sfx->data.isValid())
GSnd->UnloadSound(sfx->data);
if (sfx->data.isValid() || sfx->data3d.isValid())
DPrintf(DMSG_NOTIFY, "Unloaded sound \"%s\" (%td)\n", sfx->name.GetChars(), sfx - &S_sfx[0]);
sfx->data.Clear();
sfx->data3d.Clear();
}
//==========================================================================
//
// S_GetChannel
//
// Returns a free channel for the system sound interface.
//
//==========================================================================
FISoundChannel *S_GetChannel(void *syschan)
{
FSoundChan *chan;
if (FreeChannels != NULL)
{
chan = FreeChannels;
S_UnlinkChannel(chan);
}
else
{
chan = new FSoundChan;
memset(chan, 0, sizeof(*chan));
}
S_LinkChannel(chan, &Channels);
chan->SysChannel = syschan;
return chan;
}
//==========================================================================
//
// S_ReturnChannel
//
// Returns a channel to the free pool.
//
//==========================================================================
void S_ReturnChannel(FSoundChan *chan)
{
S_UnlinkChannel(chan);
memset(chan, 0, sizeof(*chan));
S_LinkChannel(chan, &FreeChannels);
}
//==========================================================================
//
// S_UnlinkChannel
//
//==========================================================================
void S_UnlinkChannel(FSoundChan *chan)
{
*(chan->PrevChan) = chan->NextChan;
if (chan->NextChan != NULL)
{
chan->NextChan->PrevChan = chan->PrevChan;
}
}
//==========================================================================
//
// S_LinkChannel
//
//==========================================================================
void S_LinkChannel(FSoundChan *chan, FSoundChan **head)
{
chan->NextChan = *head;
if (chan->NextChan != NULL)
{
chan->NextChan->PrevChan = &chan->NextChan;
}
*head = chan;
chan->PrevChan = head;
}
// [RH] Split S_StartSoundAtVolume into multiple parts so that sounds can
// be specified both by id and by name. Also borrowed some stuff from
// Hexen and parameters from Quake.
//==========================================================================
//
// CalcPosVel
//
// Retrieves a sound's position and velocity for 3D sounds. This version
// is for an already playing sound.
//
//=========================================================================
static void CalcPosVel(FSoundChan *chan, FVector3 *pos, FVector3 *vel)
{
CalcPosVel(chan->SourceType, chan->Actor, chan->Sector, chan->Poly, chan->Point,
chan->EntChannel, chan->ChanFlags, pos, vel);
}
//=========================================================================
//
// CalcPosVel
//
// This version is for sounds that haven't started yet so have no channel.
//
//=========================================================================
static void CalcPosVel(int type, const AActor *actor, const sector_t *sector,
const FPolyObj *poly, const float pt[3], int channum, int chanflags, FVector3 *pos, FVector3 *vel)
{
if (pos != NULL)
{
DVector3 listenpos;
int pgroup;
AActor *listener = players[consoleplayer].camera;
if (listener != NULL)
{
listenpos = listener->Pos();
*pos = listener->SoundPos();
pgroup = listener->Sector->PortalGroup;
}
else
{
listenpos.Zero();
pos->Zero();
pgroup = 0;
}
// [BL] Moved this case out of the switch statement to make code easier
// on static analysis.
if(type == SOURCE_Unattached)
{
sector_t *sec = primaryLevel->PointInSector(pt[0], pt[2]);
DVector2 disp = primaryLevel->Displacements.getOffset(pgroup, sec->PortalGroup);
pos->X = pt[0] - (float)disp.X;
pos->Y = !(chanflags & CHAN_LISTENERZ) ? pt[1] : (float)listenpos.Z;
pos->Z = pt[2] - (float)disp.Y;
}
else
{
switch (type)
{
case SOURCE_None:
default:
break;
case SOURCE_Actor:
//assert(actor != NULL);
if (actor != NULL)
{
DVector2 disp = primaryLevel->Displacements.getOffset(pgroup, actor->Sector->PortalGroup);
DVector3 posi = actor->Pos() - disp;
*pos = { (float)posi.X, (float)posi.Z, (float)posi.Y };
}
break;
case SOURCE_Sector:
assert(sector != NULL);
if (sector != NULL)
{
DVector2 disp = primaryLevel->Displacements.getOffset(pgroup, sector->PortalGroup);
if (chanflags & CHAN_AREA)
{
// listener must be reversely offset to calculate the proper sound origin.
CalcSectorSoundOrg(listenpos + disp, sector, channum, *pos);
pos->X -= (float)disp.X;
pos->Z -= (float)disp.Y;
}
else
{
pos->X = (float)(sector->centerspot.X - disp.X);
pos->Z = (float)(sector->centerspot.Y - disp.Y);
chanflags |= CHAN_LISTENERZ;
}
}
break;
case SOURCE_Polyobj:
assert(poly != NULL);
if (poly != NULL)
{
DVector2 disp = primaryLevel->Displacements.getOffset(pgroup, poly->CenterSubsector->sector->PortalGroup);
CalcPolyobjSoundOrg(listenpos + disp, poly, *pos);
pos->X -= (float)disp.X;
pos->Z -= (float)disp.Y;
}
break;
}
if ((chanflags & CHAN_LISTENERZ) && players[consoleplayer].camera != NULL)
{
pos->Y = (float)listenpos.Z;
}
}
}
if (vel != NULL)
{
// Only actors maintain velocity information.
if (type == SOURCE_Actor && actor != NULL)
{
vel->X = float(actor->Vel.X * TICRATE);
vel->Y = float(actor->Vel.Z * TICRATE);
vel->Z = float(actor->Vel.Y * TICRATE);
}
else
{
vel->Zero();
}
}
}
//==========================================================================
//
// ValidatePosVel
//
//==========================================================================
inline bool Validate(const float value, const float limit)
{
return value >= -limit && value <= limit;
}
static bool Validate(const FVector3 &value, const float limit, const char *const name, const AActor *const actor)
{
const bool valid =
Validate(value.X, limit)
&& Validate(value.Y, limit)
&& Validate(value.Z, limit);
if (!valid)
{
// Sound position and velocity have Y and Z axes swapped comparing to map coordinate system
Printf(TEXTCOLOR_RED "Invalid sound %s " TEXTCOLOR_WHITE "(%f, %f, %f)", name, value.X, value.Z, value.Y);
if (actor == nullptr)
{
Printf("\n");
}
else
{
Printf(TEXTCOLOR_RED " for actor of class " TEXTCOLOR_WHITE "%s\n", actor->GetClass()->TypeName.GetChars());
}
}
return valid;
}
static bool ValidatePosVel(const AActor *actor, const FVector3 &pos, const FVector3 &vel)
{
// The actual limit for map coordinates
static const float POSITION_LIMIT = 1024.f * 1024.f;
const bool valid = Validate(pos, POSITION_LIMIT, "position", actor);
// The maximum velocity is enough to travel through entire map in one tic
static const float VELOCITY_LIMIT = 2 * POSITION_LIMIT * TICRATE;
return Validate(vel, VELOCITY_LIMIT, "velocity", actor) && valid;
}
static bool ValidatePosVel(const FSoundChan *const chan, const FVector3 &pos, const FVector3 &vel)
{
return ValidatePosVel(chan->SourceType == SOURCE_Actor ? chan->Actor : nullptr, pos, vel);
}
//==========================================================================
//
// CalcSectorSoundOrg
//
// Returns the perceived sound origin for a sector. If the listener is
// inside the sector, then the origin is their location. Otherwise, the
// origin is from the nearest wall on the sector.
//
//==========================================================================
static void CalcSectorSoundOrg(const DVector3 &listenpos, const sector_t *sec, int channum, FVector3 &pos)
{
if (!(sec->Level->i_compatflags & COMPATF_SECTORSOUNDS))
{
// Are we inside the sector? If yes, the closest point is the one we're on.
if (primaryLevel->PointInSector(listenpos.X, listenpos.Y) == sec)
{
pos.X = (float)listenpos.X;
pos.Z = (float)listenpos.Y;
}
else
{
// Find the closest point on the sector's boundary lines and use
// that as the perceived origin of the sound.
DVector2 xy;
sec->ClosestPoint(listenpos, xy);
pos.X = (float)xy.X;
pos.Z = (float)xy.Y;
}
}
else
{
pos.X = float(sec->centerspot.X);
pos.Z = float(sec->centerspot.Y);
}
// Set sound vertical position based on channel.
if (channum == CHAN_FLOOR)
{
pos.Y = (float)MIN<double>(sec->floorplane.ZatPoint(listenpos), listenpos.Z);
}
else if (channum == CHAN_CEILING)
{
pos.Y = (float)MAX<double>(sec->ceilingplane.ZatPoint(listenpos), listenpos.Z);
}
else if (channum == CHAN_INTERIOR)
{
pos.Y = (float)clamp<double>(listenpos.Z, sec->floorplane.ZatPoint(listenpos), sec->ceilingplane.ZatPoint(listenpos));
}
}
//==========================================================================
//
// CalcPolySoundOrg
//
// Returns the perceived sound origin for a polyobject. This is similar to
// CalcSectorSoundOrg, except there is no special case for being "inside"
// a polyobject, so the sound literally comes from the polyobject's walls.
// Vertical position of the sound always comes from the visible wall.
//
//==========================================================================
static void CalcPolyobjSoundOrg(const DVector3 &listenpos, const FPolyObj *poly, FVector3 &pos)
{
side_t *side;
sector_t *sec;
DVector2 ppos;
poly->ClosestPoint(listenpos, ppos, &side);
pos.X = (float)ppos.X;
pos.Z = (float)ppos.Y;
sec = side->sector;
pos.Y = (float)clamp<double>(listenpos.Z, sec->floorplane.ZatPoint(listenpos), sec->ceilingplane.ZatPoint(listenpos));
}
//==========================================================================
//
// S_StartSound
//
// 0 attenuation means full volume over whole primaryLevel->
// 0 < attenuation means to scale the distance by that amount when
// calculating volume.
//
//==========================================================================
static FSoundChan *S_StartSound(AActor *actor, const sector_t *sec, const FPolyObj *poly,
const FVector3 *pt, int channel, FSoundID sound_id, float volume, float attenuation,
FRolloffInfo *forcedrolloff=NULL, float spitch = 0.0f)
{
sfxinfo_t *sfx;
int chanflags;
int basepriority;
int org_id;
int pitch;
FSoundChan *chan;
FVector3 pos, vel;
FRolloffInfo *rolloff;
FSoundLoadBuffer SoundBuffer;
if (sound_id <= 0 || volume <= 0 || nosfx || nosound )
return NULL;
int type;
if (actor != NULL)
{
type = SOURCE_Actor;
}
else if (sec != NULL)
{
type = SOURCE_Sector;
}
else if (poly != NULL)
{
type = SOURCE_Polyobj;
}
else if (pt != NULL)
{
type = SOURCE_Unattached;
}
else
{
type = SOURCE_None;
}
org_id = sound_id;
chanflags = channel & ~7;
channel &= 7;
CalcPosVel(type, actor, sec, poly, &pt->X, channel, chanflags, &pos, &vel);
if (!ValidatePosVel(type == SOURCE_Actor ? actor : nullptr, pos, vel))
{
return nullptr;
}
if (compatflags & COMPATF_MAGICSILENCE)
{ // For people who just can't play without a silent BFG.
channel = CHAN_WEAPON;
}
else if ((chanflags & CHAN_MAYBE_LOCAL) && (compatflags & COMPATF_SILENTPICKUP))
{
if (actor != nullptr && actor != players[consoleplayer].camera)
{
return nullptr;
}
}
sfx = &S_sfx[sound_id];
// Scale volume according to SNDINFO data.
volume = MIN(volume * sfx->Volume, 1.f);
if (volume <= 0)
return NULL;
// When resolving a link we do not want to get the NearLimit of
// the referenced sound so some additional checks are required
int near_limit = sfx->NearLimit;
float limit_range = sfx->LimitRange;
auto pitchmask = sfx->PitchMask;
rolloff = &sfx->Rolloff;
// Resolve player sounds, random sounds, and aliases
while (sfx->link != sfxinfo_t::NO_LINK)
{
if (sfx->bPlayerReserve)
{
sound_id = FSoundID(S_FindSkinnedSound (actor, sound_id));
near_limit = S_sfx[sound_id].NearLimit;
limit_range = S_sfx[sound_id].LimitRange;
rolloff = &S_sfx[sound_id].Rolloff;
}
else if (sfx->bRandomHeader)
{
// Random sounds attenuate based on the original (random) sound as well as the chosen one.
attenuation *= sfx->Attenuation;
sound_id = FSoundID(S_PickReplacement (sound_id));
if (near_limit < 0)
{
near_limit = S_sfx[sound_id].NearLimit;
limit_range = S_sfx[sound_id].LimitRange;
}
if (rolloff->MinDistance == 0)
{
rolloff = &S_sfx[sound_id].Rolloff;
}
}
else
{
sound_id = FSoundID(sfx->link);
if (near_limit < 0)
{