code:
//
// Definitions of common game-only data structures/functions
// (and declarations of data appearing in both)
// for EDuke32 and Mapster32
//

#ifndef EDUKE32_COMMON_GAME_H_
#define EDUKE32_COMMON_GAME_H_

#include "collections.h"
#include "grpscan.h"

#ifdef __cplusplus
extern "C" {
#endif

extern int g_useCwd;

#ifndef APPNAME
#define APPNAME             "Rednukem"
#endif

#ifndef APPBASENAME
#define APPBASENAME         "rednukem"
#endif

#define GAMEFLAG_DUKE       0x00000001
#define GAMEFLAG_NAM        0x00000002
#define GAMEFLAG_NAPALM     0x00000004
#define GAMEFLAG_WW2GI      0x00000008
#define GAMEFLAG_ADDON      0x00000010
#define GAMEFLAG_SHAREWARE  0x00000020
#define GAMEFLAG_RR         0x00000040
#define GAMEFLAG_RRRA       0x00000080
#define GAMEFLAG_DEER       0x00000100
#define GAMEFLAG_REALITY    0x00000200
//#define GAMEFLAG_DUKEBETA   0x00000060 // includes 0x20 since it's a shareware beta
//#define GAMEFLAG_FURY       0x00000080
//#define GAMEFLAG_STANDALONE 0x00000100
#define GAMEFLAGMASK        0x000003FF // flags allowed from grpinfo

extern struct grpfile_t const *g_selectedGrp;

extern int32_t g_gameType;
extern int     g_addonNum;

#define DUKE                (g_gameType & GAMEFLAG_DUKE)
#define RR                  (g_gameType & GAMEFLAG_RR)
#define RRRA                (g_gameType & GAMEFLAG_RRRA)
#define NAM                 (g_gameType & GAMEFLAG_NAM)
#define NAPALM              (g_gameType & GAMEFLAG_NAPALM)
#define WW2GI               (g_gameType & GAMEFLAG_WW2GI)
#define NAM_WW2GI           (g_gameType & (GAMEFLAG_NAM|GAMEFLAG_WW2GI))
#define SHAREWARE           (g_gameType & GAMEFLAG_SHAREWARE)
#define DEER                (g_gameType & GAMEFLAG_DEER)
#define REALITY             (g_gameType & GAMEFLAG_REALITY)
//#define DUKEBETA            ((g_gameType & GAMEFLAG_DUKEBETA) == GAMEFLAG_DUKEBETA)
//#define FURY                (g_gameType & GAMEFLAG_FURY)

enum Games_t {
    GAME_DUKE = 0,
    GAME_RR,
    GAME_RRRA,
    GAME_NAM,
    GAME_NAPALM,
    GAME_WW2GI,
    GAMECOUNT
};

enum searchpathtypes_t {
    SEARCHPATH_REMOVE = 1<<0,
    SEARCHPATH_NAM    = 1<<1,
    SEARCHPATH_WW2GI  = 1<<2,
    SEARCHPATH_RR     = 1<<3,
    SEARCHPATH_RRRA   = 1<<4,
    SEARCHPATH_DEER   = 1<<5,
};

typedef enum basepal_ {
    BASEPAL = 0,
    WATERPAL,
    SLIMEPAL,
    DREALMSPAL,
    TITLEPAL,
    ENDINGPAL,  // 5
    ANIMPAL,
    DRUGPAL,
    BASEPALCOUNT
} basepal_t;

#define OSDTEXT_DEFAULT   "^00"
#define OSDTEXT_DARKRED   "^10"
#define OSDTEXT_GREEN     "^11"
#define OSDTEXT_RED       "^21"
#define OSDTEXT_YELLOW    "^23"

#define OSDTEXT_BRIGHT    "^S0"

#define OSD_ERROR OSDTEXT_DARKRED OSDTEXT_BRIGHT

extern const char *g_gameNamePtr;

extern char *g_grpNamePtr;
extern char *g_scriptNamePtr;
extern char *g_rtsNamePtr;

extern const char *G_DefaultGrpFile(void);
extern const char *G_GrpFile(void);

extern const char *G_DefaultConFile(void);
extern const char *G_ConFile(void);

extern GrowArray<char *> g_scriptModules;

extern void G_AddCon(const char *buffer);
extern void G_AddConModule(const char *buffer);

extern void clearGrpNamePtr(void);
extern void clearScriptNamePtr(void);

extern int loaddefinitions_game(const char *fn, int32_t preload);
extern int32_t g_groupFileHandle;

//////////

extern void G_InitMultiPsky(int CLOUDYOCEAN__DYN, int MOONSKY1__DYN, int BIGORBIT1__DYN, int LA__DYN);
extern void G_SetupGlobalPsky(void);

//////////

extern void G_AddSearchPaths(void);
extern void G_CleanupSearchPaths(void);

extern void G_ExtPreInit(int32_t argc,char const * const * argv);
extern void G_ExtInit(void);
extern void G_ScanGroups(void);
extern void G_LoadGroups(int32_t autoload);

extern const char * G_GetInstallPath(int32_t insttype);

//////////

void G_LoadGroupsInDir(const char *dirname);
void G_DoAutoload(const char *dirname);

//////////

extern void G_LoadLookups(void);

//////////

void Duke_CommonCleanup(void);

#if defined HAVE_FLAC || defined HAVE_VORBIS
# define FORMAT_UPGRADE_ELIGIBLE
extern int g_maybeUpgradeSoundFormats;
extern int32_t S_OpenAudio(const char *fn, char searchfirst, uint8_t ismusic);
#else
# define S_OpenAudio(fn, searchfirst, ismusic) kopen4loadfrommod(fn, searchfirst)
#endif

#ifdef __cplusplus
}
#endif

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2016 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 "duke3d.h"
#include "scriplib.h"
#include "osdcmds.h"
#include "renderlayer.h"
#include "cmdline.h"

#ifdef __ANDROID__
# include "android.h"
#endif

#if defined RENDERTYPESDL && defined SDL_TARGET && SDL_TARGET > 1
# include "sdl_inc.h"
#endif

// we load this in to get default button and key assignments
// as well as setting up function mappings

#define __SETUP__   // JBF 20031211
#include "_functio.h"

hashtable_t h_gamefuncs    = { NUMGAMEFUNCTIONS<<1, NULL };

int32_t CONFIG_FunctionNameToNum(const char *func)
{
    int32_t i;

    if (!func)
        return -1;

    i = hash_find(&h_gamefuncs,func);

    if (i < 0)
    {
        char *str = Bstrtolower(Xstrdup(func));
        i = hash_find(&h_gamefuncs,str);
        Xfree(str);

        return i;
    }

    return i;
}

char *CONFIG_FunctionNumToName(int32_t func)
{
    if ((unsigned)func >= (unsigned)NUMGAMEFUNCTIONS)
        return NULL;
    return gamefunctions[func];
}

int32_t CONFIG_AnalogNameToNum(const char *func)
{
    if (!func)
        return -1;

    if (!Bstrcasecmp(func,"analog_turning"))
    {
        return analog_turning;
    }
    if (!Bstrcasecmp(func,"analog_strafing"))
    {
        return analog_strafing;
    }
    if (!Bstrcasecmp(func,"analog_moving"))
    {
        return analog_moving;
    }
    if (!Bstrcasecmp(func,"analog_lookingupanddown"))
    {
        return analog_lookingupanddown;
    }

    return -1;
}

const char *CONFIG_AnalogNumToName(int32_t func)
{
    switch (func)
    {
    case analog_turning:
        return "analog_turning";
    case analog_strafing:
        return "analog_strafing";
    case analog_moving:
        return "analog_moving";
    case analog_lookingupanddown:
        return "analog_lookingupanddown";
    }

    return NULL;
}

static void CONFIG_SetJoystickButtonFunction(int i, int j, int function)
{
    ud.config.JoystickFunctions[i][j] = function;
    CONTROL_MapButton(function, i, j, controldevice_joystick);
}
static void CONFIG_SetJoystickAnalogAxisScale(int i, int scale)
{
    ud.config.JoystickAnalogueScale[i] = scale;
    CONTROL_SetAnalogAxisScale(i, scale, controldevice_joystick);
}
static void CONFIG_SetJoystickAnalogAxisInvert(int i, int invert)
{
    ud.config.JoystickAnalogueInvert[i] = invert;
    CONTROL_SetAnalogAxisInvert(i, invert);
}
static void CONFIG_SetJoystickAnalogAxisDeadSaturate(int i, int dead, int saturate)
{
    ud.config.JoystickAnalogueDead[i] = dead;
    ud.config.JoystickAnalogueSaturate[i] = saturate;
    JOYSTICK_SetDeadZone(i, dead, saturate);
}
static void CONFIG_SetJoystickDigitalAxisFunction(int i, int j, int function)
{
    ud.config.JoystickDigitalFunctions[i][j] = function;
    CONTROL_MapDigitalAxis(i, function, j);
}
static void CONFIG_SetJoystickAnalogAxisFunction(int i, int function)
{
    ud.config.JoystickAnalogueAxes[i] = function;
    CONTROL_MapAnalogAxis(i, function);
}
void CONFIG_SetDefaultKeys(const char (*keyptr)[MAXGAMEFUNCLEN], bool lazy/*=false*/)
{
    static char const s_gamefunc_[] = "gamefunc_";
    int constexpr strlen_gamefunc_  = ARRAY_SIZE(s_gamefunc_) - 1;

    if (!lazy)
    {
        Bmemset(ud.config.KeyboardKeys, 0xff, sizeof(ud.config.KeyboardKeys));
        CONTROL_ClearAllBinds();
    }

    for (int i=0; i < ARRAY_SSIZE(gamefunctions); ++i)
    {
        if (gamefunctions[i][0] == '\0')
            continue;

        auto &key = ud.config.KeyboardKeys[i];

        int const default0 = KB_StringToScanCode(keyptr[i<<1]);
        int const default1 = KB_StringToScanCode(keyptr[(i<<1)+1]);

        // skip the function if the default key is already used
        // or the function is assigned to another key
        if (lazy && (key[0] != 0xff || (CONTROL_KeyIsBound(default0) && Bstrlen(CONTROL_KeyBinds[default0].cmdstr) > strlen_gamefunc_
                        && CONFIG_FunctionNameToNum(CONTROL_KeyBinds[default0].cmdstr + strlen_gamefunc_) >= 0)))
        {
#if 0 // defined(DEBUGGINGAIDS)
            if (key[0] != 0xff)
                initprintf("Skipping %s bound to %s\n", keyptr[i<<1], CONTROL_KeyBinds[default0].cmdstr);
#endif
            continue;
        }

        key[0] = default0;
        key[1] = default1;

        if (key[0])
            CONTROL_FreeKeyBind(key[0]);

        if (key[1])
            CONTROL_FreeKeyBind(key[1]);

        if (i == gamefunc_Show_Console)
            OSD_CaptureKey(key[0]);
        else
            CONFIG_MapKey(i, key[0], 0, key[1], 0);
    }
}

