code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT, sirlemonhead

This file is part of PCExhumed.

PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "compat.h"
#include "baselayer.h"
#include "renderlayer.h" // for win_gethwnd()
#include "build.h"
#include "cache1d.h"
#include "fx_man.h"
#include "keyboard.h"
#include "control.h"
#include "engine.h"
#include "exhumed.h"
#include "config.h"
#include "sound.h"
#include "init.h"
#include "object.h"
#include "player.h"
#include "random.h"
#include "snake.h"
#include "trigdat.h"
#include "sequence.h"
#include "cd.h"

#define kMaxFXVolume   255

#if 0
extern "C" {
#include "usrhooks.h"
#include "music.h"
#include "multivoc.h"
#include "fx_man.h"
#include "midi.h"
#include "mpu401.h"
}
#endif

short nSoundsPlaying = 0;
short nAmbientChannel = -1;

short nStopSound;
short nStoneSound;
short nSwitchSound;

short nLocalEyeSect;
short nElevSound;
short nCreepyTimer;

const char *SoundFiles[kMaxSoundFiles] =
{
  "spl_big",
  "spl_smal",
  "bubble_l",
  "grn_drop",
  "p_click",
  "grn_roll",
  "cosprite",
  "m_chant0",
  "anu_icu",
  "item_reg",
  "item_spe", // 10
  "item_key",
  "torch_on", // 12
  "jon_bnst",
  "jon_gasp",
  "jon_land",
  "jon_gags",
  "jon_fall",
  "jon_drwn",
  "jon_air1",
  "jon_glp1", // 20
  "jon_bbwl",
  "jon_pois",
  "amb_ston",
  "cat_icu",
  "bubble_h",
  "set_land",
  "jon_hlnd",
  "jon_laf2",
  "spi_jump",
  "jon_scub", // 30
  "item_use",
  "tr_arrow",
  "swi_foot",
  "swi_ston",
  "swi_wtr1",
  "tr_fire",
  "m_skull5",
  "spi_atak",
  "anu_hit",
  "fishdies", // 40
  "scrp_icu",
  "jon_wade",
  "amb_watr",
  "tele_1",
  "wasp_stg",
  "res",
  "drum4",
  "rex_icu",
  "m_hits_u",
  "q_tail", // 50
  "vatr_mov",
  "jon_hit3",
  "jon_t_2", // 53
  "jon_t_1",
  "jon_t_5",
  "jon_t_6",
  "jon_t_8",
  "jon_t_4",
  "rasprit1",
  "jon_fdie", // 60
  "wijaf1",
  "ship_1",
  "saw_on",
  "ra_on",
  "amb_ston", // 65
  "vatr_stp", // 66
  "mana1",
  "mana2",
  "ammo",
  "pot_pc1", // 70?
  "pot_pc2",
  "weapon",
  "alarm",
  "tick1",
  "scrp_zap", // 75
  "jon_t_3",
  "jon_laf1",
  "blasted",
  "jon_air2" // 79
};

short StaticSound[kMaxSoundFiles];

// TODO - temp location. Needs to exist within config file
//
// Sound variables
//
//int FXDevice;
//int MusicDevice;
//int FXVolume;
//int MusicVolume;
//int SoundToggle;
//int MusicToggle;
//int VoiceToggle;
//int AmbienceToggle;
//fx_blaster_config BlasterConfig;
//int NumVoices;
//int NumChannels;
//int NumBits;
//int MixRate;
//int32 MidiPort;
//int ReverseStereo;

int nNextFreq;
int nTotalSoundBytes;
int nSoundCount;
short nSwirlyFrames;

short nDistTable[256];

struct ActiveSound
{
    short nSprite;
    short nSound;
    short f_4; // volume
    short nAngle;
    short f_8; // volume
    short f_a;
    short f_c;
    int hFX; // ASS FX_() handle
    int f_12; // pitch
    int f_16; // pitch
    int nClock;
    int x;
    int y;
    int z;
    short nSector;
    short nChannel;
};

ActiveSound sActiveSound[kMaxActiveSounds];

#if 0
int AIL_allocate_sample_handle(int);
int AIL_allocate_sequence_handle(int);
void AIL_startup(void);
void AIL_set_preference(int, int);
int AIL_install_DIG_INI(void);
int AIL_install_MDI_INI(void);
void AIL_shutdown(void);
void AIL_end_sequence(int);
void AIL_set_sequence_volume(int, int, int);
void AIL_init_sequence(int, char*, int);
void AIL_start_sequence(int);
void AIL_set_sequence_loop_count(int, int);
void AIL_set_sequence_volume(int, int, int);
void AIL_set_sample_playback_rate(int, int);
void AIL_end_sample(int);
int AIL_sample_status(int);
void AIL_set_sample_volume(int, int);
void AIL_set_sample_pan(int, int);
void AIL_init_sample(int);
void AIL_set_sample_file(int, char*, int);
void AIL_start_sample(int);
void AIL_set_sample_loop_count(int, int);
int AIL_sample_playback_rate(int);
char AIL_error[256];
#endif
char pMusicBuf[45000];
char szSoundName[kMaxSounds][kMaxSoundNameLen];
char *SoundBuf[kMaxSounds];
int SoundLen[kMaxSounds];
char SoundLock[kMaxSounds];

extern char message_text[80];
extern short message_timer;

int S, dig, mdi, handle;
int nActiveSounds;

short nLocalSectFlags;
short nLocalChan;

uint8_t nPanTable[] = {
    0, 2, 4, 6, 8, 10, 12, 14,
    16, 18, 20, 22, 24, 26, 28, 30,
    32, 34, 36, 38, 40, 42, 44, 46,
    48, 50, 52, 54, 56, 58, 60, 62,
    64, 66, 68, 70, 72, 74, 76, 78,
    80, 82, 84, 86, 88, 90, 92, 94,
    96, 98, 100, 102, 104, 106, 108, 110,
    112, 114, 116, 118, 120, 122, 124, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128,
    128, 128, 128, 128, 128, 128, 128, 128
};

void CalcASSPan(int nPan, int nVolume, int *pLeft, int *pRight)
{
    if (nPan < 0)
        nPan = 0;
    else if (nPan > 127)
        nPan = 127;

    if (nVolume < 0)
        nVolume = 0;
    else if (nVolume > 127)
        nVolume = 127;

    *pLeft = mulscale6(nPanTable[nPan], nVolume);
    *pRight = mulscale6(nPanTable[127-nPan], nVolume);
}

void ASSCallback(intptr_t num)
{
    if ((int32_t)num == MUSIC_ID) {
        return;
    }

    // TODO: add mutex?
    if ((int32_t)num == -1)
        handle = -1;
    else if ((int32_t)num >= 0 && (int32_t)num < kMaxActiveSounds)
        sActiveSound[num].hFX = -1;
}

void CreateDistTable(void)
{
    int eax = 260;

    for (int i = 0; i < 256; i++)
    {
        if (eax > 65280)
        {
            nDistTable[i] = 255;
        }
        else
        {
            nDistTable[i] = eax >> 8;

            eax = (eax * eax) >> 8;
        }
    }
}

void InitSoundInfo(void)
{
    int i;
    memset(sActiveSound, 255, sizeof(sActiveSound));

    for (i = 0; i < kMaxActiveSounds; i++)
    {
        sActiveSound[i].nChannel = 0;
        sActiveSound[i].hFX = -1;
    }
    nActiveSounds = i;

    handle = -1;
}

void InitFX(void)
{
#ifdef MIXERTYPEWIN
    void* initdata = (void*)win_gethwnd(); // used for DirectSound
#else
    void* initdata = NULL;
#endif

    dig = 0;

    if (bNoSound)
        return;

    if (FX_Init(NumVoices, NumChannels, MixRate, initdata) != FX_Ok)
    {
        DebugOut("Error initializing sound card!\n");
        initprintf("Error initializing sound card!\n");
        DebugOut("ERROR: %s\n", FX_ErrorString(FX_Error));
        return;
    }

    dig = 1;

    FX_SetCallBack(ASSCallback);

    CreateDistTable();
    InitSoundInfo();

    nTotalSoundBytes = 0;
    nSoundCount = 0;
    nCreepyTimer = kCreepyCount;

    SetMasterFXVolume(FXVolume);

#if 0
    int status = FX_Init(FXDevice, NumVoices, NumChannels, NumBits, MixRate);
    if (status == FX_Ok)
    {
        FX_SetVolume(FXVolume);

        if (ReverseStereo == 1) {
            FX_SetReverseStereo(!FX_GetReverseStereo());
        }
    }

    if (status != FX_Ok) {
//		Error("Sound startup error: %s", FX_ErrorString(FX_Error));
    }

    status = FX_SetCallBack(testcallback);

    if (status != FX_Ok) {
//		Error("Sound startup error: %s", FX_ErrorString(FX_Error));
    }
#endif
}

void UnInitFX()
{
    FX_Shutdown();
}

#if 0
void InitMusic()
{
    if (bNoSound)
    {
        mdi = 0;
        return;
    }

    mdi = AIL_install_MDI_INI();
    if (!mdi)
    {
        initprintf("AIL_install midi failed\n");
        return;
    }
    S = AIL_allocate_sequence_handle(mdi);
    if (!S)
    {
        initprintf("Midi handle failed");
        return;
    }
}

void UnInitMusic()
{
    if (mdi)
        AIL_end_sequence(S);
}

void FadeSong()
{
    AIL_set_sequence_volume(S, 0, 1000);
}

int LoadSong(const char *song)
{
    FILE *f;
    if (!mdi)
        return 0;

    AIL_end_sequence(S);
    f = fopen(song, "rb");
    if (!f)
    {
        sprintf(message_text, "Unable to midi open file '%s'!\n", song);
        message_timer = 1000;
        return 0;
    }

    if (fread(pMusicBuf, sizeof(pMusicBuf), 1, f) == sizeof(pMusicBuf))
    {
        sprintf(message_text, "Programmer error: not enough memory allocated for song file.\n");
        message_timer = 1000;
        fclose(f);
        return 0;
    }
    fclose(f);

    AIL_init_sequence(S, pMusicBuf, 0);
    AIL_start_sequence(S);
    AIL_set_sequence_loop_count(S, 0);
    AIL_set_sequence_volume(S, gMusicVolume>>1, 0);
}
#else
void InitMusic()
{
}

