- refactoring of DN3D sound code complete but not tested yet.

This commit is contained in:
Christoph Oelckers 2019-12-15 13:34:00 +01:00
parent 62660e76f3
commit a28cd17454
15 changed files with 355 additions and 376 deletions

View file

@ -270,6 +270,7 @@ static int osdcmd_noclip(osdcmdptr_t UNUSED(parm))
return OSDCMD_OK;
}
/*
static int osdcmd_restartsound(osdcmdptr_t UNUSED(parm))
{
UNREFERENCED_CONST_PARAMETER(parm);
@ -281,6 +282,7 @@ static int osdcmd_restartsound(osdcmdptr_t UNUSED(parm))
return OSDCMD_OK;
}
*/
void onvideomodechange(int32_t newmode)
{
@ -303,7 +305,6 @@ int32_t registerosdcommands(void)
OSD_RegisterFunction("give","give <all|health|weapons|ammo|armor|keys|inventory>: gives requested item", osdcmd_give);
OSD_RegisterFunction("god","god: toggles god mode", osdcmd_god);
OSD_RegisterFunction("noclip","noclip: toggles clipping mode", osdcmd_noclip);
OSD_RegisterFunction("restartsound","restartsound: reinitializes the sound system",osdcmd_restartsound);
OSD_RegisterFunction("vidmode","vidmode <xdim> <ydim> <bpp> <fullscreen>: change the video mode",osdcmd_vidmode);

View file

@ -45,6 +45,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "gstrings.h"
#include "quotemgr.h"
#include "mapinfo.h"
#include "s_soundinternal.h"
#ifndef NETCODE_DISABLE
#include "enet.h"
#endif
@ -545,3 +546,11 @@ void CONFIG_InitMouseAndController()
inputState.keyFlushScans();
}
CCMD(snd_reset)
{
Mus_Stop();
soundEngine->Reset();
MUS_ResumeSaved();
}

View file