void CONFIG_SetDefaults(void)
{
    // JBF 20031211
    int32_t i;

    ud.config.scripthandle = -1;
#ifdef __ANDROID__
    droidinput.forward_sens = 5.f;
    droidinput.strafe_sens = 5.f;
    droidinput.pitch_sens = 5.f;
    droidinput.yaw_sens = 5.f;
    droidinput.hideStick = 0;
    droidinput.gameControlsAlpha = 0.5;
    droidinput.toggleCrouch = 1;
    droidinput.quickSelectWeapon = 1;

    ud.setup.xdim = droidinfo.screen_width;
    ud.setup.ydim = droidinfo.screen_height;
#else
# if defined RENDERTYPESDL && SDL_MAJOR_VERSION > 1
    uint32_t inited = SDL_WasInit(SDL_INIT_VIDEO);
    if (inited == 0)
        SDL_Init(SDL_INIT_VIDEO);
    else if (!(inited & SDL_INIT_VIDEO))
        SDL_InitSubSystem(SDL_INIT_VIDEO);

    SDL_DisplayMode dm;
    if (SDL_GetDesktopDisplayMode(0, &dm) == 0)
    {
        ud.setup.xdim = dm.w;
        ud.setup.ydim = dm.h;
    }
    else
# endif
    {
        ud.setup.xdim = 1024;
        ud.setup.ydim = 768;
    }
#endif

#ifdef USE_OPENGL
    ud.setup.bpp = 32;
#else
    ud.setup.bpp = 8;
#endif
    ud.config.useprecache = 1;
    ud.config.AmbienceToggle = 1;
    ud.config.FXVolume = 255;
#if defined(_WIN32)
    ud.config.MixRate = 44100;
#elif defined __ANDROID__
    ud.config.MixRate = droidinfo.audio_sample_rate;
#else
    ud.config.MixRate = 48000;
#endif
    ud.config.MouseBias = 0;
    ud.config.MouseDeadZone = 0;
    ud.config.MusicToggle = 1;
    ud.config.MusicVolume = 195;
    ud.config.MusicDevice = ASS_AutoDetect;
    g_myAimMode = g_player[0].ps->aim_mode = 1;
    ud.config.AutoAim = 1;
    ud.config.NumBits = 16;
    ud.config.NumChannels = 2;
#if defined GEKKO || defined __OPENDINGUX__
    ud.config.NumVoices = 32;
#else
    ud.config.NumVoices = 64;
#endif
#ifdef ASS_REVERSESTEREO
    ud.config.ReverseStereo = 0;
#endif
    ud.auto_run = 1;
    ud.config.ShowOpponentWeapons = 0;
    ud.config.SoundToggle = 1;
    ud.config.CheckForUpdates = 1;
    ud.config.AutoAim = 1;
    ud.config.JoystickAimWeight = 5;
    ud.config.JoystickViewCentering = 3;
    ud.config.JoystickAimAssist = 1;
    ud.althud = 1;
    ud.automsg = 0;
    ud.autovote = 0;
    ud.brightness = 8;
    ud.camerasprite = -1;

#if defined GEKKO || defined __OPENDINGUX__
    ud.camera_time = 11;
#elif defined(__ANDROID__)
    ud.camera_time = 7;
#else
    ud.camera_time = 4;
#endif

    ud.color = 0;
    ud.crosshair = 1;
    ud.crosshairscale = 50;
    ud.obituaries = 1;
    ud.democams = 1;
    ud.detail = 0;
    ud.drawweapon = 1;
    ud.idplayers = 1;
    ud.levelstats = 0;
    ud.lockout = 0;
    ud.m_ffire = 1;
    ud.m_marker = 1;
    ud.menu_slidebarz = 65536;
    ud.menu_slidebarmargin = RR ? 6 * 65536 : 65536;
    ud.menu_slidecursorz = RR ? 32768 : 65536;
    ud.mouseaiming = 0;
    ud.mouseflip = 1;
    ud.msgdisptime = 120;
    ud.pwlockout[0] = '\0';
    ud.runkey_mode = 0;
    ud.screen_size = 4;
    ud.screen_tilting = 1;
    ud.shadows = 1;
    ud.statusbarflags = STATUSBAR_NOSHRINK;
    ud.statusbarmode = 1;
    ud.statusbarscale = 100;
    ud.team = 0;
    ud.viewbob = 1;
    ud.weaponsway = 1;
    ud.weaponswitch = 3;	// new+empty
    ud.angleinterpolation = 0;
    ud.setup.usejoystick = 1;
    ud.setup.forcesetup = 1;
    ud.setup.noautoload = 1;
    ud.setup.fullscreen = 1;
    ud.setup.usemouse = 1;

    ud.config.VoiceToggle = 5; // bitfield, 1 = local, 2 = dummy, 4 = other players in DM
    ud.display_bonus_screen = 1;
    ud.show_level_text = 1;
    ud.configversion = 0;
    ud.weaponscale = 100;
    ud.textscale = 200;
    ud.screenfade = 1;
    ud.menubackground = 1;
    ud.hudontop = 0;
    ud.default_skill = 1;
    ud.slidebar_paldisabled = 1;
    ud.shadow_pal = 4;
    ud.menu_scrollbartilenum = -1;
    ud.menu_scrollbarz = 65536;
    ud.menu_scrollcursorz = 65536;
    ud.autosave = 1;
    ud.autosavedeletion = 1;
    ud.maxautosaves = 5;
    ud.fov = 90;

    Bstrcpy(ud.rtsname, G_DefaultRtsFile());

    Bstrcpy(szPlayerName, "Player");

    //if (RR)
    //{
    //    Bstrcpy(ud.ridecule[0], "Yer as ugly as a mud fence!");
    //    Bstrcpy(ud.ridecule[1], "Duck you pecker-head!");
    //    Bstrcpy(ud.ridecule[2], "You like that boy?");
    //    Bstrcpy(ud.ridecule[3], "Yer lower than catfish crap!");
    //    Bstrcpy(ud.ridecule[4], "Eat lead, you shit monkey!");
    //    Bstrcpy(ud.ridecule[5], "You dumb-ass!");
    //    Bstrcpy(ud.ridecule[6], "Yer slower'n a three legged dog!");
    //    Bstrcpy(ud.ridecule[7], "Come on...Squeal like a pig!");
    //    Bstrcpy(ud.ridecule[8], "Haw, haw, haw!");
    //    Bstrcpy(ud.ridecule[9], "Now you gone and done it!");
    //}
    //else
    //{
        Bstrcpy(ud.ridecule[0], "An inspiration for birth control.");
        Bstrcpy(ud.ridecule[1], "You're gonna die for that!");
        Bstrcpy(ud.ridecule[2], "It hurts to be you.");
        Bstrcpy(ud.ridecule[3], "Lucky son of a bitch.");
        Bstrcpy(ud.ridecule[4], "Hmmm... payback time.");
        Bstrcpy(ud.ridecule[5], "You bottom dwelling scum sucker.");
        Bstrcpy(ud.ridecule[6], "Damn, you're ugly.");
        Bstrcpy(ud.ridecule[7], "Ha ha ha... wasted!");
        Bstrcpy(ud.ridecule[8], "You suck!");
        Bstrcpy(ud.ridecule[9], "AARRRGHHHHH!!!");
    //}

    // JBF 20031211

    if (RR)
    {
        Bstrcpy((char*)keydefaults[gamefunc_Holo_Duke<<1], "B");
        Bstrcpy((char*)keydefaults[gamefunc_Jetpack<<1], "C");
        Bstrcpy((char*)keydefaults[gamefunc_NightVision<<1], "Y");
        Bstrcpy((char*)keydefaults[gamefunc_MedKit<<1], "R");
        Bstrcpy((char*)keydefaults[gamefunc_Steroids<<1], "M");
        Bstrcpy((char*)keydefaults[gamefunc_Show_Opponents_Weapon<<1], "V");

        Bstrcpy((char*)oldkeydefaults[gamefunc_Holo_Duke<<1], "B");
        Bstrcpy((char*)oldkeydefaults[gamefunc_Jetpack<<1], "C");
        Bstrcpy((char*)oldkeydefaults[gamefunc_NightVision<<1], "Y");
        Bstrcpy((char*)oldkeydefaults[gamefunc_MedKit<<1], "W");
        Bstrcpy((char*)oldkeydefaults[gamefunc_Steroids<<1], "M");
        Bstrcpy((char*)oldkeydefaults[gamefunc_Show_Opponents_Weapon<<1], "E");
        Bstrcpy((char*)oldkeydefaults[gamefunc_Show_Console<<1], "V");
    }

    CONFIG_SetDefaultKeys(keydefaults);

    memset(ud.config.MouseFunctions, -1, sizeof(ud.config.MouseFunctions));
    memset(ud.config.JoystickFunctions, -1, sizeof(ud.config.JoystickFunctions));
    memset(ud.config.JoystickDigitalFunctions, -1, sizeof(ud.config.JoystickDigitalFunctions));

    CONTROL_MouseSensitivity = DEFAULTMOUSESENSITIVITY;
    for (i=0; i<MAXMOUSEBUTTONS; i++)
    {
        ud.config.MouseFunctions[i][0] = CONFIG_FunctionNameToNum(mousedefaults[i]);
        CONTROL_MapButton(ud.config.MouseFunctions[i][0], i, 0, controldevice_mouse);
        if (i>=4) continue;
        ud.config.MouseFunctions[i][1] = CONFIG_FunctionNameToNum(mouseclickeddefaults[i]);
        CONTROL_MapButton(ud.config.MouseFunctions[i][1], i, 1, controldevice_mouse);
    }

#if !defined GEKKO
    CONFIG_SetGameControllerDefaults();
#else
    for (i=0; i<MAXJOYBUTTONSANDHATS; i++)
    {
        ud.config.JoystickFunctions[i][0] = CONFIG_FunctionNameToNum(joystickdefaults[i]);
        ud.config.JoystickFunctions[i][1] = CONFIG_FunctionNameToNum(joystickclickeddefaults[i]);
        CONTROL_MapButton(ud.config.JoystickFunctions[i][0], i, 0, controldevice_joystick);
        CONTROL_MapButton(ud.config.JoystickFunctions[i][1], i, 1, controldevice_joystick);
    }

    for (i=0; i<MAXJOYAXES; i++)
    {
        ud.config.JoystickAnalogueScale[i] = DEFAULTJOYSTICKANALOGUESCALE;
        ud.config.JoystickAnalogueInvert[i] = 0;
        ud.config.JoystickAnalogueDead[i] = DEFAULTJOYSTICKANALOGUEDEAD;
        ud.config.JoystickAnalogueSaturate[i] = DEFAULTJOYSTICKANALOGUESATURATE;
        CONTROL_SetAnalogAxisScale(i, ud.config.JoystickAnalogueScale[i], controldevice_joystick);
        CONTROL_SetAnalogAxisInvert(i, 0, controldevice_joystick);

        ud.config.JoystickDigitalFunctions[i][0] = CONFIG_FunctionNameToNum(joystickdigitaldefaults[i*2]);
        ud.config.JoystickDigitalFunctions[i][1] = CONFIG_FunctionNameToNum(joystickdigitaldefaults[i*2+1]);
        CONTROL_MapDigitalAxis(i, ud.config.JoystickDigitalFunctions[i][0], 0, controldevice_joystick);
        CONTROL_MapDigitalAxis(i, ud.config.JoystickDigitalFunctions[i][1], 1, controldevice_joystick);

        ud.config.JoystickAnalogueAxes[i] = CONFIG_AnalogNameToNum(joystickanalogdefaults[i]);
        CONTROL_MapAnalogAxis(i, ud.config.JoystickAnalogueAxes[i], controldevice_joystick);
    }
#endif
}

// wrapper for CONTROL_MapKey(), generates key bindings to reflect changes to keyboard setup
void CONFIG_MapKey(int which, kb_scancode key1, kb_scancode oldkey1, kb_scancode key2, kb_scancode oldkey2)
{
    int const keys[] = { key1, key2, oldkey1, oldkey2 };
    char buf[2*MAXGAMEFUNCLEN];

    if (which == gamefunc_Show_Console)
        OSD_CaptureKey(key1);

    for (int k = 0; (unsigned)k < ARRAY_SIZE(keys); k++)
    {
        if (keys[k] == 0xff || !keys[k])
            continue;

        int match = 0;

        for (; sctokeylut[match].key; match++)
        {
            if (keys[k] == sctokeylut[match].sc)
                break;
        }

        tempbuf[0] = 0;

        for (int i=NUMGAMEFUNCTIONS-1; i>=0; i--)
        {
            if (ud.config.KeyboardKeys[i][0] == keys[k] || ud.config.KeyboardKeys[i][1] == keys[k])
            {
                Bsprintf(buf, "gamefunc_%s; ", CONFIG_FunctionNumToName(i));
                Bstrcat(tempbuf,buf);
            }
        }

        int const len = Bstrlen(tempbuf);

        if (len >= 2)
        {
            tempbuf[len-2] = 0;  // cut off the trailing "; "
            CONTROL_BindKey(keys[k], tempbuf, 1, sctokeylut[match].key ? sctokeylut[match].key : "<?>");
        }
        else
        {
            CONTROL_FreeKeyBind(keys[k]);
        }
    }
}

void CONFIG_SetupMouse(void)
{
    int32_t i;
    char str[80];
    char temp[80];
    int32_t scale;

    if (ud.config.scripthandle < 0) return;

    for (i=0; i<MAXMOUSEBUTTONS; i++)
    {
        Bsprintf(str,"MouseButton%d",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle,"Controls", str,temp))
            ud.config.MouseFunctions[i][0] = CONFIG_FunctionNameToNum(temp);

        Bsprintf(str,"MouseButtonClicked%d",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle,"Controls", str,temp))
            ud.config.MouseFunctions[i][1] = CONFIG_FunctionNameToNum(temp);
    }

    {
        tempbuf[0] = 0;
        SCRIPT_GetString(ud.config.scripthandle, "Controls","Mouse_Sensitivity",&tempbuf[0]);
        if (tempbuf[0]) CONTROL_MouseSensitivity = atof(tempbuf);
    }

    for (i=0; i<MAXMOUSEBUTTONS; i++)
    {
        CONTROL_MapButton(ud.config.MouseFunctions[i][0], i, 0, controldevice_mouse);
        CONTROL_MapButton(ud.config.MouseFunctions[i][1], i, 1,  controldevice_mouse);
    }
}