void UnInitMusic()
{
}

void FadeSong()
{
}

int LoadSong(const char *song)
{
    UNREFERENCED_PARAMETER(song);
    return 0;
}
#endif

int LoadSound(const char *sound)
{
    if (!dig)
        //return 0;
        return -1;

    int i;

    for (i = 0; i < nSoundCount; i++)
    {
        if (!Bstrncasecmp(szSoundName[i], sound, kMaxSoundNameLen))
            return i;
    }

    if (i >= kMaxSounds)
        bail2dos("Too many sounds being loaded... increase array size\n");

    strncpy(szSoundName[i], sound, kMaxSoundNameLen);

    char buffer[BMAX_PATH];
    buffer[0] = 0;

    strncat(buffer, szSoundName[i], kMaxSoundNameLen);

    char *pzTail = buffer + strlen(buffer);
    while (*pzTail == ' ' && pzTail != buffer)
        *pzTail-- = '\0';

    static const char *soundfileformats[] = { ".ogg", ".wav", ".voc" };
    char sndfilename[BMAX_PATH];
    buildvfs_kfd hSnd = buildvfs_kfd_invalid;

    for (auto fmt : soundfileformats)
    {
        strcpy(sndfilename, buffer);
        strcat(sndfilename, fmt);

        hSnd = kopen4loadfrommod(sndfilename, 0);
        if (hSnd != buildvfs_kfd_invalid)
            break;
    }

    if (hSnd != buildvfs_kfd_invalid)
    {
        int nSize = kfilelength(hSnd);
        SoundLock[i] = 255; // TODO: implement cache lock properly
        SoundLen[i] = nSize;
        g_cache.allocateBlock((intptr_t*)&SoundBuf[i], nSize, &SoundLock[i]);

        if (!SoundBuf[i])
            bail2dos("Error allocating buf '%s' to %lld  (size=%ld)!\n", buffer, (intptr_t)&SoundBuf[i], nSize);

        if (kread(hSnd, SoundBuf[i], nSize) != nSize)
            bail2dos("Error reading '%s'!\n", buffer);
    }
    else
    {
        if (!ISDEMOVER) {
            bail2dos("Unable to open sound '%s'!\n", buffer); // demo tries to load sound files it doesn't have
        }

        SoundBuf[i] = NULL;
        SoundLen[i] = 0;
        return -1;
    }

    kclose(hSnd);
    nSoundCount++;
    return i;
}

#if 0
void FreeSounds(void)
{
    int i;
    for (i = 0; i < nSoundCount; i++)
        free(SoundBuf[i]);
}
#endif

void LoadFX(void)
{
    if (!dig)
        return;

    int i;
    for (i = 0; i < kMaxSoundFiles; i++)
    {
        StaticSound[i] = LoadSound(SoundFiles[i]);

        if (StaticSound[i] < 0)
            bail2dos("error loading static sound #%d ('%.8s')\n", i, SoundFiles[i]);
    }
}

void GetSpriteSoundPitch(short nSector, int *pVolume, int *pPitch)
{
    if (nSector < 0)
        return;

    if ((SectFlag[nSector] ^ nLocalSectFlags) & kSectUnderwater)
    {
        *pVolume >>= 1;
        *pPitch -= 1200;
    }
}

void BendAmbientSound(void)
{
    if (nAmbientChannel < 0)
        return;

    ActiveSound *pASound = &sActiveSound[nAmbientChannel];
    //AIL_set_sample_playback_rate(pASound->f_e, nDronePitch+11000);

    if (pASound->hFX > 0)
        FX_SetFrequency(pASound->hFX, nDronePitch+11000);
}

void CheckAmbience(short nSector)
{
    if (SectSound[nSector] != -1)
    {
        short nSector2 = SectSoundSect[nSector];
        walltype *pWall = &wall[sector[nSector2].wallptr];

        if (nAmbientChannel < 0)
        {
            PlayFXAtXYZ(SectSound[nSector]|0x4000, pWall->x, pWall->y, sector[nSector2].floorz, nSector);
            return;
        }

        ActiveSound *pASound = &sActiveSound[nAmbientChannel];

        if (nSector == nSector2)
        {
            spritetype *pSprite = &sprite[PlayerList[0].nSprite];
            pASound->x = pSprite->x;
            pASound->y = pSprite->y;
            pASound->z = pSprite->z;
        }
        else
        {
            pASound->x = pWall->x;
            pASound->y = pWall->y;
            pASound->z = sector[nSector2].floorz;
        }
    }
    else if (nAmbientChannel != -1)
    {
        if (sActiveSound[nAmbientChannel].hFX > 0)
            FX_StopSound(sActiveSound[nAmbientChannel].hFX);

        sActiveSound[nAmbientChannel].hFX = -1;
        nAmbientChannel = -1;
    }
}

int GetDistFromDXDY(int dx, int dy)
{
    int nSqr = dx*dx+dy*dy;
    return (nSqr>>3)-(nSqr>>5);
}

#if 0
void MuteSounds(void)
{
    if (!dig)
        return;

    int i;
    ActiveSound *pASound = sActiveSound;
    pASound++;
    for (i = 1; i < kMaxActiveSounds; i++, pASound++)
    {
        if (pASound->f_e > -1 && FX_SoundActive(pASound->f_e))
            FX_SetPan(pASound->f_e, 0, 0, 0);
    }
}

void SetChanPan(int nSound, int nPan)
{
    AIL_set_sample_pan(sActiveSound[nSound].f_e, nPan);
}
#endif

void SoundBigEntrance(void)
{
    StopAllSounds();
    ActiveSound *pASound = sActiveSound;

    for (int i = 0; i < 4; i++, pASound++)
    {
#if 0
        AIL_init_sample(pASound->f_e);
        short nPitch = i*512-1200;
        pASound->f_16 = nPitch;
        AIL_set_sample_playback_rate(pASound->f_e, 11000+nPitch);
        AIL_set_sample_file(pASound->f_e, SoundBuf[12], -1);
        AIL_set_sample_volume(pASound->f_e, 200);
        AIL_set_sample_pan(pASound->f_e, 63-(i&1)*127);
        AIL_start_sample(pASound->f_e);
#endif
        short nPitch = i*512-1200;
        pASound->f_16 = nPitch;
        int nLeft, nRight;
        CalcASSPan(63-(i&1)*127, 200, &nLeft, &nRight);

        if (pASound->hFX > 0)
            FX_StopSound(pASound->hFX);

        pASound->hFX = FX_Play(SoundBuf[kSoundTorchOn], SoundLen[kSoundTorchOn], -1, 0, 0, max(nLeft, nRight), nLeft, nRight, 0, fix16_one, i);

        if (pASound->hFX > 0)
            FX_SetFrequency(pASound->hFX, 11000+nPitch);
    }
}

void StartSwirly(int nActiveSound)
{
    ActiveSound *pASound = &sActiveSound[nActiveSound];
    pASound->nAngle &= kAngleMask;

    //AIL_init_sample(pASound->f_e);
    short nPitch = nNextFreq - RandomSize(9);
    pASound->f_16 = nPitch;

    nNextFreq = 25000 - RandomSize(10) * 6;
    if (nNextFreq > 32000)
        nNextFreq = 32000;

    //AIL_set_sample_file(pASound->f_e, SoundBuf[StaticSound[kSoundMana1]], -1);

    int nVolume = nSwirlyFrames+1;
    if (nVolume >= 220)
        nVolume = 220;

    pASound->f_4 = nVolume;

    int nPan = pASound->nAngle & 127;
    int nLeft, nRight;

    CalcASSPan(nPan, nVolume, &nLeft, &nRight);

    if (pASound->hFX > 0)
        FX_StopSound(pASound->hFX);

    pASound->hFX = FX_Play(SoundBuf[StaticSound[kSoundMana1]], SoundLen[StaticSound[kSoundMana1]], -1, 0, 0, max(nLeft, nRight), nLeft, nRight, 0, fix16_one, nActiveSound);

//    if (pASound->hFX > 0)
//y        FX_SetFrequency(pASound->hFX, nPitch);

#if 0
    AIL_set_sample_volume(pASound->f_e, nVolume);
    AIL_set_sample_playback_rate(pASound->f_e, nPitch);
    AIL_set_sample_loop_count(pASound->f_e, 1);
    AIL_set_sample_pan(pASound->f_e, pASound->f_6);
    AIL_start_sample(pASound->f_e);
#endif
}

void StartSwirlies()
{
    StopAllSounds();

    nNextFreq = 19000;
    nSwirlyFrames = 0;

    for (int i = 1; i <= 4; i++)
        StartSwirly(i);
}

void UpdateSwirlies()
{
    nSwirlyFrames++;
    ActiveSound* pASound = sActiveSound;
    pASound++;

    for (int i = 1; i <= 4; i++, pASound++)
    {
        if (pASound->hFX <= 0 || !FX_SoundActive(pASound->hFX))
            StartSwirly(i);

        if (pASound->hFX > 0)
        {
            int nLeft, nRight;
            int nPan = 64+(Sin((int)totalclock<<(4+i))>>8);
            CalcASSPan(nPan, pASound->f_4, &nLeft, &nRight);
            FX_SetPan(pASound->hFX, max(nLeft, nRight), nLeft, nRight);
            FX_SetFrequency(pASound->hFX, pASound->f_16);
        }
        //AIL_set_sample_pan(pASound->f_e, 64+(Sin((int)totalclock<<(4+i))>>8));
    }
}