@ -157,12 +157,8 @@ void SoundEngine::CacheMarkedSounds()
void SoundEngine::CacheSound (sfxinfo_t *sfx)
{
if (GSnd)
if (GSnd && !sfx->bTentative)
{
if (sfx->bPlayerReserve)
{
return;
}
sfxinfo_t *orig = sfx;
while (!sfx->bRandomHeader && sfx->link != sfxinfo_t::NO_LINK)
{
@ -338,8 +334,7 @@ FString SoundEngine::ListSoundChannels()
void SoundEngine::CalcPosVel(FSoundChan *chan, FVector3 *pos, FVector3 *vel)
{
CalcPosVel(chan->SourceType, chan->Source, chan->Point,
chan->EntChannel, chan->ChanFlags, pos, vel);
CalcPosVel(chan->SourceType, chan->Source, chan->Point, chan->EntChannel, chan->ChanFlags, chan->SoundID, pos, vel);
}
bool SoundEngine::ValidatePosVel(const FSoundChan* const chan, const FVector3& pos, const FVector3& vel)
@ -403,7 +398,7 @@ FSoundChan *SoundEngine::StartSound(int type, const void *source,
chanflags = channel & ~7;
channel &= 7;
CalcPosVel(type, source, &pt->X, channel, chanflags, &pos, &vel);
CalcPosVel(type, source, &pt->X, channel, chanflags, sound_id, &pos, &vel);
if (!ValidatePosVel(type, source, pos, vel))
{
@ -1101,8 +1096,9 @@ void SoundEngine::SetPitch(FSoundChan *chan, float pitch)
// Is a sound being played by a specific emitter?
//==========================================================================
bool SoundEngine::GetSoundPlayingInfo (int sourcetype, const void *source, int sound_id)
int SoundEngine::GetSoundPlayingInfo (int sourcetype, const void *source, int sound_id)
{
int count = 0;
if (sound_id > 0)
{
for (FSoundChan *chan = Channels; chan != NULL; chan = chan->NextChan)
@ -1111,11 +1107,11 @@ bool SoundEngine::GetSoundPlayingInfo (int sourcetype, const void *source, int s
(chan->SourceType == sourcetype &&
chan->Source == source)))
{
return true;
count++;
}
}
}
return false;
return count;
}
//==========================================================================
@ -1543,14 +1539,11 @@ int SoundEngine::AddSoundLump(const char* logicalname, int lump, int CurrentPitc
newsfx.NearLimit = 2;
newsfx.LimitRange = 256 * 256;
newsfx.bRandomHeader = false;
newsfx.bPlayerReserve = false;
newsfx.bLoadRAW = false;
newsfx.bPlayerCompat = false;
newsfx.b16bit = false;
newsfx.bUsed = false;
newsfx.bSingular = false;
newsfx.bTentative = false;
newsfx.bPlayerSilent = false;
newsfx.ResourceId = resid;
newsfx.RawRate = 0;
newsfx.link = sfxinfo_t::NO_LINK;

View file

@ -40,11 +40,7 @@ struct sfxinfo_t
unsigned bSingular:1;
unsigned bTentative:1;
unsigned bPlayerReserve : 1;
unsigned bPlayerCompat : 1;
unsigned bPlayerSilent:1; // This player sound is intentionally silent.
unsigned userFlags;
int userdata;
TArray<uint8_t> UserData;
int RawRate; // Sample rate to use when bLoadRAW is true
@ -57,6 +53,37 @@ struct sfxinfo_t
float Attenuation; // Multiplies the attenuation passed to S_Sound.
void MarkUsed(); // Marks this sound as used.
void Clear()
{
data.Clear();
data3d.Clear();
lumpnum = -1; // lump number of sfx
next = -1;
index = 0; // [RH] For hashing
Volume = 1.f;
ResourceId = -1;
PitchMask = 0;
NearLimit = 4; // 0 means unlimited
LimitRange = 256*256;
bRandomHeader = false;
bLoadRAW = false;
b16bit= false;
bUsed = false;
bSingular = false;
bTentative = true;
RawRate = 0; // Sample rate to use when bLoadRAW is true
LoopStart = 0; // -1 means no specific loop defined
link = NO_LINK;
Rolloff = {};
Attenuation = 1.f;
}
};
// Rolloff types
@ -256,7 +283,7 @@ private:
bool IsChannelUsed(int sourcetype, const void* actor, int channel, int* seen);
// This is the actual sound positioning logic which needs to be provided by the client.
virtual void CalcPosVel(int type, const void* source, const float pt[3], int channel, int chanflags, FVector3* pos, FVector3* vel) = 0;
virtual void CalcPosVel(int type, const void* source, const float pt[3], int channel, int chanflags, FSoundID chanSound, FVector3* pos, FVector3* vel) = 0;
// This can be overridden by the clent to provide some diagnostics. The default lets everything pass.
virtual bool ValidatePosVel(int sourcetype, const void* source, const FVector3& pos, const FVector3& vel) { return true; }
@ -313,7 +340,7 @@ public:
bool IsSourcePlayingSomething(int sourcetype, const void* actor, int channel, int sound_id);
// Stop and resume music, during game PAUSE.
bool GetSoundPlayingInfo(int sourcetype, const void* source, int sound_id);
int GetSoundPlayingInfo(int sourcetype, const void* source, int sound_id);
void UnloadAllSounds();
void Reset();
void MarkUsed(int num);
@ -329,10 +356,6 @@ public:
{
return object && listener.ListenerObject == object;
}
bool isPlayerReserve(int snd_id)
{
return S_sfx[snd_id].bPlayerReserve; // Later this needs to be abstracted out of the engine itself. Right now that cannot be done.
}
void SetListener(SoundListener& l)
{
listener = l;
@ -369,17 +392,22 @@ public:
{
S_rnd.Clear();
}
int GetUserFlags(int snd)
void *GetUserData(int snd)
{
return S_sfx[snd].userFlags;
}
int GetUserData(int snd)
{
return S_sfx[snd].userdata;
return S_sfx[snd].UserData.Data();
}
bool isValidSoundId(int id)
{
return id > 0 && id < (int)S_sfx.Size();
return id > 0 && id < (int)S_sfx.Size() && !S_sfx[id].bTentative;
}
template<class func> bool EnumerateChannels(func callback)
{
for (FSoundChan* chan = Channels; chan; chan = chan->NextChan)
{
if (callback(chan)) return true;
}
return false;
}
void ChannelVirtualChanged(FISoundChannel* ichan, bool is_virtual);

View file

@ -1492,7 +1492,8 @@ ACTOR_STATIC void G_MoveFX(void)
else if (pSprite->lotag < 999 && (unsigned)sector[pSprite->sectnum].lotag < 9 && // ST_9_SLIDING_ST_DOOR
snd_ambience && sector[SECT(spriteNum)].floorz != sector[SECT(spriteNum)].ceilingz)
{
if (g_sounds[pSprite->lotag].m & SF_MSFX)
auto flags = S_GetUserFlags(pSprite->lotag);
if (flags & SF_MSFX)
{
int playerDist = dist(&sprite[pPlayer->i], pSprite);
@ -1505,10 +1506,10 @@ ACTOR_STATIC void G_MoveFX(void)
}
#endif
if (playerDist < spriteHitag && T1(spriteNum) == 0 && FX_VoiceAvailable(g_sounds[pSprite->lotag].pr-1))
if (playerDist < spriteHitag && T1(spriteNum) == 0)// && FX_VoiceAvailable(g_sounds[pSprite->lotag].pr-1))
{
// Start playing an ambience sound.
#if 0 // let the sound system handle this internally.
char om = g_sounds[pSprite->lotag].m;
if (g_numEnvSoundsPlaying == snd_numvoices)
{
@ -1525,10 +1526,8 @@ ACTOR_STATIC void G_MoveFX(void)
if (j == -1)
goto next_sprite;
}
g_sounds[pSprite->lotag].m |= SF_LOOP;
A_PlaySound(pSprite->lotag,spriteNum);
g_sounds[pSprite->lotag].m = om;
#endif
A_PlaySound(pSprite->lotag,spriteNum, true);
T1(spriteNum) = 1; // AMBIENT_SFX_PLAYING
}
else if (playerDist >= spriteHitag && T1(spriteNum) == 1)
@ -1541,7 +1540,7 @@ ACTOR_STATIC void G_MoveFX(void)
}
}
if ((g_sounds[pSprite->lotag].m & (SF_GLOBAL|SF_DTAG)) == SF_GLOBAL)
if ((flags & (SF_GLOBAL|SF_DTAG)) == SF_GLOBAL)
{
// Randomly playing global sounds (flyby of planes, screams, ...)

View file

@ -4745,43 +4745,6 @@ void G_HandleLocalKeys(void)
}
}
static int32_t S_DefineAudioIfSupported(char **fn, const char *name)
{
#if !defined HAVE_FLAC || !defined HAVE_VORBIS
const char *extension = Bstrrchr(name, '.');
# if !defined HAVE_FLAC
if (extension && !Bstrcasecmp(extension, ".flac"))
return -2;
# endif
# if !defined HAVE_VORBIS
if (extension && !Bstrcasecmp(extension, ".ogg"))
return -2;
# endif
#endif
realloc_copy(fn, name);
return 0;
}
static int32_t S_DefineSound(int sndidx, const char *name, int minpitch, int maxpitch, int priority, int type, int distance, float volume)
{
if ((unsigned)sndidx >= MAXSOUNDS || S_DefineAudioIfSupported(&g_sounds[sndidx].filename, name))
return -1;
auto &snd = g_sounds[sndidx];
snd.ps = clamp(minpitch, INT16_MIN, INT16_MAX);
snd.pe = clamp(maxpitch, INT16_MIN, INT16_MAX);
snd.pr = priority & 255;
snd.m = type & ~SF_ONEINST_INTERNAL;
snd.vo = clamp(distance, INT16_MIN, INT16_MAX);
snd.volume = volume;
if (snd.m & SF_LOOP)
snd.m |= SF_ONEINST_INTERNAL;
return 0;
}
// Returns:
// 0: all OK
// -1: ID declaration was invalid:
@ -5399,10 +5362,6 @@ static void G_Cleanup(void)
Xfree(g_player[i].input);
}
for (i=MAXSOUNDS-1; i>=0; i--)
{
Xfree(g_sounds[i].filename);
}
#if !defined LUNATIC
if (label != (char *)&sprite[0]) Xfree(label);
if (labelcode != (int32_t *)&sector[0]) Xfree(labelcode);
@ -5432,7 +5391,6 @@ static void G_Cleanup(void)
void G_Shutdown(void)
{
S_SoundShutdown();
engineUnInit();
G_Cleanup();
}
@ -6031,7 +5989,6 @@ int GameInterface::app_main()
}
videoSetPalette(0, myplayer.palette, 0);
S_SoundStartup();
}
// check if the minifont will support lowercase letters (3136-3161)