void CONFIG_SetupJoystick(void)
{
    int32_t i;
    char str[80];
    char temp[80];
    int32_t scale;

    if (ud.config.scripthandle < 0) return;

    for (i=0; i<MAXJOYBUTTONSANDHATS; i++)
    {
        Bsprintf(str,"ControllerButton%d",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle,"Controls", str,temp))
            ud.config.JoystickFunctions[i][0] = CONFIG_FunctionNameToNum(temp);

        Bsprintf(str,"ControllerButtonClicked%d",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle,"Controls", str,temp))
            ud.config.JoystickFunctions[i][1] = CONFIG_FunctionNameToNum(temp);
    }

    // map over the axes
    for (i=0; i<MAXJOYAXES; i++)
    {
        Bsprintf(str,"ControllerAnalogAxes%d",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle, "Controls", str,temp))
            if (CONFIG_AnalogNameToNum(temp) != -1 || (!temp[0] && CONFIG_FunctionNameToNum(temp) != -1))
                ud.config.JoystickAnalogueAxes[i] = CONFIG_AnalogNameToNum(temp);

        Bsprintf(str,"ControllerDigitalAxes%d_0",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle, "Controls", str,temp))
            if (CONFIG_FunctionNameToNum(temp) != -1 || (!temp[0] && CONFIG_FunctionNameToNum(temp) != -1))
                ud.config.JoystickDigitalFunctions[i][0] = CONFIG_FunctionNameToNum(temp);

        Bsprintf(str,"ControllerDigitalAxes%d_1",i);
        temp[0] = 0;
        if (!SCRIPT_GetString(ud.config.scripthandle, "Controls", str,temp))
            if (CONFIG_FunctionNameToNum(temp) != -1 || (!temp[0] && CONFIG_FunctionNameToNum(temp) != -1))
                ud.config.JoystickDigitalFunctions[i][1] = CONFIG_FunctionNameToNum(temp);

        Bsprintf(str,"ControllerAnalogScale%d",i);
        scale = ud.config.JoystickAnalogueScale[i];
        SCRIPT_GetNumber(ud.config.scripthandle, "Controls", str,&scale);
        ud.config.JoystickAnalogueScale[i] = scale;

        Bsprintf(str,"ControllerAnalogInvert%d",i);
        scale = ud.config.JoystickAnalogueInvert[i];
        SCRIPT_GetNumber(ud.config.scripthandle, "Controls", str,&scale);
        ud.config.JoystickAnalogueInvert[i] = scale;

        Bsprintf(str,"ControllerAnalogDead%d",i);
        scale = ud.config.JoystickAnalogueDead[i];
        SCRIPT_GetNumber(ud.config.scripthandle, "Controls", str,&scale);
        ud.config.JoystickAnalogueDead[i] = scale;

        Bsprintf(str,"ControllerAnalogSaturate%d",i);
        scale = ud.config.JoystickAnalogueSaturate[i];
        SCRIPT_GetNumber(ud.config.scripthandle, "Controls", str,&scale);
        ud.config.JoystickAnalogueSaturate[i] = scale;
    }

    for (i=0; i<MAXJOYBUTTONSANDHATS; i++)
    {
        CONTROL_MapButton(ud.config.JoystickFunctions[i][0], i, 0, controldevice_joystick);
        CONTROL_MapButton(ud.config.JoystickFunctions[i][1], i, 1,  controldevice_joystick);
    }
    for (i=0; i<MAXJOYAXES; i++)
    {
        CONTROL_MapAnalogAxis(i, ud.config.JoystickAnalogueAxes[i]);
        CONTROL_MapDigitalAxis(i, ud.config.JoystickDigitalFunctions[i][0], 0);
        CONTROL_MapDigitalAxis(i, ud.config.JoystickDigitalFunctions[i][1], 1);
        CONTROL_SetAnalogAxisScale(i, ud.config.JoystickAnalogueScale[i], controldevice_joystick);
        CONTROL_SetAnalogAxisInvert(i, ud.config.JoystickAnalogueInvert[i]);
    }
}

struct GameControllerButtonSetting
{
    GameControllerButton button;
    int function;

    void apply() const
    {
        CONFIG_SetJoystickButtonFunction(button, 0, function);
    }
};
struct GameControllerAnalogAxisSetting
{
    GameControllerAxis axis;
    int function;

    void apply() const
    {
        CONFIG_SetJoystickAnalogAxisFunction(axis, function);
    }
};
struct GameControllerDigitalAxisSetting
{
    GameControllerAxis axis;
    int polarity;
    int function;

    void apply() const
    {
        CONFIG_SetJoystickDigitalAxisFunction(axis, polarity, function);
    }
};

static void CONFIG_SetGameControllerAxesModern()
{
    static GameControllerAnalogAxisSetting const analogAxes[] =
    {
        { CONTROLLER_AXIS_LEFTX, analog_strafing },
        { CONTROLLER_AXIS_LEFTY, analog_moving },
        { CONTROLLER_AXIS_RIGHTX, analog_turning },
        { CONTROLLER_AXIS_RIGHTY, analog_lookingupanddown },
    };

    CONFIG_SetJoystickAnalogAxisScale(CONTROLLER_AXIS_RIGHTX, 65536);
    CONFIG_SetJoystickAnalogAxisScale(CONTROLLER_AXIS_RIGHTY, 65536);

    for (auto const & analogAxis : analogAxes)
        analogAxis.apply();
}

void CONFIG_SetGameControllerDefaults()
{
    CONFIG_SetGameControllerDefaultsClear();
    CONFIG_SetGameControllerAxesModern();

    static GameControllerButtonSetting const buttons[] =
    {
        { CONTROLLER_BUTTON_A, gamefunc_Open },
        { CONTROLLER_BUTTON_B, gamefunc_Toggle_Crouch },
        { CONTROLLER_BUTTON_Y, gamefunc_Quick_Kick },
        { CONTROLLER_BUTTON_BACK, gamefunc_Map },
        { CONTROLLER_BUTTON_LEFTSTICK,  gamefunc_Run },
        { CONTROLLER_BUTTON_RIGHTSTICK, gamefunc_Crouch },
        { CONTROLLER_BUTTON_DPAD_UP,    gamefunc_Previous_Weapon },
        { CONTROLLER_BUTTON_DPAD_DOWN,  gamefunc_Next_Weapon },
        { CONTROLLER_BUTTON_LEFTSHOULDER,  gamefunc_Crouch },
        { CONTROLLER_BUTTON_RIGHTSHOULDER, gamefunc_Alt_Fire },
        { CONTROLLER_BUTTON_MISC, gamefunc_Third_Person_View },
    };

    static GameControllerButtonSetting const buttonsDuke[] =
    {
        { CONTROLLER_BUTTON_X, gamefunc_Inventory },
        { CONTROLLER_BUTTON_DPAD_LEFT,  gamefunc_Inventory_Left  },
        { CONTROLLER_BUTTON_DPAD_RIGHT, gamefunc_Inventory_Right },
    };

    static GameControllerButtonSetting const buttonsFury[] =
    {
        { CONTROLLER_BUTTON_X, gamefunc_Steroids }, // Reload
        { CONTROLLER_BUTTON_DPAD_LEFT,  gamefunc_MedKit },
        { CONTROLLER_BUTTON_DPAD_RIGHT, gamefunc_NightVision }, // Radar
    };

    static GameControllerDigitalAxisSetting const digitalAxes[] =
    {
        { CONTROLLER_AXIS_TRIGGERLEFT,  1, gamefunc_Jump },
        { CONTROLLER_AXIS_TRIGGERRIGHT, 1, gamefunc_Fire },
    };

    for (auto const & button : buttons)
        button.apply();

    for (auto const & button : buttonsDuke)
        button.apply();

    for (auto const & digitalAxis : digitalAxes)
        digitalAxis.apply();
}

void CONFIG_SetGameControllerDefaultsClear()
{
    for (int i=0; i<MAXJOYBUTTONSANDHATS; i++)
    {
        CONFIG_SetJoystickButtonFunction(i, 0, -1);
        CONFIG_SetJoystickButtonFunction(i, 1, -1);
    }

    for (int i=0; i<MAXJOYAXES; i++)
    {
        CONFIG_SetJoystickAnalogAxisScale(i, DEFAULTJOYSTICKANALOGUESCALE);
        CONFIG_SetJoystickAnalogAxisInvert(i, 0);
        CONFIG_SetJoystickAnalogAxisDeadSaturate(i, DEFAULTJOYSTICKANALOGUEDEAD, DEFAULTJOYSTICKANALOGUESATURATE);

        CONFIG_SetJoystickDigitalAxisFunction(i, 0, -1);
        CONFIG_SetJoystickDigitalAxisFunction(i, 1, -1);

        CONFIG_SetJoystickAnalogAxisFunction(i, -1);
    }
}

int32_t CONFIG_ReadSetup(void)
{
    int32_t dummy;
    char commmacro[] = "CommbatMacro# ";
    char tempbuf[1024];

    CONTROL_ClearAssignments();
    CONFIG_SetDefaults();

    ud.config.setupread = 1;
    pathsearchmode = 1;

    if (ud.config.scripthandle < 0)
    {
        if (buildvfs_exists(g_setupFileName))  // JBF 20031211
            ud.config.scripthandle = SCRIPT_Load(g_setupFileName);
#if !defined(EDUKE32_TOUCH_DEVICES)
        else if (buildvfs_exists(SETUPFILENAME))
        {
            int32_t i;
            i=wm_ynbox("Import Configuration Settings", "The configuration file \"%s\" was not found. "
                "Import configuration data from \"%s\"?", g_setupFileName, SETUPFILENAME);
            if (i) ud.config.scripthandle = SCRIPT_Load(SETUPFILENAME);
        }
        else if (buildvfs_exists("duke3d.cfg"))
        {
            int32_t i;
            i=wm_ynbox("Import Configuration Settings", "The configuration file \"%s\" was not found. "
                "Import configuration data from \"duke3d.cfg\"?", g_setupFileName);
            if (i) ud.config.scripthandle = SCRIPT_Load("duke3d.cfg");
        }
#endif
    }

    pathsearchmode = 0;

    if (ud.config.scripthandle < 0)
        return -1;

    for (dummy = 0; dummy < MAXRIDECULE; dummy++)
    {
        commmacro[13] = dummy+'0';
        SCRIPT_GetString(ud.config.scripthandle, "Comm Setup",commmacro,&ud.ridecule[dummy][0]);
    }

    Bmemset(tempbuf, 0, sizeof(tempbuf));
    SCRIPT_GetString(ud.config.scripthandle, "Comm Setup","PlayerName",&tempbuf[0]);

    char nameBuf[64];

    while (Bstrlen(OSD_StripColors(nameBuf, tempbuf)) > 10)
        tempbuf[Bstrlen(tempbuf) - 1] = '\0';

    Bstrncpyz(szPlayerName, tempbuf, sizeof(szPlayerName));

    SCRIPT_GetString(ud.config.scripthandle, "Comm Setup","RTSName",&ud.rtsname[0]);

    SCRIPT_GetNumber(ud.config.scripthandle, "Setup", "ConfigVersion", &ud.configversion);
    SCRIPT_GetNumber(ud.config.scripthandle, "Setup", "ForceSetup", &ud.setup.forcesetup);
    SCRIPT_GetNumber(ud.config.scripthandle, "Setup", "NoAutoLoad", &ud.setup.noautoload);
    SCRIPT_GetNumber(ud.config.scripthandle, "Setup", "CacheSize", &dummy);

    if (dummy > MAXCACHE1DSIZE)
        MAXCACHE1DSIZE = dummy;

    if (g_noSetup == 0 && g_modDir[0] == '/')
    {
        struct Bstat st;
        SCRIPT_GetString(ud.config.scripthandle, "Setup","ModDir",&g_modDir[0]);

        if (Bstat(g_modDir, &st))
        {
            if ((st.st_mode & S_IFDIR) != S_IFDIR)
            {
                initprintf("Invalid mod dir in cfg!\n");
                Bsprintf(g_modDir,"/");
            }
        }
    }

    if (g_grpNamePtr == NULL && g_addonNum == 0)
    {
        SCRIPT_GetStringPtr(ud.config.scripthandle, "Setup","SelectedGRP",&g_grpNamePtr);
        if (g_grpNamePtr && !Bstrlen(g_grpNamePtr))
            g_grpNamePtr = dup_filename(G_DefaultGrpFile());
    }

    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "Out",&ud.lockout);
    SCRIPT_GetString(ud.config.scripthandle, "Screen Setup","Password",&ud.pwlockout[0]);

    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "ScreenHeight", &ud.setup.ydim);
    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "ScreenMode", &ud.setup.fullscreen);
    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "ScreenWidth", &ud.setup.xdim);

    vec2_t windowPos;
    if (!SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "WindowPosX", &windowPos.x)
        && !SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "WindowPosY", &windowPos.y))
    {
        g_windowPos = windowPos;
        g_windowPosValid = true;
    }

    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "MaxRefreshFreq", (int32_t *)&maxrefreshfreq);
    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "ScreenBPP", &ud.setup.bpp);

    if (ud.setup.bpp < 8) ud.setup.bpp = 32;

#ifdef POLYMER
    int32_t rendmode = 0;
    SCRIPT_GetNumber(ud.config.scripthandle, "Screen Setup", "Polymer", &rendmode);
    glrendmode = (rendmode > 0) ? REND_POLYMER : REND_POLYMOST;
#endif

    SCRIPT_GetNumber(ud.config.scripthandle, "Misc", "Executions",&ud.executions);

#ifdef _WIN32
    SCRIPT_GetNumber(ud.config.scripthandle, "Updates", "CheckForUpdates", &ud.config.CheckForUpdates);
    SCRIPT_GetNumber(ud.config.scripthandle, "Updates", "LastUpdateCheck", &ud.config.LastUpdateCheck);
#endif

    ud.config.setupread = 1;
    return 0;
}