void UpdateSounds()
{
    if (!dig || nFreeze)
        return;

    nLocalSectFlags = SectFlag[nPlayerViewSect[nLocalPlayer]];
//    spritetype *pSprite = &sprite[PlayerList[nLocalPlayer].nSprite];
    int x, y;
    short ang;

    if (nSnakeCam >= 0)
    {
        Snake *pSnake = &SnakeList[nSnakeCam];
        spritetype *pSnakeSprite = &sprite[pSnake->nSprites[0]];
        x = pSnakeSprite->x;
        y = pSnakeSprite->y;
        ang = pSnakeSprite->ang;
    }
    else
    {
        x = initx;
        y = inity;
        ang = inita;
    }

    ActiveSound* pASound = sActiveSound;
    pASound++;

    for (int i = 1; i < kMaxActiveSounds; i++, pASound++)
    {
        if (FX_SoundValidAndActive(pASound->hFX))
        {
            short nSoundSprite = pASound->nSprite;
            int dx, dy;
            if (nSoundSprite < 0)
            {
                dx = x-pASound->x;
                dy = y-pASound->y;
            }
            else
            {
                dx = x-sprite[nSoundSprite].x;
                dy = y-sprite[nSoundSprite].y;
            }

            dx >>= 8;
            dy >>= 8;

            short nSoundAng;
            if ((dx|dy) == 0)
                nSoundAng = 0;
            else
                nSoundAng = AngleDelta(GetMyAngle(dx, dy), ang, 1024);

            int nDist = GetDistFromDXDY(dx, dy);
            if (nDist >= 255)
            {
                FX_StopSound(pASound->hFX);
                if (pASound->f_a&0x4000)
                    nAmbientChannel = -1;
                return;
            }

            int nVolume = kMaxFXVolume - nDist;
            if (nVolume < 0)
                nVolume = 0;
            if (nVolume > kMaxFXVolume)
                nVolume = kMaxFXVolume;

            int nPitch = pASound->f_16;
            short nSoundSect;
            if (nSoundSprite >= 0)
            {
                if (nSoundSprite == nLocalSpr)
                    nSoundSect = nPlayerViewSect[nLocalPlayer];
                else
                    nSoundSect = sprite[nSoundSprite].sectnum;
            }
            else
                nSoundSect = pASound->nSector;

            GetSpriteSoundPitch(nSoundSect, &nVolume, &nPitch);

            if (pASound->f_12 != nPitch)
                pASound->f_12 = nPitch;

            if (nVolume != pASound->f_4 || nSoundAng != pASound->nAngle)
            {
                int nLeft, nRight;
                int nPan = 63+(Sin(nSoundAng+1023)>>8);
                CalcASSPan(nPan, nVolume, &nLeft, &nRight);
                FX_SetPan(pASound->hFX, nVolume, nLeft, nRight);

                if (nPitch < 0)
                    FX_SetFrequency(pASound->hFX, 7000);

                pASound->f_4 = nVolume;
                pASound->nAngle = nSoundAng;
            }
        }
    }
}

void UpdateCreepySounds()
{
    if (levelnum == 20 || nFreeze)
        return;

    spritetype *pSprite = &sprite[PlayerList[nLocalPlayer].nSprite];
    nCreepyTimer--;

    if (nCreepyTimer <= 0)
    {
        if (nCreaturesLeft > 0 && !(SectFlag[nPlayerViewSect[nLocalPlayer]] & 0x2000))
        {
            int vsi = seq_GetFrameSound(SeqOffsets[kSeqCreepy], totalmoves % SeqSize[SeqOffsets[kSeqCreepy]]);

            if (vsi >= 0 && (vsi&0x1ff) < kMaxSounds)
            {
                int vdx = (totalmoves+32)&31;

                if (totalmoves & 1)
                    vdx = -vdx;

                int vax = (totalmoves+32)&63;

                if (totalmoves & 2)
                    vax = -vax;

                PlayFXAtXYZ(vsi, pSprite->x+vdx, pSprite->y+vax, pSprite->z, pSprite->sectnum);
            }
        }
        nCreepyTimer = kCreepyCount;
    }
}

int LocalSoundPlaying(void)
{
    if (!dig)
        return 0;

    return sActiveSound[nLocalChan].hFX > 0 && FX_SoundActive(sActiveSound[nLocalChan].hFX);
}

int GetLocalSound(void)
{
    if (LocalSoundPlaying() == -1)
        return -1;

    return sActiveSound[nLocalChan].nSound & 0x1ff;
}

void UpdateLocalSound(void)
{
    if (!dig)
        return;

    if (sActiveSound[nLocalChan].hFX > 0)
        FX_SetPan(sActiveSound[nLocalChan].hFX, kMaxFXVolume, kMaxFXVolume, kMaxFXVolume);
}

void StopLocalSound(void)
{
    if (!dig)
        return;

    if (nLocalChan == nAmbientChannel)
        nAmbientChannel = -1;

    if (LocalSoundPlaying())
        FX_StopSound(sActiveSound[nLocalChan].hFX);
}

void SetLocalChan(int nChannel)
{
    nLocalChan = nChannel;
}

void PlaySound(int nSound)
{
    if (!dig)
        return;

    if (nSound < 0 || nSound >= kMaxSounds || !SoundBuf[nSound])
    {
        initprintf("PlaySound: Invalid sound nSound == %i\n", nSound);
        return;
    }

    int bLoop = SoundBuf[nSound][26] == 6;

    if (handle >= 0)
        FX_StopSound(handle);

    handle = FX_Play(SoundBuf[nSound], SoundLen[nSound], bLoop ? 0 : -1, 0, 0, kMaxFXVolume, kMaxFXVolume, kMaxFXVolume, 0, fix16_one, -1);

#if 0
    AIL_init_sample(handle);
    AIL_set_sample_file(handle, SoundBuf[nSound], -1);
    AIL_set_sample_volume(handle, kMaxFXVolume >>1);

    if (SoundBuf[nSound][26] == 6)
        AIL_set_sample_loop_count(handle, 0);

    AIL_start_sample(handle);
#endif
}

void SetMasterFXVolume(int nVolume)
{
    if (nVolume > 255)
        nVolume = 255;
    if (nVolume < 0)
        nVolume = 0;

    FX_SetVolume(nVolume);
}

void PlayLocalSound(short nSound, short nRate)
{
    if (!SoundToggle)
        return;

    if (!dig)
        return;

    if (nSound < 0 || nSound >= kMaxSounds || !SoundBuf[nSound])
    {
        initprintf("PlayLocalSound: Invalid sound nSound == %i, nRate == %i\n", nSound, nRate);
        return;
    }

    if (nLocalChan == nAmbientChannel)
        nAmbientChannel = -1;

    int bLoop = SoundBuf[nSound][26] == 6;

    ActiveSound* pASound = &sActiveSound[nLocalChan];

    if (pASound->hFX > 0)
        FX_StopSound(pASound->hFX);

    pASound->hFX = FX_Play(SoundBuf[nSound], SoundLen[nSound], bLoop ? 0 : -1, 0, 0, kMaxFXVolume, kMaxFXVolume, kMaxFXVolume, 0, fix16_one, nLocalChan);

    if (nRate)
    {
        int nFreq = 0;
        FX_GetFrequency(pASound->hFX, &nFreq);
        FX_SetFrequency(pASound->hFX, nFreq+nRate);
    }
#if 0
    AIL_init_sample(pASound->f_e);
    AIL_set_sample_file(pASound->f_e, SoundBuf[nSound], -1);
    AIL_set_sample_volume(pASound->f_e, kMaxFXVolume >>1);

    if (nRate)
        AIL_set_sample_playback_rate(pASound->f_e, AIL_sample_playback_rate(pASound->f_e)+nRate);

    if (SoundBuf[nSound][26] == 6)
        AIL_set_sample_loop_count(pASound->f_e, 0);

    AIL_start_sample(pASound->f_e);
#endif
    pASound->nSound = nSound;
    SetLocalChan(0);
}

void PlayTitleSound(void)
{
    PlayLocalSound(StaticSound[kSoundItemSpecial], 0);
}

void PlayLogoSound(void)
{
    PlayLocalSound(StaticSound[kSoundJonLaugh2], 7000);
}

void PlayGameOverSound(void)
{
    PlayLocalSound(StaticSound[kSoundJonLaugh2], 0);
}

int soundx, soundy, soundz;
short soundsect;