View file

@ -5361,86 +5361,74 @@ repeatcase:
continue;
case CON_DEFINESOUND:
{
FString filename;
int ps, pe, vo, pr, m;
float volume;
g_scriptPtr--;
C_GetNextValue(LABEL_DEFINE);
// Ideally we could keep the value of i from C_GetNextValue() instead of having to hash_find() again.
// This depends on tempbuf remaining in place after C_GetNextValue():
j = hash_find(&h_labels,tempbuf);
j = hash_find(&h_labels, tempbuf);
k = g_scriptPtr[-1];
if (EDUKE32_PREDICT_FALSE((unsigned)k >= MAXSOUNDS-1))
if ((unsigned)k >= MAXSOUNDS - 1)
{
initprintf("%s:%d: error: sound index exceeds limit of %d.\n",g_scriptFileName,g_lineNumber, MAXSOUNDS-1);
initprintf("%s:%d: error: sound index exceeds limit of %d.\n", g_scriptFileName, g_lineNumber, MAXSOUNDS - 1);
g_errorCnt++;
k = MAXSOUNDS-1;
k = MAXSOUNDS - 1;
}
else if (EDUKE32_PREDICT_FALSE(g_sounds[k].filename != NULL))
/*else if (g_sounds[k].filename != NULL)
{
initprintf("%s:%d: warning: sound %d already defined (%s)\n",g_scriptFileName,g_lineNumber,k,g_sounds[k].filename);
initprintf("%s:%d: warning: sound %d already defined (%s)\n", g_scriptFileName, g_lineNumber, k, g_sounds[k].filename);
g_warningCnt++;
}
}*/
g_scriptPtr--;
i = 0;
C_SkipComments();
if (g_sounds[k].filename == NULL)
g_sounds[k].filename = (char *)Xcalloc(BMAX_PATH,sizeof(uint8_t));
TArray<char> buffer;
if (*textptr == '\"')
{
textptr++;
while (*textptr && *textptr != '\"')
{
g_sounds[k].filename[i++] = *textptr++;
if (EDUKE32_PREDICT_FALSE(i >= BMAX_PATH-1))
{
initprintf("%s:%d: error: sound filename exceeds limit of %d characters.\n",g_scriptFileName,g_lineNumber,BMAX_PATH-1);
g_errorCnt++;
C_SkipComments();
break;
}
buffer.Push(*textptr++);
}
textptr++;
}
else while (*textptr != ' ' && *textptr != '\t' && *textptr != '\r' && *textptr != '\n')
{
g_sounds[k].filename[i++] = *textptr++;
if (EDUKE32_PREDICT_FALSE(i >= BMAX_PATH-1))
{
initprintf("%s:%d: error: sound filename exceeds limit of %d characters.\n",g_scriptFileName,g_lineNumber,BMAX_PATH-1);
g_errorCnt++;
C_SkipComments();
break;
}
buffer.Push(*textptr++);
}
g_sounds[k].filename[i] = '\0';
buffer.Push(0);
C_GetNextValue(LABEL_DEFINE);
g_sounds[k].ps = g_scriptPtr[-1];
ps = g_scriptPtr[-1];
C_GetNextValue(LABEL_DEFINE);
g_sounds[k].pe = g_scriptPtr[-1];
pe = g_scriptPtr[-1];
C_GetNextValue(LABEL_DEFINE);
g_sounds[k].pr = g_scriptPtr[-1];
pr = g_scriptPtr[-1];
C_GetNextValue(LABEL_DEFINE);
g_sounds[k].m = g_scriptPtr[-1] & ~SF_ONEINST_INTERNAL;
if (g_scriptPtr[-1] & SF_LOOP)
g_sounds[k].m |= SF_ONEINST_INTERNAL;
m = g_scriptPtr[-1];
C_GetNextValue(LABEL_DEFINE);
g_sounds[k].vo = g_scriptPtr[-1];
vo = g_scriptPtr[-1];
g_scriptPtr -= 5;
g_sounds[k].volume = 1.f;
int res = S_DefineSound(k, filename, ps, pe, pr, m, vo, 1.f);
if (k > g_highestSoundIdx)
g_highestSoundIdx = k;
volume = 1.f;
if (g_dynamicSoundMapping && j >= 0 && (labeltype[j] & LABEL_DEFINE))
G_ProcessDynamicSoundMapping(label+(j<<6), k);
G_ProcessDynamicSoundMapping(label + (j << 6), k);
continue;
}
case CON_ENDEVENT:

View file

@ -149,7 +149,6 @@ G_EXTERN int32_t g_noEnemies;
G_EXTERN int32_t g_restorePalette;
G_EXTERN int32_t g_screenCapture;
G_EXTERN projectile_t SpriteProjectile[MAXSPRITES];
G_EXTERN sound_t g_sounds[MAXSOUNDS];
G_EXTERN uint32_t everyothertime;
G_EXTERN uint32_t g_moveThingsCount;
G_EXTERN double g_gameUpdateTime;