void CONFIG_WriteSettings(void) // save binds and aliases to <cfgname>_settings.cfg
{
    int32_t i;
    BFILE *fp;
    char *ptr = Xstrdup(g_setupFileName);
    char tempbuf[128];

    if (!Bstrcmp(g_setupFileName, SETUPFILENAME))
        Bsprintf(tempbuf, "settings.cfg");
    else Bsprintf(tempbuf, "%s_settings.cfg", strtok(ptr, "."));

    fp = Bfopen(tempbuf, "wt");

    if (fp)
    {
        Bfprintf(fp,"// this file is automatically generated by %s\n", AppProperName);
        Bfprintf(fp,"unbindall\n");

        for (i=0; i<MAXBOUNDKEYS+MAXMOUSEBUTTONS; i++)
            if (CONTROL_KeyIsBound(i))
                Bfprintf(fp,"bind \"%s\"%s \"%s\"\n",CONTROL_KeyBinds[i].key,
                CONTROL_KeyBinds[i].repeat?"":" norepeat",CONTROL_KeyBinds[i].cmdstr);

        for (int i=0; i<NUMGAMEFUNCTIONS; ++i)
        {
            char const * name = CONFIG_FunctionNumToName(i);
            if (name && name[0] != '\0' && (ud.config.KeyboardKeys[i][0] == 0xff || !ud.config.KeyboardKeys[i][0]))
            {
                Bfprintf(fp,"unbound %s\n", name);
            }
        }

        OSD_WriteAliases(fp);

        if (g_crosshairSum != -1 && g_crosshairSum != DefaultCrosshairColors.r+(DefaultCrosshairColors.g<<8)+(DefaultCrosshairColors.b<<16))
            Bfprintf(fp, "crosshaircolor %d %d %d\n", CrosshairColors.r, CrosshairColors.g, CrosshairColors.b);

        OSD_WriteCvars(fp);

        Bfclose(fp);

        if (!Bstrcmp(g_setupFileName, SETUPFILENAME))
            OSD_Printf("Wrote settings.cfg\n");
        else OSD_Printf("Wrote %s_settings.cfg\n",ptr);

        Xfree(ptr);
        return;
    }

    if (!Bstrcmp(g_setupFileName, SETUPFILENAME))
        OSD_Printf("Error writing settings.cfg: %s\n", strerror(errno));
    else OSD_Printf("Error writing %s_settings.cfg: %s\n",ptr,strerror(errno));

    Xfree(ptr);
}

void CONFIG_WriteSetup(uint32_t flags)
{
    int32_t dummy;

    if (!ud.config.setupread) return;

    if (ud.config.scripthandle < 0)
        ud.config.scripthandle = SCRIPT_Init(g_setupFileName);

    SCRIPT_PutNumber(ud.config.scripthandle, "Misc", "Executions",ud.executions,FALSE,FALSE);

    SCRIPT_PutNumber(ud.config.scripthandle, "Setup","ConfigVersion",BYTEVERSION_EDUKE32,FALSE,FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Setup", "ForceSetup", ud.setup.forcesetup, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Setup", "NoAutoLoad", ud.setup.noautoload, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Setup", "CacheSize", MAXCACHE1DSIZE, FALSE, FALSE);

#ifdef POLYMER
    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "Polymer",glrendmode == REND_POLYMER,FALSE,FALSE);
#endif

    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "ScreenBPP", ud.setup.bpp, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "ScreenHeight", ud.setup.ydim, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "ScreenMode", ud.setup.fullscreen, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "ScreenWidth", ud.setup.xdim, FALSE, FALSE);

    if (g_grpNamePtr && !g_addonNum)
        SCRIPT_PutString(ud.config.scripthandle, "Setup","SelectedGRP",g_grpNamePtr);

#ifdef STARTUP_SETUP_WINDOW
    if (g_noSetup == 0)
        SCRIPT_PutString(ud.config.scripthandle, "Setup","ModDir",&g_modDir[0]);
#endif
    // exit early after only updating the values that can be changed from the startup window
    if (flags & 1)
    {
        SCRIPT_Save(ud.config.scripthandle, g_setupFileName);
        SCRIPT_Free(ud.config.scripthandle);
        return;
    }

    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "MaxRefreshFreq", maxrefreshfreq, FALSE, FALSE);
    if (g_windowPosValid)
    {
        SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "WindowPosX", g_windowPos.x, FALSE, FALSE);
        SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "WindowPosY", g_windowPos.y, FALSE, FALSE);
    }

    SCRIPT_PutNumber(ud.config.scripthandle, "Screen Setup", "Out",ud.lockout,FALSE,FALSE);
    SCRIPT_PutString(ud.config.scripthandle, "Screen Setup", "Password",ud.pwlockout);

#ifdef _WIN32
    SCRIPT_PutNumber(ud.config.scripthandle, "Updates", "CheckForUpdates", ud.config.CheckForUpdates, FALSE, FALSE);
    SCRIPT_PutNumber(ud.config.scripthandle, "Updates", "LastUpdateCheck", ud.config.LastUpdateCheck, FALSE, FALSE);
#endif

    if (ud.setup.usemouse)
    {
        for (dummy=0; dummy<MAXMOUSEBUTTONS; dummy++)
        {
            if (CONFIG_FunctionNumToName(ud.config.MouseFunctions[dummy][0]))
            {
                Bsprintf(buf, "MouseButton%d", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.MouseFunctions[dummy][0]));
            }

            if (dummy >= (MAXMOUSEBUTTONS-2)) continue;

            if (CONFIG_FunctionNumToName(ud.config.MouseFunctions[dummy][1]))
            {
                Bsprintf(buf, "MouseButtonClicked%d", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.MouseFunctions[dummy][1]));
            }
        }
    }

    if (ud.setup.usejoystick)
    {
        for (dummy=0; dummy<MAXJOYBUTTONSANDHATS; dummy++)
        {
            if (CONFIG_FunctionNumToName(ud.config.JoystickFunctions[dummy][0]))
            {
                Bsprintf(buf, "ControllerButton%d", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.JoystickFunctions[dummy][0]));
            }

            if (CONFIG_FunctionNumToName(ud.config.JoystickFunctions[dummy][1]))
            {
                Bsprintf(buf, "ControllerButtonClicked%d", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.JoystickFunctions[dummy][1]));
            }
        }
        for (dummy=0; dummy<MAXJOYAXES; dummy++)
        {
            if (CONFIG_AnalogNumToName(ud.config.JoystickAnalogueAxes[dummy]))
            {
                Bsprintf(buf, "ControllerAnalogAxes%d", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_AnalogNumToName(ud.config.JoystickAnalogueAxes[dummy]));
            }

            if (CONFIG_FunctionNumToName(ud.config.JoystickDigitalFunctions[dummy][0]))
            {
                Bsprintf(buf, "ControllerDigitalAxes%d_0", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.JoystickDigitalFunctions[dummy][0]));
            }

            if (CONFIG_FunctionNumToName(ud.config.JoystickDigitalFunctions[dummy][1]))
            {
                Bsprintf(buf, "ControllerDigitalAxes%d_1", dummy);
                SCRIPT_PutString(ud.config.scripthandle, "Controls", buf, CONFIG_FunctionNumToName(ud.config.JoystickDigitalFunctions[dummy][1]));
            }

            if (ud.config.JoystickAnalogueScale[dummy] != DEFAULTJOYSTICKANALOGUESCALE)
            {
                Bsprintf(buf, "ControllerAnalogScale%d", dummy);
                SCRIPT_PutNumber(ud.config.scripthandle, "Controls", buf, ud.config.JoystickAnalogueScale[dummy], FALSE, FALSE);
            }

            Bsprintf(buf, "ControllerAnalogInvert%d", dummy);
            SCRIPT_PutNumber(ud.config.scripthandle, "Controls", buf, ud.config.JoystickAnalogueInvert[dummy], FALSE, FALSE);

            if (ud.config.JoystickAnalogueDead[dummy] != DEFAULTJOYSTICKANALOGUEDEAD)
            {
                Bsprintf(buf, "ControllerAnalogDead%d", dummy);
                SCRIPT_PutNumber(ud.config.scripthandle, "Controls", buf, ud.config.JoystickAnalogueDead[dummy], FALSE, FALSE);
            }

            if (ud.config.JoystickAnalogueSaturate[dummy] != DEFAULTJOYSTICKANALOGUESATURATE)
            {
                Bsprintf(buf, "ControllerAnalogSaturate%d", dummy);
                SCRIPT_PutNumber(ud.config.scripthandle, "Controls", buf, ud.config.JoystickAnalogueSaturate[dummy], FALSE, FALSE);
            }
        }
    }

    SCRIPT_PutString(ud.config.scripthandle, "Comm Setup","PlayerName",&szPlayerName[0]);

    SCRIPT_PutString(ud.config.scripthandle, "Comm Setup","RTSName",&ud.rtsname[0]);

    char commmacro[] = "CommbatMacro# ";

    for (dummy = 0; dummy < MAXRIDECULE; dummy++)
    {
        commmacro[13] = dummy+'0';
        SCRIPT_PutString(ud.config.scripthandle, "Comm Setup",commmacro,&ud.ridecule[dummy][0]);
    }

    SCRIPT_Save(ud.config.scripthandle, g_setupFileName);

    if ((flags & 2) == 0)
        SCRIPT_Free(ud.config.scripthandle);

    OSD_Printf("Wrote %s\n",g_setupFileName);
    CONFIG_WriteSettings();
    Bfflush(NULL);
}

static const char *CONFIG_GetMapEntryName(char m[], char const * const mapname)
{
    strcpy(m, mapname);

    char *p = strrchr(m, '/');
    if (!p) p = strrchr(m, '\\');
    if (p) Bmemmove(m, p, Bstrlen(p)+1);
    for (p=m; *p; p++) *p = tolower(*p);

    // cheap hack because SCRIPT_GetNumber doesn't like the slashes
    p = m;
    while (*p == '/') p++;

    return p;
}

static void CONFIG_GetMD4EntryName(char m[], uint8_t const * const md4)
{
    sprintf(m, "MD4_%08x%08x%08x%08x",
            B_BIG32(B_UNBUF32(&md4[0])), B_BIG32(B_UNBUF32(&md4[4])),
            B_BIG32(B_UNBUF32(&md4[8])), B_BIG32(B_UNBUF32(&md4[12])));
}

int32_t CONFIG_GetMapBestTime(char const * const mapname, uint8_t const * const mapmd4)
{
    if (!ud.config.setupread || ud.config.scripthandle < 0)
        return -1;

    char m[37];
    CONFIG_GetMD4EntryName(m, mapmd4);

    int32_t t = -1;
    if (SCRIPT_GetNumber(ud.config.scripthandle, "MapTimes", m, &t))
    {
        // fall back to map filenames
        char m2[BMAX_PATH];
        char const * const p = CONFIG_GetMapEntryName(m2, mapname);
        SCRIPT_GetNumber(ud.config.scripthandle, "MapTimes", p, &t);
    }
    return t;
}

int32_t CONFIG_SetMapBestTime(uint8_t const * const mapmd4, int32_t const tm)
{
    if (ud.config.scripthandle < 0) ud.config.scripthandle = SCRIPT_Init(g_setupFileName);
    if (ud.config.scripthandle < 0) return -1;

    char m[37];
    CONFIG_GetMD4EntryName(m, mapmd4);

    SCRIPT_PutNumber(ud.config.scripthandle, "MapTimes", m, tm, FALSE, FALSE);
    return 0;
}

repo_name: orochi/nblood

license: mit


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.
*/
//-------------------------------------------------------------------------

#ifndef config_public_h_
#define config_public_h_

#include "function.h"

#define SETUPNAMEPARM "SETUPFILE"

int32_t CONFIG_ReadSetup( void );
void CONFIG_GetSetupFilename( void );
void CONFIG_WriteSetup(uint32_t flags);
void CONFIG_SetupMouse( void );
void CONFIG_SetupJoystick( void );
void CONFIG_SetDefaultKeys(const char (*keyptr)[MAXGAMEFUNCLEN], bool lazy=false);

void CONFIG_SetGameControllerDefaults(void);
void CONFIG_SetGameControllerDefaultsClear(void);

int32_t CONFIG_GetMapBestTime(char const * mapname, uint8_t const * mapmd4);
int32_t CONFIG_SetMapBestTime(uint8_t const * mapmd4, int32_t tm);

void CONFIG_MapKey(int32_t which, kb_scancode key1, kb_scancode oldkey1, kb_scancode key2, kb_scancode oldkey2);

int32_t CONFIG_FunctionNameToNum(const char *func);
char *CONFIG_FunctionNumToName(int32_t func);
int32_t CONFIG_AnalogNameToNum(const char *func);
const char *CONFIG_AnalogNumToName(int32_t func);
void CONFIG_SetDefaults(void);

#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 "duke3d.h"
#include "demo.h"
//#include "premap.h"  // G_UpdateScreenArea()
#include "menus.h"
#include "savegame.h"
#include "input.h"
#include "screens.h"

char g_firstDemoFile[BMAX_PATH];

FILE *g_demo_filePtr = (FILE *)NULL;  // write
int32_t g_demo_recFilePtr = -1;  // read