short PlayFX2(unsigned short nSound, short nSprite)
{
    if (!SoundToggle)
        return -1;

    if (!dig)
        return -1;

    if ((nSound&0x1ff) >= kMaxSounds || !SoundBuf[(nSound&0x1ff)])
    {
        initprintf("PlayFX2: Invalid sound nSound == %i, nSprite == %i\n", nSound, nSprite);
        return -1;
    }

    nLocalSectFlags = SectFlag[nPlayerViewSect[nLocalPlayer]];
    short v1c = 0;
    short vcx = 0;

    if (nSprite >= 0)
    {
        v1c = nSprite & 0x2000;
        vcx = nSprite & 0x4000;
        nSprite &= 0xfff;
        soundx = sprite[nSprite].x;
        soundy = sprite[nSprite].y;
        soundz = sprite[nSprite].z;
        soundsect = sprite[nSprite].sectnum;
    }

    int dx = (initx - soundx) >> 8;
    int dy = (inity - soundy) >> 8;

    short nSoundAng = 0;

    if (dx || dy) {
        nSoundAng = AngleDelta(GetMyAngle(dx, dy), inita, 1024);
    }

    int nDist = GetDistFromDXDY(dx, dy);
    if (nDist >= 255)
    {
        if (nSprite > -1)
            StopSpriteSound(nSprite);

        return -1;
    }

    int nVolume;

    if (!v1c)
    {
        nVolume = kMaxFXVolume - nDist;
        if (nVolume <= 0)
        {
            if (nSprite > -1)
                StopSpriteSound(nSprite);
            return -1;
        }
        if (nVolume > kMaxFXVolume)
            nVolume = kMaxFXVolume;
    }
    else
        nVolume = kMaxFXVolume;

    short vc = nSound & (~0x1ff);
    short v4 = nSound & 0x2000;
    short v8 = nSound & 0x1000;
    short v14 = nSound & 0x4000;
    short v10 = (nSound & 0xe00)>>9;
    int v2c = 0x7fffffff;
    ActiveSound* v38 = NULL;
    ActiveSound* v28 = NULL;
    ActiveSound* vdi = NULL;
    nSound &= 0x1ff;

    short v20;

    if (v8 || v14)
        v20 = 1000;
    else if (nSprite != -1 && vcx)
        v20 = 2000;
    else
        v20 = 0;

    ActiveSound* pASound = sActiveSound;
    pASound++;

    for (int i = 1; i < kMaxActiveSounds; i++, pASound++)
    {
        if (pASound->hFX <= 0 || !FX_SoundActive(pASound->hFX))
            vdi = pASound;
        else if (v20 >= pASound->f_c)
        {
            if (v2c > pASound->nClock && pASound->f_c <= v20)
            {
                v28 = pASound;
                v2c = pASound->nClock;
            }
            if (!v8)
            {
                if (nSound == pASound->nSound)
                {
                    if (v4 == 0 && nSprite == pASound->nSprite)
                        return -1;

                    if (v20 >= pASound->f_c)
                        v38 = pASound;
                }
                else if (nSprite == pASound->nSprite)
                {
                    if (v4 || nSound != pASound->nSound)
                    {
                        vdi = pASound;
                        break;
                    }
                }
            }
        }
    }

    if (!vdi)
    {
        if (v38)
            vdi = v38;
        else if (v28)
            vdi = v28;
    }

    if (FX_SoundValidAndActive(vdi->hFX))
    {
        FX_StopSound(vdi->hFX);
        if (vdi->nChannel == nAmbientChannel)
            nAmbientChannel = -1;
    }

    int nPitch;
    if (v10)
        nPitch = -(totalmoves&((1<<v10)-1))*16;
    else
        nPitch = 0;

    if (vdi)
    {
        vdi->f_16 = nPitch;
        vdi->f_8 = nVolume;

        if (nSprite < 0)
        {
            vdi->x = soundx;
            vdi->y = soundy;
            vdi->nSector = soundsect;
        }

        GetSpriteSoundPitch(soundsect, &nVolume, &nPitch);

        vdi->f_12 = nPitch;
        vdi->f_4 = nVolume;
        vdi->nAngle = nSoundAng;
        vdi->nSprite = nSprite;
        vdi->nSound = nSound;
        vdi->nClock = (int)totalclock;
        vdi->f_c = v20;
        vdi->f_a = vc;
        short nPan = 63+(Sin(nSoundAng+1023)>>8);
        int nLeft, nRight;

        int bLoop = SoundBuf[nSound][26] == 6;

        CalcASSPan(nPan, nVolume>>1, &nLeft, &nRight);

        vdi->hFX = FX_Play(SoundBuf[nSound], SoundLen[nSound], bLoop ? 0 : -1, 0, 0, max(nLeft, nRight), nLeft, nRight, 0, fix16_one, vdi-sActiveSound);

        if (nPitch)
        {
            int nFreq = 0;
            FX_GetFrequency(vdi->hFX, &nFreq);
            FX_SetFrequency(vdi->hFX, nFreq+nPitch);
        }
#if 0
        AIL_init_sample(vdi->f_e);
        AIL_set_sample_file(vdi->f_e, SoundBuf[nSound], -1);
        AIL_set_sample_pan(vdi->f_e, nPan);
        AIL_set_sample_volume(vdi->f_e, nVolume>>1);

        if (SoundBuf[nSound][26] == 6)
            AIL_set_sample_loop_count(vdi->f_e, 0);

        if (nPitch)
            AIL_set_sample_playback_rate(vdi->f_e, AIL_sample_playback_rate(vdi->f_e)+nPitch);

        AIL_start_sample(vdi->f_e);
#endif
        if (v14)
            nAmbientChannel = v14;

        // Nuke: added nSprite >= 0 check
        if (nSprite != nLocalSpr && nSprite >= 0 && (sprite[nSprite].cstat & 257))
            nCreepyTimer = kCreepyCount;

        return v14;
    }
    return -1;
}

short PlayFXAtXYZ(unsigned short nSound, int x, int y, int z, int nSector)
{
    soundx = x;
    soundy = y;
    soundz = z;
    soundsect = nSector & 0x3fff;
    short nSnd = PlayFX2(nSound, -1);

    if (nSnd > -1 && (nSector & 0x4000))
        sActiveSound[nSnd].f_c = 2000;

    return nSnd;
}

short D3PlayFX(unsigned short nSound, short nSprite)
{
    return PlayFX2(nSound, nSprite);
}

void StopSpriteSound(short nSprite)
{
    if (!dig)
        return;

    for (int i = 0; i < kMaxActiveSounds; i++)
    {
        if (FX_SoundValidAndActive(sActiveSound[i].hFX) && nSprite == sActiveSound[i].nSprite)
        {
            FX_StopSound(sActiveSound[i].hFX);
            return;
        }
    }
}