View file

@ -172,19 +172,6 @@ static int osdcmd_noclip(osdcmdptr_t UNUSED(parm))
return OSDCMD_OK;
}
static int osdcmd_restartsound(osdcmdptr_t UNUSED(parm))
{
UNREFERENCED_CONST_PARAMETER(parm);
S_SoundShutdown();
S_SoundStartup();
FX_StopAllSounds();
S_ClearSoundLocks();
return OSDCMD_OK;
}
int osdcmd_restartmap(osdcmdptr_t UNUSED(parm))
{
UNREFERENCED_CONST_PARAMETER(parm);
@ -812,7 +799,6 @@ int32_t registerosdcommands(void)
OSD_RegisterFunction("printtimes", "printtimes: prints VM timing statistics", osdcmd_printtimes);
OSD_RegisterFunction("restartmap", "restartmap: restarts the current map", osdcmd_restartmap);
OSD_RegisterFunction("restartsound","restartsound: reinitializes the sound system",osdcmd_restartsound);
OSD_RegisterFunction("addlogvar","addlogvar <gamevar>: prints the value of a gamevar", osdcmd_addlogvar);
OSD_RegisterFunction("setvar","setvar <gamevar> <value>: sets the value of a gamevar", osdcmd_setvar);
OSD_RegisterFunction("setvarvar","setvarvar <gamevar1> <gamevar2>: sets the value of <gamevar1> to <gamevar2>", osdcmd_setvar);

View file

@ -70,9 +70,10 @@ int A_CallSound(int sectNum, int spriteNum)
if (spriteNum == -1)
spriteNum = SFXsprite;
auto flags = S_GetUserFlags(soundNum);
if (T1(SFXsprite) == 0)
{
if ((g_sounds[soundNum].m & (SF_GLOBAL|SF_DTAG)) != SF_GLOBAL)
if ((flags & (SF_GLOBAL|SF_DTAG)) != SF_GLOBAL)
{
if (soundNum)
{
@ -93,7 +94,7 @@ int A_CallSound(int sectNum, int spriteNum)
if (SHT(SFXsprite))
A_PlaySound(SHT(SFXsprite), spriteNum);
if ((g_sounds[soundNum].m & SF_LOOP) || (SHT(SFXsprite) && SHT(SFXsprite) != soundNum))
if ((flags & SF_LOOP) || (SHT(SFXsprite) && SHT(SFXsprite) != soundNum))
S_StopEnvSound(soundNum, T6(SFXsprite));
T6(SFXsprite) = spriteNum;
@ -1465,7 +1466,9 @@ int P_ActivateSwitch(int playerNum, int wallOrSprite, int switchType)
S_PlaySound3D(SWITCH_ON, (switchType == SWITCH_SPRITE) ? wallOrSprite : g_player[playerNum].ps->i, &davector);
else if (hitag)
{
if (switchType == SWITCH_SPRITE && (g_sounds[hitag].m & SF_TALK) == 0)
auto flags = S_GetUserFlags(hitag);
if (switchType == SWITCH_SPRITE && (flags & SF_TALK) == 0)
S_PlaySound3D(hitag, wallOrSprite, &davector);
else
A_PlaySound(hitag, g_player[playerNum].ps->i);
@ -1968,7 +1971,7 @@ void A_DamageObject_Duke3D(int spriteNum, int const dmgSrc)
sprite[dmgSrc].xvel = (sprite[spriteNum].xvel>>1)+(sprite[spriteNum].xvel>>2);
sprite[dmgSrc].ang -= (SA(spriteNum)<<1)+1024;
SA(spriteNum) = getangle(SX(spriteNum)-sprite[dmgSrc].x,SY(spriteNum)-sprite[dmgSrc].y)-512;
if (g_sounds[POOLBALLHIT].num < 2)
if (S_CheckSoundPlaying(POOLBALLHIT) < 2)
A_PlaySound(POOLBALLHIT, spriteNum);
}
else

View file

@ -25,145 +25,35 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#include "compat.h"
#include "duke3d.h"
#include "renderlayer.h" // for win_gethwnd()
#include "al_midi.h"
#include "openaudio.h"
#include "z_music.h"
#include "mapinfo.h"
#include "sound/s_soundinternal.h"
#include <atomic>
BEGIN_DUKE_NS
int32_t g_highestSoundIdx;
#define DQSIZE 256
int32_t g_numEnvSoundsPlaying, g_highestSoundIdx;
static char *MusicPtr;
static int32_t MusicIsWaveform;
static int32_t MusicVoice = -1;
static bool MusicPaused;
static bool SoundPaused;
static std::atomic<uint32_t> dnum, dq[DQSIZE];
static mutex_t m_callback;
static inline void S_SetProperties(assvoice_t *snd, int const owner, int const voice, int const dist, int const clock)
class DukeSoundEngine : public SoundEngine
{
snd->owner = owner;
snd->id = voice;
snd->dist = dist;
snd->clock = clock;
}
// client specific parts of the sound engine go in this class.
void CalcPosVel(int type, const void* source, const float pt[3], int channum, int chanflags, FSoundID chanSound, FVector3* pos, FVector3* vel) override;
TArray<uint8_t> ReadSound(int lumpnum);
void S_SoundStartup(void)
public:
DukeSoundEngine() = default;
};
//==========================================================================
//
// This is to avoid hardscoding the dependency on Wads into the sound engine
//
//==========================================================================
TArray<uint8_t> DukeSoundEngine::ReadSound(int lumpnum)
{
#ifdef _WIN32
void *initdata = (void *) win_gethwnd(); // used for DirectSound
#else
void *initdata = NULL;
#endif
initprintf("Initializing sound... ");
int status = FX_Init(snd_numvoices, snd_numchannels, snd_mixrate, initdata);
if (status != FX_Ok)
{
initprintf("failed! %s\n", FX_ErrorString(status));
return;
}
initprintf("%d voices, %d channels, 16-bit %d Hz\n", *snd_numvoices, *snd_numchannels, *snd_mixrate);
for (int i = 0; i <= g_highestSoundIdx; ++i)
{
for (auto & voice : g_sounds[i].voices)
{
g_sounds[i].num = 0;
S_SetProperties(&voice, -1, 0, UINT16_MAX, 0);
}
}
snd_fxvolume.Callback();
snd_reversestereo.Callback();
//FX_SetCallBack(S_Callback);
FX_SetPrintf(OSD_Printf);
}
void S_SoundShutdown(void)
{
int status = FX_Shutdown();
if (status != FX_Ok)
{
Bsprintf(tempbuf, "S_SoundShutdown(): error: %s", FX_ErrorString(status));
G_GameExit(tempbuf);
}
}
void S_PauseSounds(bool paused)
{
if (SoundPaused == paused)
return;
SoundPaused = paused;
for (int i = 0; i <= g_highestSoundIdx; ++i)
{
for (auto & voice : g_sounds[i].voices)
if (voice.id > 0)
FX_PauseVoice(voice.id, paused);
}
}
// returns number of bytes read
int32_t S_LoadSound(int num)
{
if ((unsigned)num > (unsigned)g_highestSoundIdx || EDUKE32_PREDICT_FALSE(g_sounds[num].filename == NULL))
return 0;
auto &snd = g_sounds[num];
auto fp = S_OpenAudio(snd.filename, 0, 0);
if (!fp.isOpen())
{
OSD_Printf(OSDTEXT_RED "Sound %s(#%d) not found!\n", snd.filename, num);
return 0;
}
int32_t l = fp.GetLength();
snd.siz = l;
cacheAllocateBlock((intptr_t *)&snd.ptr, l, nullptr);
l = fp.Read(snd.ptr, l);
return l;
}
void cacheAllSounds(void)
{
for (int i=0, j=0; i <= g_highestSoundIdx; ++i)
{
if (g_sounds[i].ptr == 0)
{
j++;
if ((j&7) == 0)
gameHandleEvents();
S_LoadSound(i);
}
}
}
static inline int S_GetPitch(int num)
{
auto const &snd = g_sounds[num];
int const range = klabs(snd.pe - snd.ps);
return (range == 0) ? snd.ps : min(snd.ps, snd.pe) + rand() % range;
auto wlump = fileSystem.OpenFileReader(lumpnum);
return wlump.Read();
}
//==========================================================================
@ -172,24 +62,104 @@ static inline int S_GetPitch(int num)
//
//==========================================================================
void S_PauseSounds(bool paused)
{
soundEngine->SetPaused(paused);
}
//==========================================================================
//
//
//
//==========================================================================
void cacheAllSounds(void)
{
for (int i=0, j=0; i < MAXSOUNDS; ++i)
{
soundEngine->CacheSound(i);
if ((i&31) == 0)
gameHandleEvents();
}
}
//==========================================================================
//
//
//
//==========================================================================
static inline int S_GetPitch(int num)
{
auto const* snd = (sound_t*)soundEngine->GetUserData(num);
int const range = abs(snd->pitchEnd - snd->pitchStart);
return (range == 0) ? snd->pitchStart : min(snd->pitchStart, snd->pitchEnd) + rand() % range;
}
float S_ConvertPitch(int lpitch)
{
return pow(2, lpitch / 1200.); // I hope I got this right that ASS uses a linear scale where 1200 is a full octave.
}
int S_GetUserFlags(int sndnum)
{
return ((sound_t*)soundEngine->GetUserData(sndnum + 1))->flags;
}
//==========================================================================
//
//
//
//==========================================================================
static int S_CalcDistAndAng(int spriteNum, int soundNum, int sectNum, int angle,
int S_DefineSound(unsigned index, const char *filename, int minpitch, int maxpitch, int priority, int type, int distance, float volume)
{
if ((unsigned)index >= MAXSOUNDS)
return -1;
auto& S_sfx = soundEngine->GetSounds();
index++;
unsigned oldindex = S_sfx.Size();
if (index >= S_sfx.Size())
{
S_sfx.Resize(index + 1);
for (; oldindex <= index; oldindex++)
{
S_sfx[oldindex].Clear();
}
}
auto sfx = &S_sfx[index];
bool alreadydefined = !sfx->bTentative;
sfx->UserData.Resize(sizeof(sound_t));
auto sndinf = (sound_t*)sfx->UserData.Data();
sndinf->flags = type & ~SF_ONEINST_INTERNAL;
if (sndinf->flags & SF_LOOP)
sndinf->flags |= SF_ONEINST_INTERNAL;
sndinf->pitchStart = clamp(minpitch, INT16_MIN, INT16_MAX);
sndinf->pitchEnd = clamp(maxpitch, INT16_MIN, INT16_MAX);
sndinf->priority = priority & 255;
sndinf->volAdjust = clamp(distance, INT16_MIN, INT16_MAX);
sfx->Volume = volume;
return 0;
}
//==========================================================================
//
//
//
//==========================================================================
static int S_CalcDistAndAng(int spriteNum, int soundNum, int sectNum,
const vec3_t *cam, const vec3_t *pos, int *distPtr, FVector3 *sndPos)
{
// Todo: Some of this hackery really should be done using rolloff and attenuation instead of messing around with the sound origin.
int orgsndist = 0, sndang = 0, sndist = 0, explosion = 0;
int userflags = soundEngine->GetUserFlags(soundNum);
int dist_adjust = soundEngine->GetUserData(soundNum);
auto const* snd = (sound_t*)soundEngine->GetUserData(soundNum);
int userflags = snd->flags;
int dist_adjust = snd->volAdjust;
if (PN(spriteNum) == APLAYER && P_Get(spriteNum) == screenpeek)
goto sound_further_processing;
@ -256,67 +226,93 @@ boost:
//
//==========================================================================
void S_Update(void)
void S_GetCamera(vec3_t** c, int32_t* ca, int32_t* cs)
{
if ((g_player[myconnectindex].ps->gm & (MODE_GAME | MODE_DEMO)) == 0)
return;
g_numEnvSoundsPlaying = 0;
const vec3_t* c;
int32_t ca, cs;
if (ud.camerasprite == -1)
{
if (ud.overhead_on != 2)
{
c = &CAMERA(pos);
cs = CAMERA(sect);
ca = fix16_to_int(CAMERA(q16ang));
if (c) *c = &CAMERA(pos);
if (cs) *cs = CAMERA(sect);
if (ca) *ca = fix16_to_int(CAMERA(q16ang));
}
else
{
auto pPlayer = g_player[screenpeek].ps;
c = &pPlayer->pos;
cs = pPlayer->cursectnum;
ca = fix16_to_int(pPlayer->q16ang);
if (c) *c = &pPlayer->pos;
if (cs) *cs = pPlayer->cursectnum;
if (ca) *ca = fix16_to_int(pPlayer->q16ang);
}
}
else
{
c = &sprite[ud.camerasprite].pos;
cs = sprite[ud.camerasprite].sectnum;
ca = sprite[ud.camerasprite].ang;
if (c) *c = &sprite[ud.camerasprite].pos;
if (cs) *cs = sprite[ud.camerasprite].sectnum;
if (ca) *ca = sprite[ud.camerasprite].ang;
}
}
int sndnum = 0;
int const highest = g_highestSoundIdx;
//=========================================================================
//
// CalcPosVel
//
// The game specific part of the sound updater.
//
//=========================================================================
do
void DukeSoundEngine::CalcPosVel(int type, const void* source, const float pt[3], int channum, int chanflags, FSoundID chanSound, FVector3* pos, FVector3* vel)
{
if (pos != nullptr)
{
if (g_sounds[sndnum].num == 0)
continue;
vec3_t* campos;
int32_t camsect;
for (auto& voice : g_sounds[sndnum].voices)
S_GetCamera(&campos, nullptr, &camsect);
if (vel) vel->Zero();
// [BL] Moved this case out of the switch statement to make code easier
// on static analysis.
if (type == SOURCE_Unattached)
{
int const spriteNum = voice.owner;
if ((unsigned)spriteNum >= MAXSPRITES || voice.id <= FX_Ok || !FX_SoundActive(voice.id))
continue;
int sndist, sndang;
S_CalcDistAndAng(spriteNum, sndnum, cs, ca, c, (const vec3_t*)&sprite[spriteNum], &sndist, nullptr);
if (S_IsAmbientSFX(spriteNum))
g_numEnvSoundsPlaying++;
// AMBIENT_SOUND
//FX_Pan3D(voice.id, sndang >> 4, sndist >> 6);
voice.dist = sndist >> 6;
voice.clock++;
pos->X = pt[0];
pos->Y = campos && !(chanflags & CHAN_LISTENERZ) ? pt[1] : campos->z / 256.f;
pos->Z = pt[2];
}
} while (++sndnum <= highest);
else
{
switch (type)
{
case SOURCE_None:
default:
break;
case SOURCE_Actor:
{
auto actor = (spritetype*)source;
assert(actor != nullptr);
if (actor != nullptr)
{
S_CalcDistAndAng(int(actor - sprite), chanSound - 1, camsect, campos, &actor->pos, nullptr, pos);
/*
if (vel)
{
vel->X = float(actor->Vel.X * TICRATE);
vel->Y = float(actor->Vel.Z * TICRATE);
vel->Z = float(actor->Vel.Y * TICRATE);
}
*/
}
break;
}
}
if ((chanflags & CHAN_LISTENERZ) && campos != nullptr)
{
pos->Y = campos->z / 256.f;
}
}
}
}
@ -326,7 +322,47 @@ void S_Update(void)
//
//==========================================================================
int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
void S_Update(void)
{
SoundListener listener;
vec3_t* c;
int32_t ca, cs;
S_GetCamera(&c, &ca, &cs);
if (c != nullptr)
{
listener.angle = (float)ca * pi::pi() / 2048; // todo: Check value range for angle.
listener.velocity.Zero();
listener.position = { c->x / 16.f, c->z / 256.f, c->y / 16.f };
listener.underwater = false;
// This should probably use a real environment instead of the pitch hacking in S_PlaySound3D.
// listenactor->waterlevel == 3;
//assert(primaryLevel->Zones.Size() > listenactor->Sector->ZoneNumber);
listener.Environment = 0;// primaryLevel->Zones[listenactor->Sector->ZoneNumber].Environment;
listener.valid = true;
}
else
{
listener.angle = 0;
listener.position.Zero();
listener.velocity.Zero();
listener.underwater = false;
listener.Environment = nullptr;
listener.valid = false;
}
listener.ListenerObject = ud.camerasprite == -1 ? nullptr : &sprite[ud.camerasprite];
soundEngine->SetListener(listener);
}
//==========================================================================
//
//
//
//==========================================================================
int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos, bool looped)
{
int32_t j = VM_OnEventWithReturn(EVENT_SOUND, spriteNum, screenpeek, num);
@ -336,7 +372,7 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
if (!soundEngine->isValidSoundId(sndnum) || !SoundEnabled() || (unsigned)spriteNum >= MAXSPRITES || (pPlayer->gm & MODE_MENU) ||
(pPlayer->timebeforeexit > 0 && pPlayer->timebeforeexit <= GAMETICSPERSEC * 3)) return -1;
int userflags = soundEngine->GetUserFlags(sndnum);
int userflags = S_GetUserFlags(sndnum);
if ((!(snd_speech & 1) && (userflags & SF_TALK)) || ((userflags & SF_ADULT) && adult_lockout))
return -1;
@ -351,10 +387,15 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
else if ((snd_speech & 1) != 1)
return -1;
bool foundone = soundEngine->EnumerateChannels([&](FSoundChan* chan)
{
auto sid = chan->SoundID;
auto flags = ((sound_t*)soundEngine->GetUserData(sid))->flags;
return !!(flags & SF_TALK);
});
// don't play if any Duke talk sounds are already playing
for (j = 0; j <= g_highestSoundIdx; ++j)
if ((g_sounds[j].m & SF_TALK) && g_sounds[j].num > 0)
return -1;
if (foundone) return -1;
}
else if ((userflags & (SF_DTAG | SF_GLOBAL)) == SF_DTAG) // Duke-Tag sound
{
@ -364,7 +405,12 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
int32_t sndist;
FVector3 sndpos; // this is in sound engine space.
int const explosionp = S_CalcDistAndAng(spriteNum, sndnum, CAMERA(sect), fix16_to_int(CAMERA(q16ang)), &CAMERA(pos), pos, &sndist, &sndpos);
vec3_t* campos;
int32_t camsect;
S_GetCamera(&campos, nullptr, &camsect);
int const explosionp = S_CalcDistAndAng(spriteNum, sndnum, camsect, campos, pos, &sndist, &sndpos);
int pitch = S_GetPitch(sndnum);
auto const pOther = g_player[screenpeek].ps;
@ -387,7 +433,7 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
pitch = -768;
}
bool is_playing = soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, sndnum);
bool is_playing = soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, sndnum+1);
if (is_playing && PN(spriteNum) != MUSICANDSFX)
S_StopEnvSound(sndnum, spriteNum);
@ -399,7 +445,8 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
}
// Now
auto chan = soundEngine->StartSound(SOURCE_Actor, &sprite[spriteNum], &sndpos, CHAN_AUTO, sndnum, 1.f, 1.f, nullptr, S_ConvertPitch(pitch));
auto chflg = ((userflags & SF_LOOP) || looped) ? CHAN_AUTO | CHAN_LOOP : CHAN_AUTO;
auto chan = soundEngine->StartSound(SOURCE_Actor, &sprite[spriteNum], &sndpos, chflg, sndnum+1, 1.f, 1.f, nullptr, S_ConvertPitch(pitch));
if (!chan) return -1;
return 0;
}
@ -410,19 +457,20 @@ int S_PlaySound3D(int num, int spriteNum, const vec3_t* pos)
//
//==========================================================================
int S_PlaySound(int num)
int S_PlaySound(int num, bool looped)
{
int sndnum = VM_OnEventWithReturn(EVENT_SOUND, g_player[screenpeek].ps->i, screenpeek, num);
if (!soundEngine->isValidSoundId(sndnum) || !SoundEnabled()) return -1;
if (!soundEngine->isValidSoundId(sndnum+1) || !SoundEnabled()) return -1;
int userflags = soundEngine->GetUserFlags(sndnum);
int userflags = S_GetUserFlags(sndnum);
if ((!(snd_speech & 1) && (userflags & SF_TALK)) || ((userflags & SF_ADULT) && adult_lockout))
return -1;
int const pitch = S_GetPitch(num);
int const pitch = S_GetPitch(sndnum);
soundEngine->StartSound(SOURCE_None, nullptr, nullptr, (userflags & SF_LOOP)? CHAN_AUTO|CHAN_LOOP : CHAN_AUTO, sndnum, 1.f, ATTN_NONE, nullptr, S_ConvertPitch(pitch));
auto chflg = ((userflags & SF_LOOP) || looped) ? CHAN_AUTO | CHAN_LOOP : CHAN_AUTO;
soundEngine->StartSound(SOURCE_None, nullptr, nullptr, chflg, sndnum + 1, 1.f, ATTN_NONE, nullptr, S_ConvertPitch(pitch));
/* for reference. May still be needed for balancing later.
: FX_Play3D(snd.ptr, snd.siz, FX_ONESHOT, pitch, 0, 255 - LOUDESTVOLUME, snd.pr, snd.volume,
(num * MAXSOUNDINSTANCES) + sndnum);
@ -436,18 +484,18 @@ int S_PlaySound(int num)
//
//==========================================================================
int A_PlaySound(int soundNum, int spriteNum)
int A_PlaySound(int soundNum, int spriteNum, bool looped)
{
return (unsigned)spriteNum >= MAXSPRITES ? S_PlaySound(soundNum) :
S_PlaySound3D(soundNum, spriteNum, &sprite[spriteNum].pos);
return (unsigned)spriteNum >= MAXSPRITES ? S_PlaySound(soundNum, looped) :
S_PlaySound3D(soundNum, spriteNum, &sprite[spriteNum].pos, looped);
}
void S_StopEnvSound(int sndNum, int sprNum)
{
if (sprNum < -1 || sprNum >= MAXSPRITES) return;
if (sprNum == -1) soundEngine->StopSoundID(sndNum);
else soundEngine->StopSound(SOURCE_Actor, &sprite[sprNum], -1, sndNum);
if (sprNum == -1) soundEngine->StopSoundID(sndNum+1);
else soundEngine->StopSound(SOURCE_Actor, &sprite[sprNum], -1, sndNum+1);
}
void S_ChangeSoundPitch(int soundNum, int spriteNum, int pitchoffset)
@ -456,11 +504,11 @@ void S_ChangeSoundPitch(int soundNum, int spriteNum, int pitchoffset)
double expitch = pow(2, pitchoffset / 1200.); // I hope I got this right that ASS uses a linear scale where 1200 is a full octave.
if (spriteNum == -1)
{
soundEngine->ChangeSoundPitch(SOURCE_Unattached, nullptr, CHAN_AUTO, expitch, soundNum);
soundEngine->ChangeSoundPitch(SOURCE_Unattached, nullptr, CHAN_AUTO, expitch, soundNum+1);
}
else
{
soundEngine->ChangeSoundPitch(SOURCE_Actor, &sprite[spriteNum], CHAN_AUTO, expitch, soundNum);
soundEngine->ChangeSoundPitch(SOURCE_Actor, &sprite[spriteNum], CHAN_AUTO, expitch, soundNum+1);
}
}
@ -472,9 +520,9 @@ void S_ChangeSoundPitch(int soundNum, int spriteNum, int pitchoffset)
int A_CheckSoundPlaying(int spriteNum, int soundNum)
{
if (spriteNum == -1) return soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, soundNum);
if (spriteNum == -1) return soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, soundNum+1);
if ((unsigned)spriteNum >= MAXSPRITES) return false;
return soundEngine->IsSourcePlayingSomething(SOURCE_Actor, &sprite[spriteNum], CHAN_AUTO, soundNum);
return soundEngine->IsSourcePlayingSomething(SOURCE_Actor, &sprite[spriteNum], CHAN_AUTO, soundNum+1);
}
// Check if actor <i> is playing any sound.
@ -486,7 +534,7 @@ int A_CheckAnySoundPlaying(int spriteNum)
int S_CheckSoundPlaying(int soundNum)
{
return soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, soundNum);
return soundEngine->GetSoundPlayingInfo(SOURCE_Any, nullptr, soundNum+1);
}
//==========================================================================

View file

@ -36,38 +36,20 @@ BEGIN_DUKE_NS
// KEEPINSYNC lunatic/con_lang.lua
#define MAXSOUNDS 4096
#define MAXSOUNDINSTANCES 8
#define LOUDESTVOLUME 111
#define MUSIC_ID -65536
typedef struct
{
int16_t owner;
int16_t id;
uint16_t dist;
uint16_t clock;
} assvoice_t;
typedef struct
{
char * ptr, *filename; // 8b/16b
int32_t length, num, siz; // 12b
float volume; // 4b
assvoice_t voices[MAXSOUNDINSTANCES]; // 64b
int16_t ps, pe, vo; // 6b
char pr, m; // 2b
int pitchStart, pitchEnd, volAdjust;
int priority, flags;
} sound_t;
extern sound_t g_sounds[MAXSOUNDS];
extern int32_t g_numEnvSoundsPlaying,g_highestSoundIdx;
int A_CheckSoundPlaying(int spriteNum,int soundNum);
int A_PlaySound(int soundNum, int spriteNum);
int A_PlaySound(int soundNum, int spriteNum, bool looped = false);
void S_Callback(intptr_t num);
int A_CheckAnySoundPlaying(int spriteNum);
int S_CheckSoundPlaying(int soundNum);
inline void S_ClearSoundLocks(void) {}
int32_t S_LoadSound(uint32_t num);
void cacheAllSounds(void);
void S_MenuSound(void);
void S_PauseMusic(bool paused);
@ -76,14 +58,14 @@ void S_PlayLevelMusicOrNothing(unsigned int);
int S_TryPlaySpecialMusic(unsigned int);
void S_PlaySpecialMusicOrNothing(unsigned int);
void S_ContinueLevelMusic(void);
int S_PlaySound(int num);
int S_PlaySound3D(int num, int spriteNum, const vec3_t *pos);
void S_SoundShutdown(void);
void S_SoundStartup(void);
int S_PlaySound(int num, bool looped = false);
int S_PlaySound3D(int num, int spriteNum, const vec3_t *pos, bool looped = false);
void S_StopEnvSound(int sndNum,int sprNum);
void S_StopAllSounds(void);
void S_Update(void);
void S_ChangeSoundPitch(int soundNum, int spriteNum, int pitchoffset);
int S_GetUserFlags(int sndnum);
int S_DefineSound(unsigned index, const char* filename, int ps, int pe, int pr, int m, int vo, float vol);
static inline bool S_IsAmbientSFX(int spriteNum)
{

View file

@ -169,19 +169,6 @@ static int osdcmd_noclip(osdcmdptr_t UNUSED(parm))
return OSDCMD_OK;
}
static int osdcmd_restartsound(osdcmdptr_t UNUSED(parm))
{
UNREFERENCED_CONST_PARAMETER(parm);
S_SoundShutdown();
S_SoundStartup();
FX_StopAllSounds();
S_ClearSoundLocks();
return OSDCMD_OK;
}
int osdcmd_restartmap(osdcmdptr_t UNUSED(parm))
{
UNREFERENCED_CONST_PARAMETER(parm);
@ -669,7 +656,6 @@ int32_t registerosdcommands(void)
OSD_RegisterFunction("printtimes", "printtimes: prints VM timing statistics", osdcmd_printtimes);
OSD_RegisterFunction("restartmap", "restartmap: restarts the current map", osdcmd_restartmap);
OSD_RegisterFunction("restartsound","restartsound: reinitializes the sound system",osdcmd_restartsound);
OSD_RegisterFunction("spawn","spawn <picnum> [palnum] [cstat] [ang] [x y z]: spawns a sprite with the given properties",osdcmd_spawn);

View file

@ -37,7 +37,7 @@ static FORCE_INLINE CONSTEXPR fix16_t fix16_from_int(int a) { return a * fix
static FORCE_INLINE CONSTEXPR float fix16_to_float(fix16_t a) { return (float)a / fix16_one; }
static FORCE_INLINE CONSTEXPR double fix16_to_dbl(fix16_t a) { return (double)a / fix16_one; }
static inline int fix16_to_int(fix16_t a)
static inline constexpr int fix16_to_int(fix16_t a)
{
#ifdef FIXMATH_NO_ROUNDING
return (a >> 16);

View file

@ -1344,7 +1344,7 @@ OptionMenu AdvSoundOptions //protected
Submenu "$SNDMNU_MIDIPLAYER", "MidiPlayerOptions"
Submenu "$SNDMNU_MODREPLAYER", "ModReplayerOptions"
StaticText " "
Command "$SNDMNU_RESTART", "restartsound"
Command "$SNDMNU_RESTART", "snd_reset"
}