int32_t g_demo_cnt;
int32_t g_demo_goalCnt=0;
int32_t g_demo_totalCnt;
int32_t g_demo_paused=0;
int32_t g_demo_rewind=0;
int32_t g_demo_showStats=0;
static int32_t g_demo_soundToggle;

static int32_t demo_hasdiffs, demorec_diffs=1, demorec_difftics = 2*REALGAMETICSPERSEC;
int32_t demoplay_diffs=1;
int32_t demorec_diffs_cvar=1;
int32_t demorec_force_cvar=0;
int32_t demorec_difftics_cvar = 2*REALGAMETICSPERSEC;
int32_t demorec_diffcompress_cvar=1;
int32_t demorec_synccompress_cvar=1;
int32_t demorec_seeds_cvar=1;
int32_t demoplay_showsync=1;

static int32_t demo_synccompress=1, demorec_seeds=1, demo_hasseeds;

char g_demo_legacy = 0;
int32_t demo_reccnt_init = 0;

#pragma pack(push,1)
typedef struct {
    int32_t reccnt;
    int8_t version; // 117 for Duke 3d v1.5, 108 for RR(RA)
    int8_t volume_number, level_number, player_skill, m_coop, m_ffire;
    int16_t multimode, m_monsters_off;
    int32_t m_respawn_monsters, m_respawn_items, m_respawn_inventory, playerai;
    char user_name[16][32];
} legacydemo_t;

typedef struct {
    int8_t avel, horz;
    int16_t fvel, svel;
    int32_t bits;
} legacyinput_t;
#pragma pack(pop)

static void Demo_RestoreModes(int32_t menu)
{
    if (menu)
        Menu_Open(myconnectindex);
    else
        Menu_Close(myconnectindex);

    g_player[myconnectindex].ps->gm &= ~MODE_GAME;
    g_player[myconnectindex].ps->gm |= MODE_DEMO;
}

void Demo_PrepareWarp(void)
{
    if (!g_demo_paused)
    {
        g_demo_soundToggle = ud.config.SoundToggle;
        ud.config.SoundToggle = 0;
    }

    FX_StopAllSounds();
    S_ClearSoundLocks();
}

static int32_t G_OpenDemoRead(int32_t g_whichDemo) // 0 = mine
{
    int32_t i;
    savehead_t saveh;

    char demofn[14];
    const char *demofnptr;

    if (DEER)
        return 0;

    if (g_whichDemo == 1 && g_firstDemoFile[0])
    {
        demofnptr = g_firstDemoFile;
        const int fileNameLen = Bstrlen(g_firstDemoFile);
        if (fileNameLen >= 4 && !Bstrncasecmp(&g_firstDemoFile[fileNameLen - 4], ".dmo", 4))
            g_demo_legacy = 1;
        else
            g_demo_legacy = 0;
    }
    else
    {
        Bsprintf(demofn, DEMOFN_FMT, g_whichDemo);
        demofnptr = demofn;
        g_demo_legacy = 0;
    }

    g_demo_recFilePtr = kopen4loadfrommod(demofnptr, g_loadFromGroupOnly);
    if (g_demo_recFilePtr == -1)
    {
        // Check for legacy demo
        Bsprintf(demofn, LDEMOFN_FMT, g_whichDemo);
        demofnptr = demofn;
        g_demo_legacy = 1;
        g_demo_recFilePtr = kopen4loadfrommod(demofnptr, g_loadFromGroupOnly);
        if (g_demo_recFilePtr == -1)
            return 0;
    }

    if (g_demo_legacy)
    {
        ud.reccnt = 0;

        legacydemo_t demoHeader;

        if (kread(g_demo_recFilePtr, &demoHeader, sizeof(legacydemo_t)) != sizeof(legacydemo_t))
        {
            kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;
            return 0;
        }

        demoHeader.reccnt = B_LITTLE32(demoHeader.reccnt);
        demoHeader.multimode = B_LITTLE16(demoHeader.multimode);
        demoHeader.m_monsters_off = B_LITTLE16(demoHeader.m_monsters_off);
        demoHeader.m_respawn_monsters = B_LITTLE32(demoHeader.m_respawn_monsters);
        demoHeader.m_respawn_items = B_LITTLE32(demoHeader.m_respawn_items);
        demoHeader.m_respawn_inventory = B_LITTLE32(demoHeader.m_respawn_inventory);
        demoHeader.playerai = B_LITTLE32(demoHeader.playerai);

        ud.volume_number = demoHeader.volume_number;
        ud.level_number = demoHeader.level_number;
        ud.player_skill = demoHeader.player_skill;
        ud.m_coop = demoHeader.m_coop;
        ud.m_ffire = demoHeader.m_ffire;
        ud.multimode = demoHeader.multimode;
        ud.m_monsters_off = demoHeader.m_monsters_off;
        ud.m_respawn_monsters = demoHeader.m_respawn_monsters;
        ud.m_respawn_items = demoHeader.m_respawn_items;
        ud.m_respawn_inventory = demoHeader.m_respawn_inventory;

        for (bssize_t i = 0; i < demoHeader.multimode; i++)
        {
            Bstrncpy(g_player[i].user_name, demoHeader.user_name[i], 32);
        }

        if (!RR && demoHeader.version == 117)
        {
            int32_t autoRun;
            kread(g_demo_recFilePtr, &autoRun, sizeof(int32_t));
            //ud.auto_run = autoRun;
            kread(g_demo_recFilePtr, boardfilename, 128);
            if (boardfilename[0] != 0)
            {
                ud.m_level_number = 7;
                ud.m_volume_number = 0;
            }
        }
        else if (RR && demoHeader.version == 108)
        {
            // no op
        }
        else
        {
            kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;
            return 0;
        }

        for (bssize_t i = 0; i < ud.multimode; i++)
        {
            kread(g_demo_recFilePtr, &g_player[i].ps->aim_mode, 1);
            g_player[i].ps->auto_aim = 1;
        }

        g_demo_totalCnt = demoHeader.reccnt/ud.multimode;

        i = g_demo_totalCnt/REALGAMETICSPERSEC;
        OSD_Printf("demo %d duration: %d min %d sec\n", g_whichDemo, i/60, i%60);
        g_demo_cnt = 1;

        g_mostConcurrentPlayers = ud.multimode;

        ud.god = ud.cashman = ud.eog = ud.showallmap = 0;
        ud.noclip = ud.scrollmode = ud.overhead_on = 0; //= ud.pause_on = 0;

        totalclock = ototalclock = lockclock = 0;

        G_NewGame(ud.volume_number, ud.level_number, ud.player_skill);

        demo_reccnt_init = ud.reccnt = demoHeader.reccnt;

        return 1;
    }

    Bassert(g_whichDemo >= 1);
    i = sv_loadsnapshot(g_demo_recFilePtr, -g_whichDemo, &saveh);
    if (i)
    {
        OSD_Printf(OSD_ERROR "There were errors opening demo %d (code: %d).\n", g_whichDemo, i);
        kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;
        return 0;
    }

    demo_hasdiffs = saveh.recdiffsp;
    g_demo_totalCnt = saveh.reccnt;
    demo_synccompress = saveh.synccompress;

    demo_hasseeds = demo_synccompress&2;
    demo_synccompress &= 1;

    i = g_demo_totalCnt/REALGAMETICSPERSEC;
    OSD_Printf("demo %d duration: %d min %d sec\n", g_whichDemo, i/60, i%60);

    g_demo_cnt = 1;
    ud.reccnt = 0;

    g_mostConcurrentPlayers = ud.multimode;

    ud.god = ud.cashman = ud.eog = ud.showallmap = 0;
    ud.noclip = ud.scrollmode = ud.overhead_on = 0; //= ud.pause_on = 0;

    totalclock = ototalclock = lockclock = 0;

    return 1;
}

#if KRANDDEBUG
extern void krd_enable(int32_t which);
extern int32_t krd_print(const char *filename);
#endif

void G_OpenDemoWrite(void)
{
    char demofn[BMAX_PATH];
    int32_t i, demonum=1;

    if (ud.recstat == 2)
    {
        kclose(g_demo_recFilePtr);
        g_demo_recFilePtr = -1;
    }

    if ((g_player[myconnectindex].ps->gm&MODE_GAME) && g_player[myconnectindex].ps->dead_flag)
    {
        Bstrcpy(apStrings[QUOTE_RESERVED4], "CANNOT START DEMO RECORDING WHEN DEAD!");
        P_DoQuote(QUOTE_RESERVED4, g_player[myconnectindex].ps);
        ud.recstat = ud.m_recstat = 0;
        return;
    }
    do
    {
        if (demonum == MAXDEMOS)
            return;

        if (G_ModDirSnprintf(demofn, sizeof(demofn), DEMOFN_FMT, demonum))
        {
            initprintf("Couldn't start demo writing: INTERNAL ERROR: file name too long\n");
            goto error_wopen_demo;
        }

        demonum++;

        g_demo_filePtr = Bfopen(demofn, "rb");
        if (g_demo_filePtr == NULL)
            break;

        MAYBE_FCLOSE_AND_NULL(g_demo_filePtr);
    }
    while (1);

    g_demo_filePtr = Bfopen(demofn,"wb");
    if (g_demo_filePtr == NULL)
        return;

    i=sv_saveandmakesnapshot(g_demo_filePtr, nullptr, -1, demorec_diffs_cvar, demorec_diffcompress_cvar,
                             demorec_synccompress_cvar|(demorec_seeds_cvar<<1));
    if (i)
    {
        MAYBE_FCLOSE_AND_NULL(g_demo_filePtr);
error_wopen_demo:
        Bstrcpy(apStrings[QUOTE_RESERVED4], "FAILED STARTING DEMO RECORDING. SEE OSD FOR DETAILS.");
        P_DoQuote(QUOTE_RESERVED4, g_player[myconnectindex].ps);
        ud.recstat = ud.m_recstat = 0;
        return;
    }

    demorec_seeds = demorec_seeds_cvar;
    demorec_diffs = demorec_diffs_cvar;
    demo_synccompress = demorec_synccompress_cvar;
    demorec_difftics = demorec_difftics_cvar;

    Bsprintf(apStrings[QUOTE_RESERVED4], "DEMO %d RECORDING STARTED", demonum-1);
    P_DoQuote(QUOTE_RESERVED4, g_player[myconnectindex].ps);

    ud.reccnt = 0;
    ud.recstat = ud.m_recstat = 1;  //

# if KRANDDEBUG
    krd_enable(1);
# endif
    g_demo_cnt = 1;
}

// demo_profile: < 0: prepare
static int32_t g_demo_playFirstFlag, g_demo_profile, g_demo_stopProfile;
static int32_t g_demo_exitAfter;
void Demo_PlayFirst(int32_t prof, int32_t exitafter)
{
    g_demo_playFirstFlag = 1;
    g_demo_exitAfter = exitafter;
    Bassert(prof >= 0);
    g_demo_profile = -prof;  // prepare
}

void Demo_SetFirst(const char *demostr)
{
    char *tailptr;
    int32_t i = Bstrtol(demostr, &tailptr, 10);

    if (tailptr==demostr+Bstrlen(demostr) && (unsigned)i < MAXDEMOS)  // demo number passed
        Bsprintf(g_firstDemoFile, DEMOFN_FMT, i);
    else  // demo file name passed
    {
        int l = Bstrlen(demostr);
        if (l >= 4 && !Bstrcasecmp(&demostr[l-4], ".dmo"))
            Bstrcpy(g_firstDemoFile, demostr);
        else
            maybe_append_ext(g_firstDemoFile, sizeof(g_firstDemoFile), demostr, ".edm");
    }
}

static uint8_t g_demo_seedbuf[RECSYNCBUFSIZ];

static void Demo_WriteSync()
{
    int16_t tmpreccnt;

    fwrite("sYnC", 4, 1, g_demo_filePtr);
    tmpreccnt = (int16_t)ud.reccnt;
    fwrite(&tmpreccnt, sizeof(int16_t), 1, g_demo_filePtr);
    if (demorec_seeds)
        fwrite(g_demo_seedbuf, 1, ud.reccnt, g_demo_filePtr);

    if (demo_synccompress)
        dfwrite_LZ4(recsync, sizeof(input_t), ud.reccnt, g_demo_filePtr);
    else //if (demo_synccompress==0)
        fwrite(recsync, sizeof(input_t), ud.reccnt, g_demo_filePtr);

    ud.reccnt = 0;
}

void G_DemoRecord(void)
{
    int16_t i;

    g_demo_cnt++;

    if (demorec_diffs && (g_demo_cnt%demorec_difftics == 1))
    {
        sv_writediff(g_demo_filePtr);
        demorec_difftics = demorec_difftics_cvar;
    }

    if (demorec_seeds)
        g_demo_seedbuf[ud.reccnt] = (uint8_t)(randomseed>>24);

    for (TRAVERSE_CONNECT(i))
    {
        Bmemcpy(&recsync[ud.reccnt], g_player[i].inputBits, sizeof(input_t));
        ud.reccnt++;
    }

    if (ud.reccnt > RECSYNCBUFSIZ-MAXPLAYERS || (demorec_diffs && (g_demo_cnt%demorec_difftics == 0)))
        Demo_WriteSync();
}