void StopAllSounds(void)
{
    if (!dig)
        return;

    for (int i = 0; i < kMaxActiveSounds; i++)
    {
        if (sActiveSound[i].hFX > 0)
            FX_StopSound(sActiveSound[i].hFX);
        // AIL_end_sample(sActiveSound[i].hFX);
    }

    nSoundsPlaying = 0;
    nAmbientChannel = -1;
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT

This file is part of PCExhumed.

PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#ifndef __sound_h__
#define __sound_h__

#define kMaxSoundFiles      80
#define kMaxSounds          200
#define kMaxSoundNameLen    8
#define kMaxActiveSounds    8

#define kCreepyCount 150

#define MUSIC_ID    (-65536)

enum {
    kSoundSplashBig = 0,
    kSoundSplashSmall,
    kSoundBubbleLow,
    kSoundGrenadeDrop,
    kSoundPistolClick,
    kSoundGrenadeRoll,
    kSoundCobraSprite,
    kSoundMummyChant0,
    kSoundAnubisICU,
    kSound9,
    kSoundItemSpecial,
    kSound11,
    kSoundTorchOn,
    kSoundJonBubbleNest,
    kSoundJonGasp,
    kSound15,
    kSound16,
    kSoundJonFall,
    kSound18,
    kSoundJonAir1,
    kSound20,
    kSound21,
    kSound22,
    kSoundAmbientStone,
    kSoundCatICU,
    kSoundBubbleHigh,
    kSoundSetLand,
    kSoundJonHLand,
    kSoundJonLaugh2,
    kSoundSpiderJump,
    kSoundJonScuba,
    kSoundItemUse,
    kSoundTrapArrow,
    kSoundSwitchFoot,
    kSound34,
    kSoundSwitchWtr1,
    kSoundTrapFire,
    kSoundSpiderAttack = 38,
    kSoundAnubisHit,
    kSoundFishDies,
    kSoundScorpionICU,
    kSoundJonWade,
    kSoundAmbientWater,
    kSoundDrum4 = 47,
    kSoundRexICU = 48,
    kSoundQTail = 50,
    kSoundJonHit3 = 52,
    kSoundTauntStart = 53,
    kSoundJonFDie = 60,
    kSoundWhyIsJeffAFeeb,
    kSoundShip1,
    kSoundSawOn,
    kSound64,
    kSound65,
    kSound66,
    kSoundMana1,
    kSoundMana2,
    kSoundAmmoPickup,
    kSound70,
    kSoundPotPc1,
    kSoundWeapon,
    kSoundAlarm,
    kSoundTick1,
    kSoundScorpionZap,
    kSoundJonTaunt3,
    kSoundJonLaugh1,
    kSoundBlasted,
    kSoundJonAir2,
};

extern short nAmbientChannel;
extern short nStopSound;
extern short nStoneSound;
extern short nSwitchSound;
extern short nLocalEyeSect;
extern short nElevSound;
extern short nCreepyTimer;

extern short StaticSound[];

void UpdateSounds();
void UpdateCreepySounds();

void InitFX();
void UnInitFX();
void FadeSong();
int LocalSoundPlaying();
void LoadFX();
void StopAllSounds();
void SetLocalChan(int nChannel);
int GetLocalSound();
void UpdateLocalSound();
void StopLocalSound();
void PlayLocalSound(short nSound, short val);
int LoadSound(const char* sound);

void BendAmbientSound();
void CheckAmbience(short nSector);

short PlayFX2(unsigned short nSound, short nSprite);
short PlayFXAtXYZ(unsigned short nSound, int x, int y, int z, int nSector);
short D3PlayFX(unsigned short nSound, short nSprite);
void StopSpriteSound(short nSprite);

void StartSwirlies();
void UpdateSwirlies();

void PlayLogoSound(void);
void PlayTitleSound(void);
void PlayGameOverSound(void);

void SoundBigEntrance(void);

void SetMasterFXVolume(int nVolume);

#endif

repo_name: orochi/nblood

license: mit


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT

This file is part of PCExhumed.

PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "spider.h"
#include "exhumed.h"
#include "engine.h"
#include "runlist.h"
#include "move.h"
#include "sequence.h"
#include "random.h"
#include "sound.h"
#include "trigdat.h"
#include <assert.h>

#include "save.h"

short SpiderCount = 0;

#define kMaxSpiders 100

struct Spider
{
    short nHealth;
    short nFrame;
    short nAction;
    short nSprite;
    short nTarget;
    short nRun;
};

Spider SpiderList[kMaxSpiders];

static actionSeq ActionSeq[] = {
    {16, 0},
    {8,  0},
    {32, 0},
    {24, 0},
    {0,  0},
    {40, 1},
    {41, 1}
};

void InitSpider()
{
    SpiderCount = 0;
}

int GetSpiderSprite(int nSpider)
{
    assert (nSpider >= 0 && nSpider < kMaxSpiders);
    return SpiderList[nSpider].nSprite;
}

int BuildSpider(int nSprite, int x, int y, int z, short nSector, int nAngle)
{
    int nSpider = SpiderCount++;
    if (nSpider >= kMaxSpiders) {
        return -1;
    }

    if (nSprite == -1)
    {
        nSprite = insertsprite(nSector, 99);
    }
    else
    {
        changespritestat(nSprite, 99);
        x = sprite[nSprite].x;
        y = sprite[nSprite].y;
        z = sprite[nSprite].z;
        nAngle = sprite[nSprite].ang;
    }

    assert(nSprite >= 0 && nSprite < kMaxSprites);

    sprite[nSprite].x = x;
    sprite[nSprite].y = y;
    sprite[nSprite].z = z;
    sprite[nSprite].cstat = 0x101;
    sprite[nSprite].shade = -12;
    sprite[nSprite].clipdist = 15;
    sprite[nSprite].xvel = 0;
    sprite[nSprite].yvel = 0;
    sprite[nSprite].zvel = 0;
    sprite[nSprite].xrepeat = 40;
    sprite[nSprite].yrepeat = 40;
    sprite[nSprite].pal = sector[sprite[nSprite].sectnum].ceilingpal;
    sprite[nSprite].xoffset = 0;
    sprite[nSprite].yoffset = 0;
    sprite[nSprite].ang = nAngle;
    sprite[nSprite].picnum = 1;
    sprite[nSprite].hitag = 0;
    sprite[nSprite].lotag = runlist_HeadRun() + 1;
    sprite[nSprite].extra = -1;

    //	GrabTimeSlot(3);

    SpiderList[nSpider].nAction = 0;
    SpiderList[nSpider].nFrame = 0;
    SpiderList[nSpider].nSprite = nSprite;
    SpiderList[nSpider].nTarget = -1;
    SpiderList[nSpider].nHealth = 160;

    sprite[nSprite].owner = runlist_AddRunRec(sprite[nSprite].lotag - 1, nSpider, kRunSpider);

    SpiderList[nSpider].nRun = runlist_AddRunRec(NewRun, nSpider, kRunSpider);

    nCreaturesLeft++;

    return nSpider;
}

void FuncSpider(int a, int nDamage, int nRun)
{
    short nSpider = RunData[nRun].nVal;
    assert(nSpider >= 0 && nSpider < kMaxSpiders);

    int nVel = 0;

    short nSprite = SpiderList[nSpider].nSprite;
    short nAction = SpiderList[nSpider].nAction;

    int nMessage = a & kMessageMask;

    switch (nMessage)
    {
        default:
        {
            DebugOut("unknown msg %d for Spider\n", nMessage);
            break;
        }

        case 0x20000:
        {
            nVel = 6;

            if (SpiderList[nSpider].nHealth)
            {
                if (sprite[nSprite].cstat & 8)
                {
                    sprite[nSprite].z = sector[sprite[nSprite].sectnum].ceilingz + GetSpriteHeight(nSprite);
                }
                else
                {
                    Gravity(nSprite);
                }
            }

            int nSeq = SeqOffsets[kSeqSpider] + ActionSeq[nAction].a;

            sprite[nSprite].picnum = seq_GetSeqPicnum2(nSeq, SpiderList[nSpider].nFrame);

            seq_MoveSequence(nSprite, nSeq, SpiderList[nSpider].nFrame);

            int nFrameFlag = FrameFlag[SeqBase[nSeq] + SpiderList[nSpider].nFrame];

            SpiderList[nSpider].nFrame++;
            if (SpiderList[nSpider].nFrame >= SeqSize[nSeq]) {
                SpiderList[nSpider].nFrame = 0;
            }

            short nTarget = SpiderList[nSpider].nTarget;

            if (nTarget <= -1 || sprite[nTarget].cstat & 0x101)
            {
                switch (nAction)
                {
                    default:
                        return;

                    case 0:
                    {
                        if ((nSpider & 0x1F) == (totalmoves & 0x1F))
                        {
                            if (nTarget < 0) {
                                nTarget = FindPlayer(nSprite, 100);
                            }

                            if (nTarget >= 0)
                            {
                                SpiderList[nSpider].nAction = 1;
                                SpiderList[nSpider].nFrame = 0;
                                SpiderList[nSpider].nTarget = nTarget;

                                sprite[nSprite].xvel = Cos(sprite[nSprite].ang);
                                sprite[nSprite].yvel = sintable[sprite[nSprite].ang]; // NOTE - not angle masking here in original code
                                return;
                            }
                        }

                        break;
                    }
                    case 1:
                    {
                        if (nTarget >= 0) {
                            nVel++;
                        }
        goto case_3;
                        break;
                    }
                    case 4:
                    {
                        if (!SpiderList[nSpider].nFrame)
                        {
                            SpiderList[nSpider].nFrame  = 0;
                            SpiderList[nSpider].nAction = 1;
                        }
                        fallthrough__;
                    }
                    case 3:
                    {
        case_3:
                        short nSector = sprite[nSprite].sectnum;

                        if (sprite[nSprite].cstat & 8)
                        {
                            sprite[nSprite].zvel = 0;
                            sprite[nSprite].z = sector[nSector].ceilingz + (tilesiz[sprite[nSprite].picnum].y << 5);

                            if (sector[nSector].ceilingstat & 1)
                            {
                                sprite[nSprite].cstat ^= 8;
                                sprite[nSprite].zvel = 1;

                                SpiderList[nSpider].nAction = 3;
                                SpiderList[nSpider].nFrame  = 0;
                            }
                        }

                        if ((totalmoves & 0x1F) == (nSpider & 0x1F))
                        {
                            PlotCourseToSprite(nSprite, nTarget);

                            if (RandomSize(3))
                            {
                                sprite[nSprite].xvel = Cos(sprite[nSprite].ang);
                                sprite[nSprite].yvel = Sin(sprite[nSprite].ang);
                            }
                            else
                            {
                                sprite[nSprite].xvel = 0;
                                sprite[nSprite].yvel = 0;
                            }

                            if (SpiderList[nSpider].nAction == 1 && RandomBit())
                            {
                                if (sprite[nSprite].cstat & 8)
                                {
                                    sprite[nSprite].cstat ^= 8;
                                    sprite[nSprite].zvel = 1;
                                    sprite[nSprite].z = sector[nSector].ceilingz + GetSpriteHeight(nSprite);
                                }
                                else
                                {
                                    sprite[nSprite].zvel = -5120;
                                }

                                SpiderList[nSpider].nAction = 3;
                                SpiderList[nSpider].nFrame = 0;

                                if (!RandomSize(3)) {
                                    D3PlayFX(StaticSound[kSoundSpiderJump], nSprite);
                                }
                            }
                        }
                        break;
                    }
                    case 5:
                    {
                        if (!SpiderList[nSpider].nFrame)
                        {
                            runlist_DoSubRunRec(sprite[nSprite].owner);
                            runlist_FreeRun(sprite[nSprite].lotag - 1);
                            runlist_SubRunRec(SpiderList[nSpider].nRun);
                            sprite[nSprite].cstat = 0x8000;
                            mydeletesprite(nSprite);
                        }
                        return;
                    }
                    case 2:
                    {
                        if (nTarget != -1)
                        {
                            if (nFrameFlag & 0x80)
                            {
                                runlist_DamageEnemy(nTarget, nSprite, 3);
                                D3PlayFX(StaticSound[kSoundSpiderAttack], nSprite);
                            }

                            if (PlotCourseToSprite(nSprite, nTarget) < 1024) {
                                return;
                            }

                            SpiderList[nSpider].nAction = 1;
                        }
                        else
                        {
                            SpiderList[nSpider].nAction = 0;
                            sprite[nSprite].xvel = 0;
                            sprite[nSprite].yvel = 0;
                        }

                        SpiderList[nSpider].nFrame = 0;
                        break;
                    }
                }
            }
            else
            {
                SpiderList[nSpider].nTarget = -1;
                SpiderList[nSpider].nAction = 0;
                SpiderList[nSpider].nFrame = 0;

                sprite[nSprite].xvel = 0;
                sprite[nSprite].yvel = 0;
            }

            int nMov = movesprite(nSprite, sprite[nSprite].xvel << nVel, sprite[nSprite].yvel << nVel, sprite[nSprite].zvel, 1280, -1280, CLIPMASK0);

            if (!nMov)
                return;

            if (nMov & 0x10000
                && sprite[nSprite].zvel < 0
                && (hihit & 0xC000) != 0xC000
                && !((sector[sprite[nSprite].sectnum].ceilingstat) & 1))
            {
                sprite[nSprite].cstat |= 8;
                sprite[nSprite].z = GetSpriteHeight(nSprite) + sector[sprite[nSprite].sectnum].ceilingz;
                sprite[nSprite].zvel = 0;

                SpiderList[nSpider].nAction = 1;
                SpiderList[nSpider].nFrame = 0;
                return;
            }
            else
            {
                switch (nMov & 0xC000)
                {
                    case 0x8000:
                    {
                        sprite[nSprite].ang = (sprite[nSprite].ang + 256) & 0x7EF;
                        sprite[nSprite].xvel = Cos(sprite[nSprite].ang);
                        sprite[nSprite].yvel = Sin(sprite[nSprite].ang);
                        return;
                    }
                    case 0xC000:
                    {
                        if ((nMov & 0x3FFF) == nTarget)
                        {
                            int nAng = getangle(sprite[nTarget].x - sprite[nSprite].x, sprite[nTarget].y - sprite[nSprite].y);
                            if (AngleDiff(sprite[nSprite].ang, nAng) < 64)
                            {
                                SpiderList[nSpider].nAction = 2;
                                SpiderList[nSpider].nFrame = 0;
                            }
                        }
                        return;
                    }
                    default:
                        break;
                }

                if (SpiderList[nSpider].nAction == 3)
                {
                    SpiderList[nSpider].nAction = 1;
                    SpiderList[nSpider].nFrame = 0;
                }
                return;
            }

            return;
        }

        case 0x90000:
        {
            seq_PlotSequence(a & 0xFFFF, SeqOffsets[kSeqSpider] + ActionSeq[nAction].a, SpiderList[nSpider].nFrame, ActionSeq[nAction].b);
            break;
        }

        case 0xA0000:
        {
            if (SpiderList[nSpider].nHealth <= 0)
                return;

            nDamage = runlist_CheckRadialDamage(nSprite);
            // fall through
            fallthrough__;
        }

        case 0x80000:
        {
            if (!nDamage)
                return;

            short nTarget = a & 0xFFFF;

            SpiderList[nSpider].nHealth -= nDamage;
            if (SpiderList[nSpider].nHealth > 0)
            {
                /*
                NOTE:
                    nTarget check was added, but should we return if it's invalid instead
                    or should code below (action set, b set) happen?
                    Other AI doesn't show consistency in this regard (see Scorpion code)
                */
                if (nTarget > -1 && sprite[nTarget].statnum == 100)
                {
                    SpiderList[nSpider].nTarget = nTarget;
                }

                SpiderList[nSpider].nAction = 4;
                SpiderList[nSpider].nFrame  = 0;
            }
            else
            {
                // creature is dead, make some chunks
                SpiderList[nSpider].nHealth = 0;
                SpiderList[nSpider].nAction = 5;
                SpiderList[nSpider].nFrame  = 0;

                sprite[nSprite].cstat &= 0xFEFE;

                nCreaturesLeft--;

                for (int i = 0; i < 7; i++)
                {
                    BuildCreatureChunk(nSprite, seq_GetSeqPicnum(kSeqSpider, i + 41, 0));
                }
            }

            return;
        }
    }
}

class SpiderLoadSave : public LoadSave
{
public:
    virtual void Load();
    virtual void Save();
};

void SpiderLoadSave::Load()
{
    Read(&SpiderCount, sizeof(SpiderCount));
    Read(SpiderList, sizeof(Spider) * SpiderCount);
}

void SpiderLoadSave::Save()
{
    Write(&SpiderCount, sizeof(SpiderCount));
    Write(SpiderList, sizeof(Spider) * SpiderCount);
}

static SpiderLoadSave* myLoadSave;

void SpiderLoadSaveConstruct()
{
    myLoadSave = new SpiderLoadSave();
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT

This file is part of PCExhumed.

PCExhumed is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#ifndef __spider_h__
#define __spider_h__

#include "aistuff.h"

void InitSpider();
int GetSpiderSprite(int nSpider);
int BuildSpider(int nSprite, int x, int y, int z, short nSector, int nAngle);
void FuncSpider(int a, int b, int nRun);

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#include "build.h"
#include "common.h"
#include "compat.h"
#include "keyboard.h"
#include "control.h"
#include "config.h"
#include "exhumed.h"
#include "dynamicgtk.h"
#include "grpscan.h"
#include "gtkpixdata.h"

enum
{
    NONE,
    ALL,
    POPULATE_VIDEO,
    POPULATE_CONFIG,
    POPULATE_GAME,
};

enum
{
    TAB_CONFIG,
    TAB_GAME,
    TAB_MESSAGES,
};

enum
{
    INPUT_KB,
    INPUT_MOUSE,
    INPUT_JOYSTICK,
    INPUT_ALL,
};

static struct
{
    GtkWidget *startwin;
    GtkWidget *hlayout;
    GtkWidget *banner;
    GtkWidget *vlayout;
    GtkWidget *tabs;
    GtkWidget *configtlayout;
    GtkWidget *displayvlayout;
    GtkWidget *vmode3dlabel;
    GtkWidget *vmode3dcombo;
    GtkWidget *fullscreencheck;
#ifdef POLYMER
    GtkWidget *polymercheck;
#endif
    GtkWidget *inputdevlabel;
    GtkWidget *inputdevcombo;
    GtkWidget *custommodlabel;
    GtkWidget *custommodcombo;
    GtkWidget *emptyhlayout;
    GtkWidget *autoloadcheck;
    GtkWidget *alwaysshowcheck;
    GtkWidget *configtab;
    GtkWidget *gamevlayout;
    GtkWidget *gamelabel;
    GtkWidget *gamescroll;
    GtkWidget *gamelist;
    GtkWidget *gametab;
    GtkWidget *messagesscroll;
    GtkWidget *messagestext;
    GtkWidget *messagestab;
    GtkWidget *buttons;
    GtkWidget *cancelbutton;
    GtkWidget *cancelbuttonalign;
    GtkWidget *cancelbuttonlayout;
    GtkWidget *cancelbuttonicon;
    GtkWidget *cancelbuttonlabel;
    GtkWidget *startbutton;
    GtkWidget *startbuttonalign;
    GtkWidget *startbuttonlayout;
    GtkWidget *startbuttonicon;
    GtkWidget *startbuttonlabel;
} stwidgets;

static struct
{
    grpfile_t const * grp;
    char *gamedir;
    ud_setup_t shared;
#ifdef POLYMER
    int polymer;
#endif
} settings;

static int32_t retval = -1, mode = TAB_MESSAGES;
extern int32_t gtkenabled;
static void PopulateForm(unsigned char pgs);

// -- EVENT CALLBACKS AND CREATION STUFF --------------------------------------

static void on_vmode3dcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    GtkTreeModel *data;
    GtkTreeIter iter;
    int32_t val;
    UNREFERENCED_PARAMETER(user_data);

    if (!gtk_combo_box_get_active_iter(combobox, &iter)) return;
    if (!(data = gtk_combo_box_get_model(combobox))) return;
    gtk_tree_model_get(data, &iter, 1, &val, -1);
    settings.shared.xdim = validmode[val].xdim;
    settings.shared.ydim = validmode[val].ydim;
    settings.shared.bpp = validmode[val].bpp;
}

static void on_fullscreencheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.fullscreen = gtk_toggle_button_get_active(togglebutton);
    PopulateForm(POPULATE_VIDEO);
}