void G_CloseDemoWrite(void)
{
    if (ud.recstat == 1)
    {
        if (ud.reccnt > 0)
            Demo_WriteSync();

        fwrite("EnD!", 4, 1, g_demo_filePtr);

        // lastly, we need to write the number of written recsyncs to the demo file
        if (fseek(g_demo_filePtr, offsetof(savehead_t, reccnt), SEEK_SET))
            perror("G_CloseDemoWrite: final fseek");
        else
            fwrite(&g_demo_cnt, sizeof(g_demo_cnt), 1, g_demo_filePtr);

        ud.recstat = ud.m_recstat = 0;
        MAYBE_FCLOSE_AND_NULL(g_demo_filePtr);

        sv_freemem();

        Bstrcpy(apStrings[QUOTE_RESERVED4], "DEMO RECORDING STOPPED");
        P_DoQuote(QUOTE_RESERVED4, g_player[myconnectindex].ps);
    }
#if KRANDDEBUG
    krd_print("krandrec.log");
#endif
}

static int32_t g_whichDemo = 1;

static int32_t Demo_UpdateState(int32_t frominit)
{
    int32_t j = g_player[myconnectindex].ps->gm&MODE_MENU;
    int32_t k = sv_updatestate(frominit);
    //                            tmpdifftime = g_demo_cnt+12;
    Demo_RestoreModes(j);

    if (k)
        OSD_Printf("sv_updatestate() returned %d.\n", k);
    return k;
}

#define CORRUPT(code) do { corruptcode=code; goto corrupt; } while(0)

static int32_t Demo_ReadSync(int32_t errcode)
{
    uint16_t si;
    int32_t i;

    if (kread(g_demo_recFilePtr, &si, sizeof(uint16_t)) != sizeof(uint16_t))
        return errcode;

    i = si;
    if (demo_hasseeds)
    {
        if (kread(g_demo_recFilePtr, g_demo_seedbuf, i) != i)
            return errcode;
    }

    if (demo_synccompress)
    {
        if (kdfread_LZ4(recsync, sizeof(input_t), i, g_demo_recFilePtr) != i)
            return errcode+1;
    }
    else
    {
        int32_t bytes = sizeof(input_t)*i;

        if (kread(g_demo_recFilePtr, recsync, bytes) != bytes)
            return errcode+2;
    }

    ud.reccnt = i;
    return 0;
}

legacyinput_t recsynclegacy[RECSYNCBUFSIZ];

static void Demo_ReadSyncLegacy(void)
{
    int32_t l = min(ud.reccnt, RECSYNCBUFSIZ) / ud.multimode;

    kdfread(recsynclegacy, sizeof(legacyinput_t)*ud.multimode, l, g_demo_recFilePtr);

    for (bssize_t i = 0; i < l; i ++) {
        for (int j = 0; j < ud.multimode; j++)
        {
            int32_t index = i * ud.multimode + j;
            recsync[index].q16avel = F16(recsynclegacy[index].avel<<1);
            recsync[index].q16horz = F16(recsynclegacy[index].horz>>1);
            recsync[index].fvel = B_LITTLE16(recsynclegacy[index].fvel);
            recsync[index].svel = B_LITTLE16(recsynclegacy[index].svel);
            recsync[index].bits = B_LITTLE32(recsynclegacy[index].bits);
            recsync[index].extbits = 0;
        }
    }
}

////////// DEMO PROFILING (TIMEDEMO MODE) //////////
static struct {
    int32_t numtics, numframes;
    double totalgamems;
    double totalroomsdrawms, totalrestdrawms;
    double starthiticks;
} g_prof;

int32_t Demo_IsProfiling(void)
{
    return (g_demo_profile > 0);
}

static void Demo_StopProfiling(void)
{
    g_demo_stopProfile = 1;
}

static void Demo_GToc(double t)
{
    g_prof.numtics++;
    g_prof.totalgamems += timerGetFractionalTicks()-t;
}

static void Demo_RToc(double t1, double t2)
{
    g_prof.numframes++;
    g_prof.totalroomsdrawms += t2-t1;
    g_prof.totalrestdrawms += timerGetFractionalTicks()-t2;
}

static void Demo_DisplayProfStatus(void)
{
    char buf[64];

    static int32_t lastpercent=-1;
    int32_t percent = (100*g_demo_cnt)/g_demo_totalCnt;

    if (lastpercent == percent)
        return;
    lastpercent = percent;

    videoClearScreen(0);
    Bsnprintf(buf, sizeof(buf), "timing... %d/%d game tics (%d %%)",
              g_demo_cnt, g_demo_totalCnt, percent);
    gametext_center(60, buf);
    videoNextPage();
}

static void Demo_SetupProfile(void)
{
    g_demo_profile *= -1;  // now >0: profile for real

    g_demo_soundToggle = ud.config.SoundToggle;
    ud.config.SoundToggle = 0;  // restored by Demo_FinishProfile()

    Bmemset(&g_prof, 0, sizeof(g_prof));

    g_prof.starthiticks = timerGetFractionalTicks();
}

static void Demo_FinishProfile(void)
{
    if (Demo_IsProfiling())
    {
        int32_t dn=g_whichDemo-1;
        int32_t nt=g_prof.numtics, nf=g_prof.numframes;
        double gms=g_prof.totalgamems;
        double dms1=g_prof.totalroomsdrawms, dms2=g_prof.totalrestdrawms;

        ud.config.SoundToggle = g_demo_soundToggle;

        if (nt > 0)
        {
            OSD_Printf("== demo %d: %d gametics\n", dn, nt);
            OSD_Printf("== demo %d game times: %.03f ms (%.03f us/gametic)\n",
                       dn, gms, (gms*1000.0)/nt);
        }

        if (nf > 0)
        {
            OSD_Printf("== demo %d: %d frames (%d frames/gametic)\n", dn, nf, g_demo_profile-1);
            OSD_Printf("== demo %d drawrooms times: %.03f s (%.03f ms/frame)\n",
                       dn, dms1/1000.0, dms1/nf);
            OSD_Printf("== demo %d drawrest times: %.03f s (%.03f ms/frame)\n",
                       dn, dms2/1000.0, dms2/nf);
        }

        {
            double totalprofms = gms+dms1+dms2;
            double totalms = timerGetFractionalTicks()-g_prof.starthiticks;
            if (totalprofms != 0)
                OSD_Printf("== demo %d: non-profiled time overhead: %.02f %%\n",
                           dn, 100.0*totalms/totalprofms - 100.0);
        }
    }

    g_demo_profile = 0;
    g_demo_stopProfile = 0;
}
////////////////////

int32_t G_PlaybackDemo(void)
{
    int32_t bigi, j, initsyncofs = 0, lastsyncofs = 0, lastsynctic = 0, lastsyncclock = 0;
    int32_t foundemo = 0, corruptcode, outofsync=0;
    static int32_t in_menu = 0;
    //    static int32_t tmpdifftime=0;

    totalclock = 0;
    ototalclock = 0;
    lockclock = 0;

    if (ready2send)
        return 0;

    if (!g_demo_playFirstFlag)
        g_demo_profile = 0;

RECHECK:
    if (g_demo_playFirstFlag)
        g_demo_playFirstFlag = 0;
    else if (g_demo_exitAfter)
        G_GameExit(" ");

#if KRANDDEBUG
    if (foundemo)
        krd_print("krandplay.log");
#endif

    in_menu = g_player[myconnectindex].ps->gm&MODE_MENU;

    pub = NUMPAGES;
    pus = NUMPAGES;

    renderFlushPerms();

    if (!g_netServer && ud.multimode < 2)
        foundemo = G_OpenDemoRead(g_whichDemo);

    if (foundemo == 0)
    {
        ud.recstat = 0;

        if (g_whichDemo > 1)
        {
            g_whichDemo = 1;
            goto RECHECK;
        }

        fadepal(0,0,0, 0,252,28);
        P_SetGamePalette(g_player[myconnectindex].ps, BASEPAL, 1);    // JBF 20040308
        G_DrawBackground();
        M_DisplayMenus();
        videoNextPage();
        fadepal(0,0,0, 252,0,-28);
        ud.reccnt = 0;
    }
    else
    {
        ud.recstat = 2;

        g_whichDemo++;
        if (g_whichDemo == MAXDEMOS)
            g_whichDemo = 1;

        g_player[myconnectindex].ps->gm &= ~MODE_GAME;
        g_player[myconnectindex].ps->gm |= MODE_DEMO;

        if (g_demo_legacy)
            G_EnterLevel(MODE_DEMO);

        lastsyncofs = ktell(g_demo_recFilePtr);
        initsyncofs = lastsyncofs;
        lastsynctic = g_demo_cnt;
        lastsyncclock = (int32_t) totalclock;
        outofsync = 0;
#if KRANDDEBUG
        krd_enable(2);
#endif
        if (g_demo_profile < 0)
        {
            Demo_SetupProfile();
        }
    }

    if (foundemo == 0 || in_menu || I_CheckAllInput() || numplayers > 1)
    {
        FX_StopAllSounds();
        S_ClearSoundLocks();
        Menu_Open(myconnectindex);
    }

    ready2send = 0;
    bigi = 0;

    I_ClearAllInput();

    //    OSD_Printf("ticcnt=%d, total=%d\n", g_demo_cnt, g_demo_totalCnt);
    while (g_demo_cnt < g_demo_totalCnt || foundemo==0)
    {
        // Main loop here. It also runs when there's no demo to show,
        // so maybe a better name for this function would be
        // G_MainLoopWhenNotInGame()?

        // Demo requested from the OSD, its name is in g_firstDemoFile[]
        if (g_demo_playFirstFlag)
        {
            g_demo_playFirstFlag = 0;
            g_whichDemo = 1;  // force g_firstDemoFile[]
            g_demo_paused = 0;
            goto nextdemo_nomenu;
        }

        if (foundemo && (!g_demo_paused || g_demo_goalCnt))
        {
            if (g_demo_goalCnt>0 && g_demo_goalCnt < g_demo_cnt)
            {
                // initialize rewind

                int32_t menu = g_player[myconnectindex].ps->gm&MODE_MENU;

                if (g_demo_legacy)
                {
                    klseek(g_demo_recFilePtr, initsyncofs, SEEK_SET);
                    g_levelTextTime = 0;

                    g_demo_cnt = 1;
                    ud.reccnt = demo_reccnt_init;
                    bigi = 0;

                    totalclock = ototalclock = lockclock = 0;

                    G_EnterLevel(MODE_DEMO);
                }
                else
                {
                    if (g_demo_goalCnt > lastsynctic)
                    {
                        // we can use a previous diff
                        if (Demo_UpdateState(0)==0)
                        {
                            g_demo_cnt = lastsynctic;
                            klseek(g_demo_recFilePtr, lastsyncofs, SEEK_SET);
                            ud.reccnt = 0;

                            totalclock = ototalclock = lockclock = lastsyncclock;
                        }
                        else CORRUPT(-1);
                    }
                    else
                    {
                        // update to initial state
                        if (Demo_UpdateState(1) == 0)
                        {
                            klseek(g_demo_recFilePtr, initsyncofs, SEEK_SET);
                            g_levelTextTime = 0;

                            g_demo_cnt = 1;
                            ud.reccnt = 0;

                            //                        ud.god = ud.cashman = ud.eog = ud.showallmap = 0;
                            //                        ud.noclip = ud.scrollmode = ud.overhead_on = ud.pause_on = 0;

                            totalclock = ototalclock = lockclock = 0;
                        }
                        else CORRUPT(0);
                    }
                }

                Demo_RestoreModes(menu);
            }

            if (g_demo_stopProfile)
                Demo_FinishProfile();

            while (totalclock >= (lockclock+TICSPERFRAME)
                //                   || (ud.reccnt > REALGAMETICSPERSEC*2 && ud.pause_on)
                || (g_demo_goalCnt>0 && g_demo_cnt<g_demo_goalCnt))
            {
                if (g_demo_legacy)
                {
                    if (bigi == 0 || bigi >= RECSYNCBUFSIZ)
                    {
                        bigi = 0;
                        Demo_ReadSyncLegacy();
                    }
                }
                else
                {
                    if (ud.reccnt<=0)
                    {
                        // Record count reached zero (or <0, corrupted), need
                        // reading another chunk.

                        char tmpbuf[4];

                        if (ud.reccnt<0)
                        {
                            OSD_Printf("G_PlaybackDemo: ud.reccnt<0!\n");
                            CORRUPT(1);
                        }

                        bigi = 0;
                        //reread:
                        if (kread(g_demo_recFilePtr, tmpbuf, 4) != 4)
                            CORRUPT(2);

                        if (Bmemcmp(tmpbuf, "sYnC", 4)==0)
                        {
                            int32_t err = Demo_ReadSync(3);
                            if (err)
                                CORRUPT(err);
                        }

                        else if (demo_hasdiffs && Bmemcmp(tmpbuf, "dIfF", 4)==0)
                        {
                            int32_t k = sv_readdiff(g_demo_recFilePtr);

                            if (k)
                            {
                                OSD_Printf("sv_readdiff() returned %d.\n", k);
                                CORRUPT(6);
                            }
                            else
                            {
                                lastsyncofs = ktell(g_demo_recFilePtr);
                                lastsynctic = g_demo_cnt;
                                lastsyncclock = (int32_t) totalclock;

                                if (kread(g_demo_recFilePtr, tmpbuf, 4) != 4)
                                    CORRUPT(7);
                                if (Bmemcmp(tmpbuf, "sYnC", 4))
                                    CORRUPT(8);

                                {
                                    int32_t err = Demo_ReadSync(9);
                                    if (err)
                                        CORRUPT(err);
                                }

                                if ((g_demo_goalCnt==0 && demoplay_diffs) ||
                                    (g_demo_goalCnt>0 && ud.reccnt/ud.multimode >= g_demo_goalCnt-g_demo_cnt))
                                {
                                    Demo_UpdateState(0);
                                }
                            }
                        }
                        else if (Bmemcmp(tmpbuf, "EnD!", 4)==0)
                            goto nextdemo;
                        else CORRUPT(12);

                        if (0)
                        {
corrupt:
                            OSD_Printf(OSD_ERROR "Demo %d is corrupt (code %d).\n", g_whichDemo-1, corruptcode);
nextdemo:
                            Menu_Open(myconnectindex);
nextdemo_nomenu:
                            foundemo = 0;
                            ud.reccnt = 0;
                            kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;

                            if (g_demo_goalCnt>0)
                            {
                                g_demo_goalCnt=0;
                                ud.config.SoundToggle = g_demo_soundToggle;
                            }

                            if (Demo_IsProfiling())  // don't reset g_demo_profile if it's < 0
                                Demo_FinishProfile();
                            goto RECHECK;
                        }
                    }

                    if (demo_hasseeds)
                        outofsync = ((uint8_t)(randomseed>>24) != g_demo_seedbuf[bigi]);
                }

                for (TRAVERSE_CONNECT(j))
                {
                    Bmemcpy(&inputfifo[movefifoplc&(MOVEFIFOSIZ-1)][j], &recsync[bigi], sizeof(input_t));
                    bigi++;
                    ud.reccnt--;
                }

                g_demo_cnt++;

                S_Update();

                if (Demo_IsProfiling())
                {
                    double t = timerGetFractionalTicks();
                    G_DoMoveThings();
                    Demo_GToc(t);
                }
                else if (!g_demo_paused)
                {
                    // assumption that ud.multimode doesn't change in a demo may not be true
                    // sometime in the future                    v v v v v v v v v
                    if (g_demo_goalCnt==0 || !demo_hasdiffs || ud.reccnt/ud.multimode>=g_demo_goalCnt-g_demo_cnt)
                    {
                        G_DoMoveThings();  // increases lockclock by TICSPERFRAME
                    }
                    else
                    {
                        lockclock += TICSPERFRAME;
                    }
                }
                else
                {
                    int32_t k = ud.config.SoundToggle;
                    ud.config.SoundToggle = 0;
                    G_DoMoveThings();
                    ud.config.SoundToggle = k;
                }

                ototalclock += TICSPERFRAME;

                if (g_demo_goalCnt > 0)
                {
                    // if fast-forwarding, we must update totalclock
                    totalclock += TICSPERFRAME;

//                    OSD_Printf("t:%d, l+T:%d; cnt:%d, goal:%d%s", totalclock, (lockclock+TICSPERFRAME),
//                               g_demo_cnt, g_demo_goalCnt, g_demo_cnt>=g_demo_goalCnt?" ":"\n");
                    if (g_demo_cnt>=g_demo_goalCnt)
                    {
                        g_demo_goalCnt = 0;
                        ud.config.SoundToggle = g_demo_soundToggle;
                    }
                }
            }
        }
        else if (foundemo && g_demo_paused)
        {
            totalclock = lockclock;
        }

        if (Demo_IsProfiling())
            totalclock += TICSPERFRAME;

        if (engineFPSLimit())
        {
            if (foundemo == 0)
            {
                G_DrawBackground();
            }
            else
            {
                // NOTE: currently, no key/mouse events will be seen while
                // demo-profiling because we need 'totalclock' for ourselves.
                // And handleevents() -> sampletimer() would mess that up.
                G_HandleLocalKeys();

                // Render one frame (potentially many if profiling)
                if (Demo_IsProfiling())
                {
                    int32_t i, num = g_demo_profile-1;

                    Bassert(totalclock-ototalclock==4);

                    for (i=0; i<num; i++)
                    {
                        double t1 = timerGetFractionalTicks(), t2;

                        //                    initprintf("t=%d, o=%d, t-o = %d\n", totalclock,
                        //                               ototalclock, totalclock-ototalclock);

                                            // NOTE: G_DrawRooms() calculates smoothratio inside and
                                            // ignores the function argument, so we set totalclock
                                            // accordingly.
                        j = (i<<16)/num;
                        totalclock = ototalclock + (j>>16);

                        G_DrawRooms(screenpeek, j);

                        t2 = timerGetFractionalTicks();

                        G_DisplayRest(j);

                        Demo_RToc(t1, t2);
                    }

                    totalclock = ototalclock+4;

                    // draw status
                    Demo_DisplayProfStatus();

                    if (handleevents_peekkeys())
                        Demo_StopProfiling();
                }
                else
                {
                    j = calc_smoothratio_demo(totalclock, ototalclock);
                    if (g_demo_paused && g_demo_rewind)
                        j = 65536-j;

                    G_DrawRooms(screenpeek, j);
                    G_DisplayRest(j);

                }
//                    totalclocklock = totalclock;

                if (!Demo_IsProfiling() && (g_player[myconnectindex].ps->gm&MODE_MENU) == 0)
                {
                    if (demoplay_showsync && outofsync)
                        gametext_center(100, "OUT OF SYNC");

                    if (g_demo_showStats)
                    {
    #if 0
                        if (g_demo_cnt<tmpdifftime)
                            gametext_center(100, "DIFF");

                        {
                            char buf[32];
                            Bsprintf(buf, "RC:%4d  TC:%5d", ud.reccnt, g_demo_cnt);
                            gametext_center_number(100, buf);
                        }
    #endif
                        j=g_demo_cnt/REALGAMETICSPERSEC;
                        Bsprintf(buf, "%02d:%02d", j/60, j%60);
                        gametext_widenumber(18, 16, buf);

                        rotatesprite(60<<16, 16<<16, 32768, 0, SLIDEBAR, 0, 0, 2+8+16+1024, 0, 0, (xdim*95)/320, ydim-1);
                        rotatesprite(90<<16, 16<<16, 32768, 0, SLIDEBAR, 0, 0, 2+8+16+1024, (xdim*95)/320, 0, (xdim*125)/320, ydim-1);
                        rotatesprite(120<<16, 16<<16, 32768, 0, SLIDEBAR, 0, 0, 2+8+16+1024, (xdim*125)/320, 0, (xdim*155)/320, ydim-1);
                        rotatesprite(150<<16, 16<<16, 32768, 0, SLIDEBAR, 0, 0, 2+8+16+1024, (xdim*155)/320, 0, xdim-1, ydim-1);

                        j = (182<<16) - (tabledivide32_noinline((120*(g_demo_totalCnt-g_demo_cnt))<<4, g_demo_totalCnt)<<12);
                        if (RR)
                            rotatesprite_fs(j, (15<<16)+(1<<15), 16384, 0, BIGALPHANUM-9, 0, 0, 2+8+16+1024);
                        else
                            rotatesprite_fs(j, (16<<16)+(1<<15), 32768, 0, SLIDEBAR+1, 0, 0, 2+8+16+1024);

                        j=(g_demo_totalCnt-g_demo_cnt)/REALGAMETICSPERSEC;
                        Bsprintf(buf, "-%02d:%02d%s", j/60, j%60, g_demo_paused ? "   ^15PAUSED" : "");
                        gametext_widenumber(194, 16, buf);
                    }
                }

                if ((g_netServer || ud.multimode > 1) && g_player[myconnectindex].ps->gm)
                    Net_GetPackets();

                if (g_player[myconnectindex].gotvote == 0 && voting != -1 && voting != myconnectindex)
                    gametext_center(60, "Press F1 to Accept, F2 to Decline");
            }

            if ((g_player[myconnectindex].ps->gm&MODE_MENU) && (g_player[myconnectindex].ps->gm&MODE_EOL))
            {
                Demo_FinishProfile();
                videoNextPage();
                goto RECHECK;
            }

            if (I_EscapeTrigger() && (g_player[myconnectindex].ps->gm&MODE_MENU) == 0 && (g_player[myconnectindex].ps->gm&MODE_TYPE) == 0)
            {
                I_EscapeTriggerClear();
                FX_StopAllSounds();
                S_ClearSoundLocks();
                Menu_Open(myconnectindex);
                Menu_Change(MENU_MAIN);
                S_MenuSound();
            }

            if (Demo_IsProfiling())
            {
                // Do nothing: sampletimer() is reached from M_DisplayMenus() ->
                // Net_GetPackets() else.
            }
            else if (g_player[myconnectindex].ps->gm&MODE_TYPE)
            {
                Net_SendMessage();

                if ((g_player[myconnectindex].ps->gm&MODE_TYPE) != MODE_TYPE)
                {
                    g_player[myconnectindex].ps->gm = 0;
                    Menu_Open(myconnectindex);
                }
            }
            else
            {
                if (ud.recstat != 2)
                    M_DisplayMenus();

                if ((g_netServer || ud.multimode > 1)  && !Menu_IsTextInput(m_currentMenu))
                {
                    ControlInfo noshareinfo;
                    CONTROL_GetInput(&noshareinfo);
                    if (BUTTON(gamefunc_SendMessage))
                    {
                        KB_FlushKeyboardQueue();
                        CONTROL_ClearButton(gamefunc_SendMessage);
                        g_player[myconnectindex].ps->gm = MODE_TYPE;
                        typebuf[0] = 0;
                    }
                }
            }

            if (!Demo_IsProfiling())
                G_PrintGameQuotes(screenpeek);

            if (ud.last_camsprite != ud.camerasprite)
                ud.last_camsprite = ud.camerasprite;

            if (VOLUMEONE)
            {
                if (ud.show_help == 0 && (g_player[myconnectindex].ps->gm&MODE_MENU) == 0)
                    rotatesprite_fs((320-50)<<16, 9<<16, 65536L, 0, BETAVERSION, 0, 0, 2+8+16+128);
            }
            videoNextPage();
        }

        // NOTE: We must prevent handleevents() and Net_GetPackets() from
        // updating totalclock when profiling (both via sampletimer()):
        if (!Demo_IsProfiling())
            G_HandleAsync();

        if (g_player[myconnectindex].ps->gm == MODE_GAME)
        {
            // user wants to play a game, quit showing demo!

            if (foundemo)
            {
#if KRANDDEBUG
                krd_print("krandplay.log");
#endif
                kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;
            }

            return 0;
        }
    }

    ud.multimode = numplayers;  // fixes 2 infinite loops after watching demo
    kclose(g_demo_recFilePtr); g_demo_recFilePtr = -1;

    Demo_FinishProfile();

    // if we're in the menu, try next demo immediately
    if (g_player[myconnectindex].ps->gm&MODE_MENU)
        goto RECHECK;

#if KRANDDEBUG
    if (foundemo)
        krd_print("krandplay.log");
#endif

    // finished playing a demo and not in menu:
    // return so that e.g. the title can be shown
    return 1;
}


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.
*/
//-------------------------------------------------------------------------

#ifndef demo_h_
#define demo_h_

#include "compat.h"

#define DEMOFN_FMT "edemo%03d.edm"
#define LDEMOFN_FMT "demo%d.dmo"
#define MAXDEMOS 1000

extern FILE *g_demo_filePtr;
extern char g_firstDemoFile[BMAX_PATH];

extern int32_t demoplay_diffs;
extern int32_t demoplay_showsync;
extern int32_t demorec_diffcompress_cvar;
extern int32_t demorec_diffs_cvar;
extern int32_t demorec_difftics_cvar;
extern int32_t demorec_force_cvar;
extern int32_t demorec_seeds_cvar;
extern int32_t demorec_synccompress_cvar;
extern int32_t g_demo_cnt;
extern int32_t g_demo_goalCnt;
extern int32_t g_demo_paused;
extern int32_t g_demo_recFilePtr;
extern int32_t g_demo_rewind;
extern int32_t g_demo_showStats;
extern int32_t g_demo_totalCnt;

int32_t G_PlaybackDemo(void);
void Demo_PrepareWarp(void);
void G_CloseDemoWrite(void);
void G_DemoRecord(void);
void G_OpenDemoWrite(void);

void Demo_PlayFirst(int32_t prof, int32_t exitafter);
void Demo_SetFirst(const char *demostr);

int32_t Demo_IsProfiling(void);

#if KRANDDEBUG
int32_t krd_print(const char *filename);
void krd_enable(int32_t which);
#endif

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2016 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.
*/
//-------------------------------------------------------------------------

#ifndef duke3d_h_
#define duke3d_h_