#ifdef POLYMER
static void on_polymercheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    if (gtk_toggle_button_get_active(togglebutton))
    {
        glrendmode = REND_POLYMER;
        settings.polymer = TRUE;
        if (settings.shared.bpp == 8)
        {
            settings.shared.bpp = 32;
            PopulateForm(POPULATE_VIDEO);
        }
    }
    else
    {
        glrendmode = REND_POLYMOST;
        settings.polymer = FALSE;
    }
}
#endif

static void on_inputdevcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    switch (gtk_combo_box_get_active(combobox))
    {
    case 0: settings.shared.usemouse = 0; settings.shared.usejoystick = 0; break;
    case 1:	settings.shared.usemouse = 1; settings.shared.usejoystick = 0; break;
    case 2:	settings.shared.usemouse = 0; settings.shared.usejoystick = 1; break;
    case 3:	settings.shared.usemouse = 1; settings.shared.usejoystick = 1; break;
    }
}

static void on_custommodcombo_changed(GtkComboBox *combobox, gpointer user_data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;
    GtkTreePath *path;
    char *value;
    UNREFERENCED_PARAMETER(user_data);

    if (gtk_combo_box_get_active_iter(combobox, &iter))
    {
        model = gtk_combo_box_get_model(combobox);
        gtk_tree_model_get(model, &iter, 0,&value, -1);
        path = gtk_tree_model_get_path(model, &iter);

        if (*gtk_tree_path_get_indices(path) == NONE)
            settings.gamedir = NULL;
        else settings.gamedir = value;
    }
}

static void on_autoloadcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.noautoload = !gtk_toggle_button_get_active(togglebutton);
}

static void on_alwaysshowcheck_toggled(GtkToggleButton *togglebutton, gpointer user_data)
{
    UNREFERENCED_PARAMETER(user_data);
    settings.shared.forcesetup = gtk_toggle_button_get_active(togglebutton);
}

static void on_cancelbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
}

static void on_startbutton_clicked(GtkButton *button, gpointer user_data)
{
    UNREFERENCED_PARAMETER(button);
    UNREFERENCED_PARAMETER(user_data);
    retval = 1;
    gtk_main_quit();
}

static void on_gamelist_selection_changed(GtkTreeSelection *selection, gpointer user_data)
{
    GtkTreeIter iter;
    GtkTreeModel *model;
    UNREFERENCED_PARAMETER(user_data);

    if (gtk_tree_selection_get_selected(selection, &model, &iter))
    {
        grpfile_t const *fg;
        gtk_tree_model_get(model, &iter, 2, (gpointer)&fg, -1);
        settings.grp = fg;
    }
}

static gboolean on_startwin_delete_event(GtkWidget *widget, GdkEvent *event, gpointer user_data)
{
    UNREFERENCED_PARAMETER(widget);
    UNREFERENCED_PARAMETER(event);
    UNREFERENCED_PARAMETER(user_data);
    if (mode == TAB_CONFIG) { retval = 0; gtk_main_quit(); }
    else quitevent++;
    return TRUE;	// FALSE would let the event go through. we want the game to decide when to close
}

// -- SUPPORT FUNCTIONS -------------------------------------------------------

static GdkPixbuf *load_banner(void)
{
    return gdk_pixbuf_from_pixdata((GdkPixdata const *)&startbanner_pixdata, FALSE, NULL);
}

static void SetPage(int32_t n)
{
    if (!gtkenabled || !stwidgets.startwin) return;
    mode = n;
    gtk_notebook_set_current_page(GTK_NOTEBOOK(stwidgets.tabs), n);

    // each control in the config page vertical layout plus the start button should be made (in)sensitive
    if (n == TAB_CONFIG) n = TRUE; else n = FALSE;
    gtk_widget_set_sensitive(stwidgets.startbutton, n);
    gtk_container_foreach(GTK_CONTAINER(stwidgets.configtlayout),
                          (GtkCallback)gtk_widget_set_sensitive,
                          (gpointer)&n);
}

static unsigned char GetModsDirNames(GtkListStore *list)
{
    char *homedir;
    char pdir[BMAX_PATH];
    unsigned char iternumb = 0;
    BUILDVFS_FIND_REC *dirs = NULL;
    GtkTreeIter iter;

    pathsearchmode = 1;

    if ((homedir = Bgethomedir()))
    {
        Bsnprintf(pdir, sizeof(pdir), "%s/" ".eduke32", homedir);
        dirs = klistpath(pdir, "*", BUILDVFS_FIND_DIR);
        for (; dirs != NULL; dirs=dirs->next)
        {
            if ((Bstrcmp(dirs->name, "autoload") == 0) ||
                    (Bstrcmp(dirs->name, "..") == 0) ||
                    (Bstrcmp(dirs->name, ".") == 0))
                continue;
            else
            {
                gtk_list_store_append(list, &iter);
                gtk_list_store_set(list, &iter, 0,dirs->name, -1);
                iternumb++;
            }
        }
    }

    klistfree(dirs);
    dirs = NULL;

    return iternumb;
}