// JBF
#include "a.h"
#include "baselayer.h"
#include "build.h"
#include "cache1d.h"
#include "compat.h"
#include "fx_man.h"
#include "keyboard.h"
#include "pragmas.h"

#ifdef POLYMER
    #include "polymer.h"
#else
#ifdef USE_OPENGL
    #include "polymost.h"
#endif
#endif

#define HEAD2                   APPNAME

#define VOLUMEALL           (g_Shareware == 0)
#define PLUTOPAK            (g_scriptVersion >= 14)
#define VOLUMEONE           (g_Shareware == 1)

// increase by 3, because atomic GRP adds 1, and Shareware adds 2
// Non-Lua build
# define BYTEVERSION_EDUKE32      342

//#define BYTEVERSION_13      27
//#define BYTEVERSION_14      116
//#define BYTEVERSION_15      117
#define BYTEVERSION         (BYTEVERSION_EDUKE32+(PLUTOPAK?1:(VOLUMEONE<<1)))

#define NUMPAGES            1

#define RECSYNCBUFSIZ       2520   //2520 is the (LCM of 1-8)*3
#define MOVEFIFOSIZ         256

// KEEPINSYNC lunatic/con_lang.lua
#define MAXVOLUMES          7
#define MAXLEVELS           64
#define MAXGAMETYPES        16

enum {
    MUS_FIRST_SPECIAL = MAXVOLUMES*MAXLEVELS,

    MUS_INTRO = MUS_FIRST_SPECIAL,
    MUS_BRIEFING = MUS_FIRST_SPECIAL + 1,
    MUS_LOADING = MUS_FIRST_SPECIAL + 2,
};

////////// TIMING CONSTANTS //////////
// The number of 'totalclock' increments per second:
#define TICRATE             120
// The number of game state updates per second:
#define REALGAMETICSPERSEC  30
// The number of 'totalclock' increments per game state update:
// NOTE: calling a game state update a 'frame' is really weird.
// (This used to be TICRATE/GAMETICSPERSEC, which was 120/26 = 4.615~ truncated
// to 4 by integer division.)
#define TICSPERFRAME        (TICRATE/REALGAMETICSPERSEC)
// Used as a constant to satisfy all of the calculations written with ticrate =
// 26 in mind:
#define GAMETICSPERSEC      26

#define PACKBUF_SIZE        32768

#define TILE_SAVESHOT       (MAXTILES-1)
#define TILE_LOADSHOT       (MAXTILES-3)
#define TILE_TILT           (MAXTILES-2)
#define TILE_ANIM           (MAXTILES-4)
#define TILE_VIEWSCR        (MAXTILES-5)
// Reserved: TILE_VIEWSCR_1 (MAXTILES-6)
// Reserved: TILE_VIEWSCR_2 (MAXTILES-7)
EDUKE32_STATIC_ASSERT(7 <= MAXTILES-MAXUSERTILES);

// sprites with these statnums should be considered for fixing
#define ROTFIXSPR_STATNUMP(k) ((k)==STAT_DEFAULT || (k)==STAT_STANDABLE || (k)==STAT_FX || \
                            (k)==STAT_FALLER || (k)==STAT_LIGHT)
#define ROTFIXSPR_MAGIC 0x18190000

// JBF 20040604: sync is a function on some platforms
#define sync                dsync

// Uncomment the following to remove calls to a.nasm functions with the GL renderers
// so that debugging with valgrind --smc-check=none is possible:
//#define DEBUG_VALGRIND_NO_SMC

#include "n64/reality.h"
#include "_rts.h"
#include "actors.h"
#include "common_game.h"
#include "config.h"
#include "control.h"
#include "function.h"
#include "game.h"
#include "gamedef.h"
#include "gamedefs.h"
#include "gameexec.h"
#include "gamevars.h"
#include "global.h"
#include "inv.h"
#include "macros.h"
#include "music.h"
#include "namesdyn.h"
#include "net.h"
#include "player.h"
#include "quotes.h"
#include "rts.h"
#include "screentext.h"
#include "sector.h"
#include "sounds.h"
#include "soundsdyn.h"
#include "rrdh.h"

static inline int32_t G_HaveActor(int spriteNum)
{
    return g_tile[spriteNum].execPtr!=NULL;
}

static inline int32_t G_DefaultActorHealth(int spriteNum)
{
    return G_HaveActor(spriteNum) ? g_tile[spriteNum].execPtr[0] : 0;
}

#endif


code:
#ifndef EDUKE32_EVENTS_DEFS_H_
#define EDUKE32_EVENTS_DEFS_H_

// the order of these can't be changed or else compatibility with EDuke 2.0 mods will break
// KEEPINSYNC with EventNames[] and lunatic/con_lang.lua
enum GameEvent_t {
    EVENT_INIT,  // 0
    EVENT_ENTERLEVEL,
    EVENT_RESETWEAPONS,
    EVENT_RESETINVENTORY,
    EVENT_HOLSTER,
    EVENT_LOOKLEFT,  // 5
    EVENT_LOOKRIGHT,
    EVENT_SOARUP,
    EVENT_SOARDOWN,
    EVENT_CROUCH,
    EVENT_JUMP,  // 10
    EVENT_RETURNTOCENTER,
    EVENT_LOOKUP,
    EVENT_LOOKDOWN,
    EVENT_AIMUP,
    EVENT_FIRE,  // 15
    EVENT_CHANGEWEAPON,
    EVENT_GETSHOTRANGE,
    EVENT_GETAUTOAIMANGLE,
    EVENT_GETLOADTILE,
    EVENT_CHEATGETSTEROIDS,  // 20
    EVENT_CHEATGETHEAT,
    EVENT_CHEATGETBOOT,
    EVENT_CHEATGETSHIELD,
    EVENT_CHEATGETSCUBA,
    EVENT_CHEATGETHOLODUKE,  // 25
    EVENT_CHEATGETJETPACK,
    EVENT_CHEATGETFIRSTAID,
    EVENT_QUICKKICK,
    EVENT_INVENTORY,
    EVENT_USENIGHTVISION,  // 30
    EVENT_USESTEROIDS,
    EVENT_INVENTORYLEFT,
    EVENT_INVENTORYRIGHT,
    EVENT_HOLODUKEON,
    EVENT_HOLODUKEOFF,  // 35
    EVENT_USEMEDKIT,
    EVENT_USEJETPACK,
    EVENT_TURNAROUND,
    MAXEVENTS,
    EVENT_AIMDOWN = 14,
};

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2020 EDuke32 developers and contributors
Copyright (C) 2020 sirlemonhead
This file is part of Rednukem.
Rednukem 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 "filestream.h"
#include <stdlib.h>

namespace RedNukem {

bool FileStream::Open(const char *fileName)
{
    file = kopen4loadfrommod(fileName, 0);
    if (file == -1)
    {
        // log error
        return false;
    }

    return true;
}

bool FileStream::Is_Open()
{
    return file != -1;
}

void FileStream::Close()
{
    kclose(file);
    file = -1;
}

int32_t FileStream::ReadBytes(uint8_t *data, uint32_t nBytes)
{
    uint32_t nCount = (uint32_t)kread(file, data, static_cast<int32_t>(nBytes));

    if (nCount != nBytes) {
        return 0;
    }

    return (int32_t)nCount;
}

uint64_t FileStream::ReadUint64LE()
{
    uint64_t value;
    kread(file, &value, 8);
    return B_LITTLE64(value);
}

uint64_t FileStream::ReadUint64BE()
{
    uint64_t value;
    kread(file, &value, 8);
    return B_BIG64(value);
}

uint32_t FileStream::ReadUint32LE()
{
    uint32_t value;
    kread(file, &value, 4);
    return B_LITTLE32(value);
}

uint32_t FileStream::ReadUint32BE()
{
    uint32_t value;
    kread(file, &value, 4);
    return B_BIG32(value);
}

uint16_t FileStream::ReadUint16LE()
{
    uint16_t value;
    kread(file, &value, 2);
    return B_LITTLE16(value);
}

uint16_t FileStream::ReadUint16BE()
{
    uint16_t value;
    kread(file, &value, 2);
    return B_BIG16(value);
}

uint8_t FileStream::ReadByte()
{
    uint8_t value;
    kread(file, &value, 1);
    return value;
}

int32_t FileStream::Seek(int32_t offset, SeekDirection direction)
{
    int32_t nStatus = -1;
    if (kSeekStart == direction)
    {
        nStatus = klseek(file, offset, SEEK_SET);
    }
    else if (kSeekCurrent == direction)
    {
        nStatus = klseek(file, offset, SEEK_CUR);
    }
    else if (kSeekEnd == direction)
    {
        nStatus = klseek(file, offset, SEEK_END);
    }

    return nStatus;
}

int32_t FileStream::Skip(int32_t offset)
{
    return Seek(offset, kSeekCurrent);
}

int32_t FileStream::GetPosition()
{
    return ktell(file);
}

} // close namespace RedNukem


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2020 EDuke32 developers and contributors
Copyright (C) 2020 sirlemonhead
This file is part of Rednukem.
Rednukem 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 _RedNukemFileStream_h_
#define _RedNukemFileStream_h_

#include "vfs.h"
#include "compat.h"
#include <stdint.h>

namespace RedNukem {

class FileStream
{
    public:
        bool Open(const char *fileName);
        bool Is_Open();
        void Close();

        int32_t ReadBytes(uint8_t *data, uint32_t nBytes);

        uint64_t ReadUint64LE();
        uint64_t ReadUint64BE();

        uint32_t ReadUint32LE();
        uint32_t ReadUint32BE();

        uint16_t ReadUint16LE();
        uint16_t ReadUint16BE();

        uint8_t ReadByte();

        enum SeekDirection {
            kSeekCurrent = 0,
            kSeekStart   = 1,
            kSeekEnd     = 2
        };

        int32_t Seek(int32_t offset, SeekDirection = kSeekStart);
        int32_t Skip(int32_t offset);

        int32_t GetPosition();

    private:
        buildvfs_kfd file;
};

} // close namespace RedNukem

#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.
*/
//-------------------------------------------------------------------------

// function.h

// file created by makehead.exe
// these headers contain default key assignments, as well as
// default button assignments and game function names
// axis defaults are also included

#ifndef function_public_h_
#define function_public_h_
#ifdef __cplusplus
extern "C" {
#endif

#define NUMGAMEFUNCTIONS 63
#define MAXGAMEFUNCLEN 32

extern char gamefunctions[NUMGAMEFUNCTIONS][MAXGAMEFUNCLEN];
extern char keydefaults[NUMGAMEFUNCTIONS*2][MAXGAMEFUNCLEN];
extern char oldkeydefaults[NUMGAMEFUNCTIONS*2][MAXGAMEFUNCLEN];

enum GameFunction_t
   {
   gamefunc_Move_Forward,
   gamefunc_Move_Backward,
   gamefunc_Turn_Left,
   gamefunc_Turn_Right,
   gamefunc_Strafe,
   gamefunc_Fire,
   gamefunc_Open,
   gamefunc_Run,
   gamefunc_AutoRun,
   gamefunc_Jump,
   gamefunc_Crouch,
   gamefunc_Look_Up,
   gamefunc_Look_Down,
   gamefunc_Look_Left,
   gamefunc_Look_Right,
   gamefunc_Strafe_Left,
   gamefunc_Strafe_Right,
   gamefunc_Aim_Up,
   gamefunc_Aim_Down,
   gamefunc_Weapon_1,
   gamefunc_Weapon_2,
   gamefunc_Weapon_3,
   gamefunc_Weapon_4,
   gamefunc_Weapon_5,
   gamefunc_Weapon_6,
   gamefunc_Weapon_7,
   gamefunc_Weapon_8,
   gamefunc_Weapon_9,
   gamefunc_Weapon_10,
   gamefunc_Inventory,
   gamefunc_Inventory_Left,
   gamefunc_Inventory_Right,
   gamefunc_Holo_Duke,
   gamefunc_Jetpack,
   gamefunc_NightVision,
   gamefunc_MedKit,
   gamefunc_TurnAround,
   gamefunc_SendMessage,
   gamefunc_Map,
   gamefunc_Shrink_Screen,
   gamefunc_Enlarge_Screen,
   gamefunc_Center_View,
   gamefunc_Holster_Weapon,
   gamefunc_Show_Opponents_Weapon,
   gamefunc_Map_Follow_Mode,
   gamefunc_See_Coop_View,
   gamefunc_Mouse_Aiming,
   gamefunc_Toggle_Crosshair,
   gamefunc_Steroids,
   gamefunc_Quick_Kick,
   gamefunc_Next_Weapon,
   gamefunc_Previous_Weapon,
   gamefunc_Show_Console,
   gamefunc_Show_DukeMatch_Scores,
   gamefunc_Dpad_Select,
   gamefunc_Dpad_Aiming,
   gamefunc_Alt_Weapon,
   gamefunc_Last_Weapon,
   gamefunc_Quick_Save,
   gamefunc_Quick_Load,
   gamefunc_Alt_Fire,
   gamefunc_Third_Person_View,
   gamefunc_Toggle_Crouch, // TODO: Implement properly for mp
   };
#ifdef __cplusplus
}
#endif
#endif