static void PopulateForm(unsigned char pgs)
{
    if ((pgs == ALL) || (pgs == POPULATE_VIDEO))
    {
        int32_t mode3d, i;
        GtkListStore *modes3d;
        GtkTreeIter iter;
        char buf[64];

        mode3d = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, settings.shared.bpp, settings.shared.fullscreen, 1);
        if (mode3d < 0)
        {
            int32_t i, cd[] = { 32, 24, 16, 15, 8, 0 };

            for (i=0; cd[i];) { if (cd[i] >= settings.shared.bpp) i++; else break; }
            for (; cd[i]; i++)
            {
                mode3d = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, cd[i], settings.shared.fullscreen, 1);
                if (mode3d < 0) continue;
                settings.shared.bpp = cd[i];
                break;
            }
        }

        modes3d = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.vmode3dcombo)));
        gtk_list_store_clear(modes3d);

        for (i=0; i<validmodecnt; i++)
        {
            if (validmode[i].fs != settings.shared.fullscreen) continue;

            // all modes get added to the 3D mode list
            Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
            gtk_list_store_append(modes3d, &iter);
            gtk_list_store_set(modes3d, &iter, 0,buf, 1,i, -1);
            if (i == mode3d)
            {
                g_signal_handlers_block_by_func(stwidgets.vmode3dcombo, (gpointer)on_vmode3dcombo_changed, NULL);
                gtk_combo_box_set_active_iter(GTK_COMBO_BOX(stwidgets.vmode3dcombo), &iter);
                g_signal_handlers_unblock_by_func(stwidgets.vmode3dcombo, (gpointer)on_vmode3dcombo_changed, NULL);
            }
        }
    }

    if ((pgs == ALL) || (pgs == POPULATE_CONFIG))
    {
        GtkListStore *devlist, *modsdir;
        GtkTreeIter iter;
        GtkTreePath *path;
        char *value;
        unsigned char i, r = 0;
        const char *availabledev[] =
        {
            "Keyboard only",
            "Keyboard and mouse",
            "Keyboard and joystick",
            "All supported devices"
        };

        // populate input devices combo
        devlist = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.inputdevcombo)));
        gtk_list_store_clear(devlist);

        for (i=0; i<(int32_t)G_N_ELEMENTS(availabledev); i++)
        {
            gtk_list_store_append(devlist, &iter);
            gtk_list_store_set(devlist, &iter, 0,availabledev[i], -1);
        }
        switch (settings.shared.usemouse)
        {
        case 0: if (settings.shared.usejoystick)
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_JOYSTICK);
            else
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_KB);
            break;
        case 1:	if (settings.shared.usejoystick)
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_ALL);
            else
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.inputdevcombo), INPUT_MOUSE);
            break;
        }

        // populate custom mod combo
        modsdir = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(stwidgets.custommodcombo)));
        gtk_list_store_clear(modsdir);

        gtk_list_store_append(modsdir, &iter);
        gtk_list_store_set(modsdir, &iter, 0,"None", -1);
        r = GetModsDirNames(modsdir);

        for (i=0; i<=r; i++)
        {
            path = gtk_tree_path_new_from_indices(i, -1);
            gtk_tree_model_get_iter(GTK_TREE_MODEL(modsdir), &iter, path);
            gtk_tree_model_get(GTK_TREE_MODEL(modsdir), &iter, 0,&value, -1);

            if (Bstrcmp(settings.gamedir, "/") == 0)
            {
                gtk_combo_box_set_active(GTK_COMBO_BOX(stwidgets.custommodcombo), NONE);
                settings.gamedir = NULL;

                break;
            }
            if (Bstrcmp(settings.gamedir, value) == 0)
            {
                gtk_combo_box_set_active_iter(GTK_COMBO_BOX(stwidgets.custommodcombo),
                                              &iter);

                break;
            }
        }

        // populate check buttons
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.fullscreencheck), settings.shared.fullscreen);
#ifdef POLYMER
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.polymercheck), settings.polymer);
#endif
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.autoloadcheck), !settings.shared.noautoload);
        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(stwidgets.alwaysshowcheck), settings.shared.forcesetup);
    }

    if ((pgs == ALL) || (pgs == POPULATE_GAME))
    {
        GtkListStore *list;
        GtkTreeIter iter;
        GtkTreeView *gamelist;

        gamelist = GTK_TREE_VIEW(stwidgets.gamelist);
        list = GTK_LIST_STORE(gtk_tree_view_get_model(gamelist));
        gtk_list_store_clear(list);

        for (grpfile_t const * fg = foundgrps; fg; fg=fg->next)
        {
            gtk_list_store_append(list, &iter);
            gtk_list_store_set(list, &iter, 0, fg->type->name, 1, fg->filename, 2, (void const *)fg, -1);
            if (settings.grp == fg)
            {
                GtkTreeSelection *sel = gtk_tree_view_get_selection(gamelist);
                g_signal_handlers_block_by_func(sel, (gpointer)on_gamelist_selection_changed, NULL);
                gtk_tree_selection_select_iter(sel, &iter);
                g_signal_handlers_unblock_by_func(sel, (gpointer)on_gamelist_selection_changed, NULL);
            }
        }
    }
}

static gint name_sorter(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data)
{
    gchar *as, *bs;
    gint r;
    UNREFERENCED_PARAMETER(user_data);
    gtk_tree_model_get(model, a, 0, &as, -1);
    gtk_tree_model_get(model, b, 0, &bs, -1);

    r = g_utf8_collate(as,bs);

    g_free(as);
    g_free(bs);

    return r;
}

static GtkWidget *create_window(void)
{
    // Basic window
    stwidgets.startwin = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), apptitle);	// NOTE: use global app title
    gtk_window_set_position(GTK_WINDOW(stwidgets.startwin), GTK_WIN_POS_CENTER);
    gtk_window_set_resizable(GTK_WINDOW(stwidgets.startwin), FALSE);
    gtk_window_set_type_hint(GTK_WINDOW(stwidgets.startwin), GDK_WINDOW_TYPE_HINT_DIALOG);

    // Horizontal layout of banner and controls
    stwidgets.hlayout = gtk_hbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startwin), stwidgets.hlayout);

    // banner
    {
        GdkPixbuf *pixbuf = load_banner();
        stwidgets.banner = gtk_image_new_from_pixbuf(pixbuf);
        g_object_unref((gpointer)pixbuf);
    }
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.banner, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(stwidgets.banner), 0.5, 0);

    // Vertical layout of tab control and start+cancel buttons
    stwidgets.vlayout = gtk_vbox_new(FALSE, 0);
    gtk_box_pack_start(GTK_BOX(stwidgets.hlayout), stwidgets.vlayout, TRUE, TRUE, 0);

    // Tab control
    stwidgets.tabs = gtk_notebook_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.tabs, TRUE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.tabs), 4);

    // layout table of config page
    stwidgets.configtlayout = gtk_table_new(6, 3, FALSE);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.configtlayout);

    // 3D video mode LabelText
    stwidgets.vmode3dlabel = gtk_label_new_with_mnemonic("_Video mode:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.vmode3dlabel), 0.3, 0);
#ifdef POLYMER
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dlabel, 0,1, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 0);
#else
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dlabel, 0,1, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 7);
#endif

    // 3D video mode combo
    {
        GtkListStore *list = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
        GtkCellRenderer *cell;

        stwidgets.vmode3dcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.vmode3dcombo), cell, "text", 0, NULL);
    }

#ifdef POLYMER
   gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dcombo, 1,2, 0,1,
       (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 0);
#else
   gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.vmode3dcombo, 1,2, 0,1, (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 7);
#endif

    // Fullscreen checkbox
    stwidgets.displayvlayout = gtk_vbox_new(TRUE, 0);
#ifdef POLYMER
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.displayvlayout, 2,3, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 0);
#else
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.displayvlayout, 2,3, 0,1, GTK_FILL, (GtkAttachOptions)0, 4, 7);
#endif

    stwidgets.fullscreencheck = gtk_check_button_new_with_mnemonic("_Fullscreen");
    gtk_box_pack_start(GTK_BOX(stwidgets.displayvlayout), stwidgets.fullscreencheck, FALSE, FALSE, 0);

#ifdef POLYMER
    // Polymer checkbox
    stwidgets.polymercheck = gtk_check_button_new_with_mnemonic("_Polymer");
    gtk_box_pack_start(GTK_BOX(stwidgets.displayvlayout), stwidgets.polymercheck, FALSE, FALSE, 0);
#endif

    // Input devices LabelText
    stwidgets.inputdevlabel = gtk_label_new_with_mnemonic("_Input devices:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.inputdevlabel), 0.3, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.inputdevlabel, 0,1, 1,2, GTK_FILL, (GtkAttachOptions)0, 4, 0);

    // Input devices combo
    {
        GtkListStore *list = gtk_list_store_new(1, G_TYPE_STRING);
        GtkCellRenderer *cell;

        stwidgets.inputdevcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.inputdevcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.inputdevcombo), cell, "text", 0, NULL);
    }
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.inputdevcombo, 1,2, 1,2,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 0);

    // Custom mod LabelText
    stwidgets.custommodlabel = gtk_label_new_with_mnemonic("Custom _game:");
    gtk_misc_set_alignment(GTK_MISC(stwidgets.custommodlabel), 0.3, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.custommodlabel, 0,1, 2,3, GTK_FILL, (GtkAttachOptions)0, 4, 7);

    // Custom mod combo
    {
        GtkListStore *list = gtk_list_store_new(1, G_TYPE_STRING);
        GtkCellRenderer *cell;

        stwidgets.custommodcombo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(stwidgets.custommodcombo), cell, FALSE);
        gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(stwidgets.custommodcombo), cell, "text", 0, NULL);
    }
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.custommodcombo, 1,2, 2,3,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), (GtkAttachOptions)0, 4, 7);

    // Empty horizontal layout
    stwidgets.emptyhlayout = gtk_hbox_new(TRUE, 0);
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.emptyhlayout, 0,3, 3,4, (GtkAttachOptions)0,
        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 4, 0);

    // Autoload checkbox
    stwidgets.autoloadcheck = gtk_check_button_new_with_mnemonic("_Enable \"autoload\" folder");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.autoloadcheck, 0,3, 4,5, GTK_FILL, (GtkAttachOptions)0, 2, 2);

    // Always show config checkbox
    stwidgets.alwaysshowcheck = gtk_check_button_new_with_mnemonic("_Always show this window at startup");
    gtk_table_attach(GTK_TABLE(stwidgets.configtlayout), stwidgets.alwaysshowcheck, 0,3, 5,6, GTK_FILL, (GtkAttachOptions)0, 2, 2);

    // Configuration tab
    stwidgets.configtab = gtk_label_new("Configuration");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 0), stwidgets.configtab);

    // Game data layout
    stwidgets.gamevlayout = gtk_vbox_new(FALSE, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.gamevlayout);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.gamevlayout), 4);

    // Game data field LabelText
    stwidgets.gamelabel = gtk_label_new_with_mnemonic("_Game:");
    gtk_box_pack_start(GTK_BOX(stwidgets.gamevlayout), stwidgets.gamelabel, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(stwidgets.gamelabel), 0, 0.5);

    // Game data scrollable area
    stwidgets.gamescroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_box_pack_start(GTK_BOX(stwidgets.gamevlayout), stwidgets.gamescroll, TRUE, TRUE, 0);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(stwidgets.gamescroll), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(stwidgets.gamescroll), GTK_SHADOW_IN);

    // Game data list
    {
        GtkListStore *list = gtk_list_store_new(3, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);
        GtkCellRenderer *cell;
        GtkTreeViewColumn *col;

        gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(list), 0, name_sorter, NULL, NULL);
        gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(list), 0, GTK_SORT_ASCENDING);

        stwidgets.gamelist = gtk_tree_view_new_with_model(GTK_TREE_MODEL(list));
        g_object_unref(G_OBJECT(list));

        cell = gtk_cell_renderer_text_new();
        col = gtk_tree_view_column_new_with_attributes("Game", cell, "text", 0, NULL);
        gtk_tree_view_column_set_expand(col, TRUE);
        gtk_tree_view_append_column(GTK_TREE_VIEW(stwidgets.gamelist), col);
        col = gtk_tree_view_column_new_with_attributes("GRP file", cell, "text", 1, NULL);
        gtk_tree_view_column_set_min_width(col, 64);
        gtk_tree_view_append_column(GTK_TREE_VIEW(stwidgets.gamelist), col);
    }
    gtk_container_add(GTK_CONTAINER(stwidgets.gamescroll), stwidgets.gamelist);

    gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(stwidgets.gamelist), FALSE);
    gtk_tree_view_set_enable_search(GTK_TREE_VIEW(stwidgets.gamelist), FALSE);

    // Game tab
    stwidgets.gametab = gtk_label_new("Game");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 1), stwidgets.gametab);

    // Messages scrollable area
    stwidgets.messagesscroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_container_add(GTK_CONTAINER(stwidgets.tabs), stwidgets.messagesscroll);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(stwidgets.messagesscroll), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);

    // Messages text area
    stwidgets.messagestext = gtk_text_view_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.messagesscroll), stwidgets.messagestext);
    gtk_text_view_set_editable(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(stwidgets.messagestext), GTK_WRAP_WORD);
    gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(stwidgets.messagestext), FALSE);
    gtk_text_view_set_left_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);
    gtk_text_view_set_right_margin(GTK_TEXT_VIEW(stwidgets.messagestext), 2);

    // Messages tab
    stwidgets.messagestab = gtk_label_new("Messages");
    gtk_notebook_set_tab_label(GTK_NOTEBOOK(stwidgets.tabs), gtk_notebook_get_nth_page(GTK_NOTEBOOK(stwidgets.tabs), 2), stwidgets.messagestab);

    // Dialogue box buttons layout
    stwidgets.buttons = gtk_hbutton_box_new();
    gtk_box_pack_start(GTK_BOX(stwidgets.vlayout), stwidgets.buttons, FALSE, TRUE, 0);
    gtk_container_set_border_width(GTK_CONTAINER(stwidgets.buttons), 3);
    gtk_button_box_set_layout(GTK_BUTTON_BOX(stwidgets.buttons), GTK_BUTTONBOX_END);

    // Cancel button
    stwidgets.cancelbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.cancelbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.cancelbutton, GTK_CAN_DEFAULT);

    stwidgets.cancelbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbutton), stwidgets.cancelbuttonalign);

    stwidgets.cancelbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.cancelbuttonalign), stwidgets.cancelbuttonlayout);

    stwidgets.cancelbuttonicon = gtk_image_new_from_stock("gtk-cancel", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonicon, FALSE, FALSE, 0);

    stwidgets.cancelbuttonlabel = gtk_label_new_with_mnemonic("_Cancel");
    gtk_box_pack_start(GTK_BOX(stwidgets.cancelbuttonlayout), stwidgets.cancelbuttonlabel, FALSE, FALSE, 0);

    // Start button
    stwidgets.startbutton = gtk_button_new();
    gtk_container_add(GTK_CONTAINER(stwidgets.buttons), stwidgets.startbutton);
    GTK_WIDGET_SET_FLAGS(stwidgets.startbutton, GTK_CAN_DEFAULT);

    gtk_window_set_default(GTK_WINDOW(stwidgets.startwin), stwidgets.startbutton);

    stwidgets.startbuttonalign = gtk_alignment_new(0.5, 0.5, 0, 0);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbutton), stwidgets.startbuttonalign);

    stwidgets.startbuttonlayout = gtk_hbox_new(FALSE, 2);
    gtk_container_add(GTK_CONTAINER(stwidgets.startbuttonalign), stwidgets.startbuttonlayout);

    stwidgets.startbuttonicon = gtk_image_new_from_stock("gtk-execute", GTK_ICON_SIZE_BUTTON);
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonicon, FALSE, FALSE, 0);

    stwidgets.startbuttonlabel = gtk_label_new_with_mnemonic("_Start");
    gtk_box_pack_start(GTK_BOX(stwidgets.startbuttonlayout), stwidgets.startbuttonlabel, FALSE, FALSE, 0);

    // Wire up the signals
    g_signal_connect((gpointer) stwidgets.startwin, "delete_event",
                     G_CALLBACK(on_startwin_delete_event),
                     NULL);
    g_signal_connect((gpointer) stwidgets.vmode3dcombo, "changed",
                     G_CALLBACK(on_vmode3dcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.fullscreencheck, "toggled",
                     G_CALLBACK(on_fullscreencheck_toggled),
                     NULL);
#ifdef POLYMER
    g_signal_connect((gpointer) stwidgets.polymercheck, "toggled",
                     G_CALLBACK(on_polymercheck_toggled),
                     NULL);
#endif
    g_signal_connect((gpointer) stwidgets.inputdevcombo, "changed",
                     G_CALLBACK(on_inputdevcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.custommodcombo, "changed",
                     G_CALLBACK(on_custommodcombo_changed),
                     NULL);
    g_signal_connect((gpointer) stwidgets.autoloadcheck, "toggled",
                     G_CALLBACK(on_autoloadcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.alwaysshowcheck, "toggled",
                     G_CALLBACK(on_alwaysshowcheck_toggled),
                     NULL);
    g_signal_connect((gpointer) stwidgets.cancelbutton, "clicked",
                     G_CALLBACK(on_cancelbutton_clicked),
                     NULL);
    g_signal_connect((gpointer) stwidgets.startbutton, "clicked",
                     G_CALLBACK(on_startbutton_clicked),
                     NULL);
    {
        GtkTreeSelection *sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(stwidgets.gamelist));
        gtk_tree_selection_set_mode(sel, GTK_SELECTION_SINGLE);
        g_signal_connect((gpointer) sel, "changed",
                         G_CALLBACK(on_gamelist_selection_changed),
                         NULL);
    }

    // Associate labels with their controls
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.vmode3dlabel), stwidgets.vmode3dcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.inputdevlabel), stwidgets.inputdevcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.custommodlabel), stwidgets.custommodcombo);
    gtk_label_set_mnemonic_widget(GTK_LABEL(stwidgets.gamelabel), stwidgets.gamelist);

    return stwidgets.startwin;
}

// -- BUILD ENTRY POINTS ------------------------------------------------------
bool startwin_isopen(void)
{
    return gtkenabled && stwidgets.startwin;
}

int32_t startwin_open(void)
{
    if (!gtkenabled) return 0;
    if (stwidgets.startwin) return 1;

    stwidgets.startwin = create_window();
    if (stwidgets.startwin)
    {
        SetPage(TAB_MESSAGES);
        gtk_widget_show_all(stwidgets.startwin);
        gtk_main_iteration_do(FALSE);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_widget_destroy(stwidgets.startwin);
    stwidgets.startwin = NULL;
    return 0;
}

int32_t startwin_puts(const char *str)
{
    GtkWidget *textview;
    GtkTextBuffer *textbuffer;
    GtkTextIter enditer;
    GtkTextMark *mark;
    const char *aptr, *bptr;

    if (!gtkenabled || !str) return 0;
    if (!stwidgets.startwin) return 1;
    if (!(textview = stwidgets.messagestext)) return -1;
    textbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));

    gtk_text_buffer_get_end_iter(textbuffer, &enditer);
    for (aptr = bptr = str; *aptr != 0;)
    {
        switch (*bptr)
        {
        case '\b':
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr)-1);
#if GTK_CHECK_VERSION(2,6,0)
            gtk_text_buffer_backspace(textbuffer, &enditer, FALSE, TRUE);
#else
            {
                GtkTextIter iter2 = enditer;
                gtk_text_iter_backward_cursor_position(&iter2);
                //FIXME: this seems be deleting one too many chars somewhere!
                if (!gtk_text_iter_equal(&iter2, &enditer))
                    gtk_text_buffer_delete_interactive(textbuffer, &iter2, &enditer, TRUE);
            }
#endif
            aptr = ++bptr;
            break;
        case 0:
            if (bptr > aptr)
                gtk_text_buffer_insert(textbuffer, &enditer, (const gchar *)aptr, (gint)(bptr-aptr));
            aptr = bptr;
            break;
        case '\r':	// FIXME
        default:
            bptr++;
            break;
        }
    }

    mark = gtk_text_buffer_create_mark(textbuffer, NULL, &enditer, 1);
    gtk_text_view_scroll_to_mark(GTK_TEXT_VIEW(textview), mark, 0.0, FALSE, 0.0, 1.0);
    gtk_text_buffer_delete_mark(textbuffer, mark);

    return 0;
}

int32_t startwin_settitle(const char *title)
{
    if (!gtkenabled) return 0;
    if (!stwidgets.startwin) return 1;
    gtk_window_set_title(GTK_WINDOW(stwidgets.startwin), title);
    return 0;
}

int32_t startwin_idle(void *s)
{
    UNREFERENCED_PARAMETER(s);
    if (!gtkenabled) return 0;
    //if (!stwidgets.startwin) return 1;
    gtk_main_iteration_do(FALSE);
    return 0;
}

int32_t startwin_run(void)
{
    if (!gtkenabled) return 1;
    if (!stwidgets.startwin) return 1;

    SetPage(TAB_CONFIG);

    settings.shared = gSetup;
    settings.gamedir = g_modDir;
    settings.grp = g_selectedGrp;
#ifdef POLYMER
    settings.polymer = (glrendmode == REND_POLYMER) & (settings.shared.bpp != 8);
#endif
    PopulateForm(ALL);

    gtk_main();

    SetPage(TAB_MESSAGES);
    if (retval) // launch the game with these parameters
    {
        gSetup = settings.shared;
#ifdef POLYMER
        glrendmode = (settings.polymer) ? REND_POLYMER : REND_POLYMOST;
#endif
        g_selectedGrp = settings.grp;

        Bstrcpy(g_modDir, (g_noSetup == 0 && settings.gamedir != NULL) ? settings.gamedir : "/");
    }

    return retval;
}