Files
SRB2Kart-Saturn/src/d_main.c
T
alufolie91 93e595d346 fix up the "new" framelimiter
now uses uh accumulator for the frametime which is checked against the time  at the call of this as the old way could seriously drift apart after a while
the accumulated time may be synced up again automatically if so much time has passed that we missed the frametarget to not carry and time debt over which also handles cap changes by itself
also re added the old framelimiter, will need to add a toggle but still idk if this will be in normal saturn (this may introduce a bit of input lag, hence it disables below a 45 fps cap, since the lower the cap the more lag this can produce, but 45 and up should be very neglible since we do frame interpolation eitherways)
this manages to produce a hella smooth pacing even when the game runs kinda crappy, tested with mangohud and my usual hadal classic replay lukl
2026-11-14 06:46:40 +01:00

2372 lines
58 KiB
C

// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 1998-2000 by DooM Legacy Team.
// Copyright (C) 1999-2018 by Sonic Team Junior.
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file d_main.c
/// \brief SRB2 main program
///
/// SRB2 main program (D_SRB2Main) and game loop (D_SRB2Loop),
/// plus functions to parse command line parameters, configure game
/// parameters, and call the startup functions.
#include "d_netcmd.h"
#if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON)
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifdef __GNUC__
#include <unistd.h> // for getcwd
#endif
#ifdef _WIN32
#include <direct.h>
#include <malloc.h>
#endif
#include <time.h>
#include "doomdef.h"
#include "am_map.h"
#include "console.h"
#include "d_net.h"
#include "f_finale.h"
#include "g_game.h"
#include "g_input.h"
#include "hu_stuff.h"
#include "m_emotes.h"
#include "i_sound.h"
#include "i_system.h"
#include "i_time.h"
#include "i_threads.h"
#include "i_video.h"
#include "hu_stuff.h"
#include "m_argv.h"
#include "m_menu.h"
#include "m_misc.h"
#include "p_setup.h"
#include "p_saveg.h"
#include "r_main.h"
#include "r_local.h"
#include "s_sound.h"
#include "st_stuff.h"
#include "v_video.h"
#include "w_wad.h"
#include "z_zone.h"
#include "d_main.h"
#include "d_netfil.h"
#include "m_cheat.h"
#include "y_inter.h"
#include "p_local.h" // chasecam
#include "m_misc.h" // screenshot functionality
#include "dehacked.h" // Dehacked list test
#include "m_cond.h" // condition initialization
#include "fastcmp.h"
#include "r_fps.h" // Frame interpolation/uncapped
#include "keys.h"
#include "filesrch.h" // pathisdirectory
#include "d_protocol.h"
#include "m_perfstats.h"
#include "k_kart.h"
#include "k_hud.h"
#include "core/memory.h"
#include "lua_script.h"
#include "lua_profile.h"
#include "m_random.h"
/* Manually defined asset hashes for non-CMake builds
* Last updated 2015 / 05 / 03 - SRB2 v2.1.15 - srb2.srb
* Last updated 2018 / 12 / 23 - SRB2 v2.1.22 - patch.dta
* Last updated 2019 / 01 / 18 - Kart v1.0.2 - Main assets
* Last updated 2020 / 08 / 30 - Kart v1.3 - patch.kart
* Last updated 2022 / 08 / 16 - Kart v1.4 - Main assets
* Last updated 2022 / 08 / 19 - Kart v1.5 - gfx.kart
* Last updated 2022 / 11 / 01 - Kart v1.6 - gfx.kart, maps.kart
*/
// Base SRB2 hashes
#define ASSET_HASH_SRB2_SRB "c1b9577687f8a795104aef4600720ea7"
#ifdef USE_PATCH_DTA
#define ASSET_HASH_PATCH_DTA "b04fd9624bfd94dc96dcf4f400f7deb4"
#endif
// SRB2Kart-specific hashes
#define ASSET_HASH_GFX_KART "06f86ee16136eb8a7043b15001797034"
#define ASSET_HASH_TEXTURES_KART "abb53d56aba47c3a8cb0f764da1c8b80"
#define ASSET_HASH_CHARS_KART "e2c428347dde52858a3dacd29fc5b964"
#define ASSET_HASH_MAPS_KART "d051e55141ba736582228c456953cd98"
#ifdef USE_PATCH_KART
#define ASSET_HASH_PATCH_KART "00000000000000000000000000000000"
#endif
#ifdef CMAKECONFIG
#include "config.h"
#else
#include "config.h.in"
#endif
#ifdef HWRENDER
#include "hardware/hw_main.h" // 3D View Rendering
#endif
#ifdef HAVE_DISCORDRPC
#include "discord.h"
#endif
// platform independant focus loss
UINT8 window_notinfocus = false;
static char *startupiwadfiles[MAX_WADFILES];
static size_t startupiwadcount = 0;
static char *startuppwads[MAX_WADFILES];
static size_t startuppwadcount = 0;
// autoloading
static char *autoloadwadfiles[MAX_WADFILES];
static char *autoloadwadfilespost[MAX_WADFILES];
static size_t autoloadwadcount = 0;
static size_t postloadwadcount = 0;
//
boolean devparm = false; // started game with -devparm
boolean singletics = false; // timedemo
boolean lastdraw = false;
boolean intermissionbginit = false;
#ifdef MOTIONBLUR
INT32 postimgparam[MAXSPLITSCREENPLAYERS];
#endif
// These variables are only true if
// whether the respective sound system is disabled
// or they're init'ed, but the player just toggled them
boolean sound_disabled = false;
boolean music_disabled = false;
#ifdef DEBUGFILE
INT32 debugload = 0;
#endif
char savegamename[256] = {};
char srb2home[256] = ".";
char srb2path[256] = ".";
boolean usehome = true;
const char *pandf = "%s" PATHSEP "%s";
static char addonsdir[MAX_WADPATH];
//
// EVENT HANDLING
//
// Events are asynchronous inputs generally generated by the game user.
// Events can be discarded if no responder claims them
// referenced from i_system.c for I_GetKey()
event_t events[MAXEVENTS] = {};
INT32 eventhead = 0, eventtail = 0;
boolean dedicated = false;
boolean loaded_config = false; // true once config.cfg loaded AND executed
//
// D_PostEvent
// Called by the I/O functions when input is detected
//
void D_PostEvent(const event_t *ev)
{
events[eventhead] = *ev;
eventhead = (eventhead+1) & (MAXEVENTS-1);
}
// modifier keys
// Now handled in I_OsPolling
UINT8 shiftdown = 0; // 0x1 left, 0x2 right
UINT8 ctrldown = 0; // 0x1 left, 0x2 right
UINT8 altdown = 0; // 0x1 left, 0x2 right
boolean capslock = 0; // gee i wonder what this does.
//
// D_ProcessEvents
// Send all the events of the given timestamp down the responder chain
//
void D_ProcessEvents(void)
{
event_t *ev;
boolean eaten;
for (; eventtail != eventhead; eventtail = (eventtail+1) & (MAXEVENTS-1))
{
ev = &events[eventtail];
// Screenshots over everything so that they can be taken anywhere.
if (M_ScreenshotResponder(ev))
continue; // ate the event
if (gameaction == ga_nothing && gamestate == GS_TITLESCREEN)
{
if (cht_Responder(ev))
continue;
}
if (demo.savemode == DSM_TITLEENTRY)
{
if (G_DemoTitleResponder(ev))
continue;
}
// Menu input
#ifdef HAVE_THREADS
I_LockMutex(&m_menu_mutex);
#endif
{
eaten = M_Responder(ev);
}
#ifdef HAVE_THREADS
I_UnlockMutex(m_menu_mutex);
#endif
if (eaten)
continue; // menu ate the event
// Demo input:
if (demo.playback)
{
if (M_DemoResponder(ev))
continue; // demo ate the event
}
// console input
#ifdef HAVE_THREADS
I_LockMutex(&con_mutex);
#endif
{
eaten = CON_Responder(ev);
}
#ifdef HAVE_THREADS
I_UnlockMutex(con_mutex);
#endif
if (eaten)
continue; // ate the event
G_Responder(ev);
}
}
//
// D_Display
// draw current display, possibly wiping it from the previous
//
static void D_Renderview(void)
{
UINT8 i;
if (automapactive)
return;
R_ApplyLevelInterpolators(R_GetTimeFrac(RTF_LEVEL));
for (i = 0; i <= splitscreen; i++)
{
if (!P_MobjWasRemoved(players[displayplayers[i]].mo) || players[displayplayers[i]].playerstate == PST_DEAD)
{
viewssnum = i;
switch (i)
{
case 1:
if (splitscreen > 1)
{
viewwindowx = viewwidth;
viewwindowy = 0;
}
else
{
viewwindowx = 0;
viewwindowy = viewheight;
}
break;
case 2:
viewwindowx = 0;
viewwindowy = viewheight;
break;
case 3:
viewwindowx = viewwidth;
viewwindowy = viewheight;
break;
default: // Initialize for P1
viewwindowy = viewwindowx = 0;
break;
}
#ifdef HWRENDER
if (rendermode == render_opengl)
{
HWR_RenderPlayerView();
}
else if (rendermode == render_soft)
#endif
{
R_RenderPlayerView(&players[displayplayers[i]]);
if (i == 0)
R_ApplyViewMorph();
#ifdef MOTIONBLUR
V_DoPostProcessor(i, postimgparam[i]);
#else
V_DoPostProcessor(i, 0);
#endif
}
}
}
// Draw over the fourth screen so you don't have to stare at a HOM :V
if (splitscreen == 2)
{
// V_DrawPatchFill, but for the fourth screen only
INT32 x, y, pw = SHORT(srb2back->width) * vid.dup, ph = SHORT(srb2back->height) * vid.dup;
for (x = vid.width>>1; x < vid.width; x += pw)
{
for (y = vid.height>>1; y < vid.height; y += ph)
V_DrawScaledPatch(x, y, V_NOSCALESTART, srb2back);
}
}
R_RestoreLevelInterpolators();
}
// wipegamestate can be set to -1 to force a wipe on the next draw
// added comment : there is a wipe eatch change of the gamestate
gamestate_t wipegamestate = GS_LEVEL;
static void D_LimitFps(void);
static void D_MakeIntermissionBG(void)
{
if (!lastdraw)
return;
if (rendermode == render_none)
{
lastdraw = false;
intermissionbginit = false;
return;
}
#ifdef HWRENDER
if (rendermode == render_opengl)
{
HWR_MakeScreenTexture();
}
else
#endif
{
VID_BlitLinearScreen(vid.screens[0], vid.screens[1], vid.width, vid.height, vid.width, vid.width);
}
lastdraw = false;
intermissionbginit = true;
}
static boolean D_Display(void)
{
boolean ranwipe = false;
boolean forcerefresh = false;
static boolean wipe = false;
INT32 wipedefindex = 0;
if (!dedicated)
{
if (nodrawers)
return false; // for comparative timing/profiling
// check for change of screen size (video mode)
if (setmodeneeded && !wipe)
SCR_SetMode(); // change video mode
if (vid.recalc)
SCR_Recalc(); // NOTE! setsizeneeded is set by SCR_Recalc()
if (rendermode == render_soft && !splitscreen)
{
R_InterpolateViewRollAngle(R_GetTimeFrac(RTF_CAMERA));
R_CheckViewMorph();
}
// change the view size if needed
if (setsizeneeded)
{
R_ExecuteSetViewSize();
forcerefresh = true; // force background redraw
}
}
// save the current screen if about to wipe
wipe = (gamestate != wipegamestate);
if (wipe)
{
// set for all later
wipedefindex = gamestate; // wipe_xxx_toblack
if (gamestate == GS_TITLESCREEN && wipegamestate != GS_INTRO)
wipedefindex = wipe_timeattack_toblack;
else if (gamestate == GS_INTERMISSION)
{
if (intertype == int_spec) // Special Stage
wipedefindex = wipe_specinter_toblack;
else //if (intertype != int_coop) // Multiplayer
wipedefindex = wipe_multinter_toblack;
}
if (!dedicated)
{
if (gamestate != GS_LEVEL)
{
// Fade to black first
if (wipedefs[wipedefindex] != UINT8_MAX) // fades to black on its own timing, always
{
F_WipeStartScreen();
V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31);
F_WipeEndScreen();
F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
ranwipe = true;
}
if (rendermode != render_none)
{
V_SetPaletteLump("PLAYPAL"); // Reset the palette
R_ReInitColormaps(0, LUMPERROR);
}
}
F_WipeStartScreen();
}
else // dedicated servers
{
F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
ranwipe = true;
wipegamestate = gamestate;
}
}
if (dedicated) // bail out after wipe logic
return false;
// do buffered drawing
switch (gamestate)
{
case GS_LEVEL:
if (!gametic)
break;
AM_Drawer();
break;
case GS_INTERMISSION:
Y_IntermissionDrawer();
HU_Drawer();
break;
case GS_VOTING:
Y_VoteDrawer();
HU_Drawer();
break;
case GS_INTRO:
F_IntroDrawer();
if (wipegamestate == (gamestate_t)-1)
{
wipe = true;
wipedefindex = gamestate; // wipe_xxx_toblack
}
break;
case GS_CUTSCENE:
F_CutsceneDrawer();
HU_Drawer();
break;
case GS_GAMEEND:
F_GameEndDrawer();
break;
case GS_EVALUATION:
F_GameEvaluationDrawer();
HU_Drawer();
break;
case GS_CONTINUING:
F_ContinueDrawer();
break;
case GS_CREDITS:
F_CreditDrawer();
HU_Drawer();
break;
case GS_TITLESCREEN:
F_TitleScreenDrawer();
if (wipe)
wipedefindex = wipe_titlescreen_toblack;
HU_DrawSongCredits();
break;
case GS_WAITINGPLAYERS:
// The clientconnect drawer is independent...
if (netgame)
{
// I don't think HOM from nothing drawing is independent...
F_WaitingPlayersDrawer();
HU_Drawer();
}
case GS_TIMEATTACK:
case GS_DEDICATEDSERVER:
case GS_NULL:
break;
}
if (gamestate == GS_LEVEL)
{
// draw the view directly
if (cv_renderview.value)
{
PS_START_TIMING(ps_rendercalltime);
D_Renderview();
PS_STOP_TIMING(ps_rendercalltime);
D_MakeIntermissionBG();
}
PS_START_TIMING(ps_uitime);
ST_Drawer();
HU_Drawer();
}
else
{
PS_START_TIMING(ps_uitime);
}
// change gamma if needed
// (GS_LEVEL handles this already due to level-specific palettes)
if (forcerefresh && gamestate != GS_LEVEL)
V_SetPalette(0);
wipegamestate = gamestate;
// draw pause pic
if (paused && cv_showhud.value && !demo.playback)
{
INT32 py = (automapactive) ? 4 : (viewwindowy + 4);
patch_t *patch = W_CachePatchName("M_PAUSE", PU_PATCH);
V_DrawScaledPatch(viewwindowx + (BASEVIDWIDTH - patch->width)/2, py, V_SNAPTOTOP, patch);
}
if (rendermode == render_soft && demo.rewinding)
V_DrawFadeScreen(TC_RAINBOW, (leveltime & 0x20) ? SKINCOLOR_PASTEL : SKINCOLOR_MOONSLAM);
// vid size change is now finished if it was on...
vid.recalc = false;
#ifdef HAVE_THREADS
I_LockMutex(&m_menu_mutex);
#endif
M_Drawer(); // menu is drawn even on top of everything...
#ifdef HAVE_THREADS
I_UnlockMutex(m_menu_mutex);
#endif
// focus lost moved to M_Drawer
PS_STOP_TIMING(ps_uitime);
//
// wipe update
//
if (wipe)
{
// note: moved up here because NetUpdate does input changes
// and input during wipe tends to mess things up
wipedefindex += WIPEFINALSHIFT;
if (rendermode != render_none)
{
F_WipeEndScreen();
F_RunWipe(wipedefs[wipedefindex], gamestate != GS_TIMEATTACK);
ranwipe = true;
}
}
NetUpdate(); // send out any new accumulation
// It's safe to end the game now.
if (G_GetExitGameFlag())
{
Command_ExitGame_f();
G_ClearExitGameFlag();
}
//
// normal update
//
if (!wipe)
{
if (cv_netstat.value)
{
char s[50];
Net_GetNetStat();
s[sizeof s - 1] = '\0';
snprintf(s, sizeof s - 1, "get %d b/s", getbps);
V_DrawRightAlignedString(BASEVIDWIDTH, BASEVIDHEIGHT-ST_HEIGHT-40, V_YELLOWMAP, s);
snprintf(s, sizeof s - 1, "send %d b/s", sendbps);
V_DrawRightAlignedString(BASEVIDWIDTH, BASEVIDHEIGHT-ST_HEIGHT-30, V_YELLOWMAP, s);
snprintf(s, sizeof s - 1, "GameMiss %.2f%%", gamelostpercent);
V_DrawRightAlignedString(BASEVIDWIDTH, BASEVIDHEIGHT-ST_HEIGHT-20, V_YELLOWMAP, s);
snprintf(s, sizeof s - 1, "SysMiss %.2f%%", lostpercent);
V_DrawRightAlignedString(BASEVIDWIDTH, BASEVIDHEIGHT-ST_HEIGHT-10, V_YELLOWMAP, s);
}
if (cv_shittyscreen.value)
V_DrawVhsEffect(cv_shittyscreen.value == 2);
if (cv_perfstats.value)
{
M_DrawPerfStats();
}
CON_Drawer(); // Ha, i LIED!
// be sure to limit our fps *before* drawing
// so we can properly "pace" our frames
D_LimitFps();
if (cv_lua_profile.value > 0)
{
LUA_RenderTimers();
}
PS_START_TIMING(ps_swaptime);
I_FinishUpdate(); // page flip or blit buffer
PS_STOP_TIMING(ps_swaptime);
}
return ranwipe;
}
//TODO: this is absolutely fucking horrific
//TODO: pass a mobj to it so we dont have to do this terrible thing
// maybe someday.................
/*static void DoFunnyDance (void)
{
thinker_t *th;
static tic_t time = 0;
fixed_t bounce = 0;
fixed_t work, bpm = FLOAT_TO_FIXED(150.f); // FLOAT_TO_FIXED(mapmusic.bpm) << maybe can get the tempo and beat detection lib to work for autodetection
angle_t ang;
if (gamestate != GS_LEVEL)
return;
// dumb hack, preferrably would use beat detection so it starts ON the first beat
// since some songs have weird intros or begin slightly offbeat
if (S_MapMusPlaying())
{
bpm = FixedDiv((60*TICRATE)<<FRACBITS, bpm);
work = time<<FRACBITS;
work %= bpm;
if (time >= (FRACUNIT>>1)) // prevent overflow jump - takes about 15 minutes of loop on the same song to reach
time = (work>>FRACBITS);
work = FixedDiv(work*180, bpm);
ang = (FixedAngle(work)>>ANGLETOFINESHIFT) & FINEMASK;
bounce = (FINESINE(ang) - FRACUNIT/2);
for (th = thinkercap.next; th != &thinkercap; th = th->next)
{
mobj_t *mo;
if (th->function != (actionf_p1)P_MobjThinker) // not a mobj
continue;
mo = (mobj_t *)th;
if (!mo->player)
continue;
// plan is same as above, continue on the next beat of the song to stay in sync
if (paused || P_AutoPause())
{
mo->spritexscale = mo->realxscale;
mo->spriteyscale = mo->realyscale;
continue;
}
mo->spritexscale -= bounce/2;
mo->spriteyscale += bounce/2;
}
time++; // bruh
}
else
time = 0;
}*/
static precise_t sleeptime = 0;
static boolean D_UseNewFramelimiter(void)
{
//if (!cv_newframelimiter.value) return false;
return (rendermode != render_none && !dedicated && (R_GetFramerateCap() >= 45) && R_UsingFrameInterpolation());
}
static void D_LimitFps(void)
{
precise_t curtime, start;
static precise_t lasttime = 0;
// timedemo runs uncapped!
if (singletics)
return;
if (!D_UseNewFramelimiter())
return;
const UINT32 framecap = R_GetFramerateCap();
// uncapped obviously does not need to be... capped...
if (framecap == 0)
return;
// dont need to sleep if we vsync and our framecap is set to refresh rate or higher
if (cv_vidwait.value && (cv_fpscap.value == 0 || framecap > I_GetRefreshRate()))
return;
start = I_GetPreciseTime();
const UINT64 precision = I_GetPrecisePrecision();
// frametarget in precise_t ticks (ex. 60fps = ~16,666,666)
const precise_t frametarget = precision / framecap;
lasttime += frametarget;
// just sync this up if we missed the target
if ((INT64)(start - lasttime) >= 0)
lasttime = start;
while (1)
{
// check the current time against the "time of the old frame"
curtime = I_GetPreciseTime();
// done waiting!
// continue as normal
if ((INT64)(curtime - lasttime) >= 0)
{
// time we spent :chaosleep:ing or doing absolutely nothing
// for frameskip calculations
sleeptime = curtime - start;
return;
}
// if we have more than 1ms to wait
// sleep for a bit to not trash the cpu lul
precise_t remaining = lasttime - curtime;
if (remaining > (precise_t)(precision / 1000))
{
// sleep for 90% of the time we gotta wait for the next frame
// since we dont wanna oversleep :chaosleep:
I_SleepDuration(9 * remaining / 10);
}
}
// the rest we just be waitin until we meet our frametime target
}
// =========================================================================
// D_SRB2Loop
// =========================================================================
tic_t rendergametic = 0;
void D_SRB2Loop(void)
{
tic_t entertic = 0, oldentertics = 0, realtics = 0, rendertimeout = INFTICS;
double deltatics = 0.0;
double deltasecs = 0.0;
UINT64 precision = 0;
boolean interp = false;
boolean doDisplay = false;
int frameskip = 0;
if (dedicated)
server = true;
// Pushing of + parameters is now done back in D_SRB2Main, not here.
I_UpdateTime(cv_timescale.value);
oldentertics = I_GetTime();
// end of loading screen: CONS_Printf() will no more call FinishUpdate()
con_startup = false;
// make sure to do a d_display to init mode _before_ load a level
SCR_SetMode(); // change video mode
SCR_Recalc();
// Check and print which version is executed.
// Use this as the border between setup and the main game loop being entered.
CONS_Printf(
"===========================================================================\n"
" We hope you enjoy this game as\n"
" much as we did making it!\n"
"===========================================================================\n");
// hack to start on a nice clear console screen.
COM_ImmedExecute("cls;version");
if (rendermode == render_soft)
V_DrawFixedPatch(0, 0, FRACUNIT/2, 0, W_CachePatchNum(W_GetNumForName("KARTKREW"), PU_PATCH), NULL);
I_FinishUpdate(); // page flip or blit buffer
precision = I_GetPrecisePrecision();
for (;;)
{
precise_t elapsed;
precise_t enterprecise, finishprecise;
boolean ranwipe = false;
sleeptime = 0;
enterprecise = I_GetPreciseTime();
I_HandleInterrupt();
memset(&g_dc, 0, sizeof(g_dc));
Z_Frame_Reset();
I_UpdateTime(cv_timescale.value);
if (lastwipetic)
{
oldentertics = lastwipetic;
lastwipetic = 0;
}
// get real tics
entertic = I_GetTime();
realtics = entertic - oldentertics;
oldentertics = entertic;
if (demo.playback && gamestate == GS_LEVEL)
{
// Nicer place to put this.
realtics = realtics * cv_playbackspeed.value;
}
#ifdef DEBUGFILE
if (!realtics && debugload)
debugload--;
#endif
interp = !dedicated && R_UsingFrameInterpolation();
doDisplay = false;
renderisnewtic = (realtics > 0 || singletics);
if (renderisnewtic)
{
// don't skip more than 10 frames at a time
// (fadein / fadeout cause massive frame skip!)
if (realtics > 8)
realtics = 1;
// process tics (but maybe not if realtic == 0)
TryRunTics(realtics);
if (lastdraw || singletics || (gametic > rendergametic))
{
rendergametic = gametic;
rendertimeout = entertic + TICRATE/17;
doDisplay = true;
}
else if (rendertimeout < entertic) // in case the server hang or netsplit
{
// Lagless camera! Yay!
if (cv_laglesscam.value && gamestate == GS_LEVEL && netgame)
{
// Evaluate the chase cam once for every local realtic
// This might actually be better suited inside G_Ticker or TryRunTics
for (tic_t chasecamtics = 0; (chasecamtics < realtics); chasecamtics++)
{
P_RunChaseCameras();
}
R_UpdateViewInterpolation();
}
doDisplay = true;
}
}
if (interp)
{
renderdeltatics = DoubleToFixed(deltatics);
// I looked at the possibility of putting in a float drawer for
// perfstats and it's very complicated, so we'll just do this instead...
ps_interp_frac.value.p = (precise_t)((FIXED_TO_FLOAT(g_time.timefrac)) * 1000.0f);
ps_interp_lag.value.p = (precise_t)((deltasecs) * 1000.0);
const boolean lagging = ((deltatics >= 1.0) || hu_stopped);
R_SetTimeFrac(lagging ? FRACUNIT : g_time.timefrac);
}
else
{
renderdeltatics = realtics * FRACUNIT;
R_SetTimeFrac(FRACUNIT);
}
if (interp || doDisplay)
{
if (!frameskip)
{
ranwipe = D_Display();
}
else if (!dedicated)
{
// always update console movement
// otherwise it will takes literal ages to open
CON_MoveConsole();
}
}
// Only take screenshots after drawing.
if (moviemode)
M_SaveFrame();
if (takescreenshot)
M_DoScreenShot();
#ifndef DEDICATED
if (!dedicated && renderisnewtic)
{
G_DeviceLEDTick();
}
#endif
// consoleplayer -> displayplayers (hear sounds from viewpoint)
if (renderisnewtic)
S_UpdateSounds(); // move positional sounds
//LUA_Step();
#ifdef HAVE_DISCORDRPC
if (!dedicated && renderisnewtic)
{
Discord_RunCallbacks();
}
#endif
// Fully completed frame made.
finishprecise = I_GetPreciseTime();
// Use the time without sleep for frameskip calculations:
// post-sleep time is literally being intentionally wasted
elapsed = (finishprecise - enterprecise) - sleeptime;
deltasecs = (double)elapsed / (double)precision;
deltatics = deltasecs * (double)NEWTICRATE;
// If time spent this game loop exceeds a single tic,
// it's probably because of rendering.
//
// Skip rendering the next frame, up to a limit of 3
// frames before a frame is rendered no matter what.
//
// Wipes run an inner loop and artificially increase
// the measured time.
if (cv_frameskip.value)
{
if (!ranwipe && (frameskip < 3) && (deltatics > 1.0))
{
frameskip++;
}
else
{
frameskip = 0;
}
}
else
{
frameskip = 0;
}
// old fps limiter
if (!singletics && !D_UseNewFramelimiter())
{
const UINT32 framecap = R_GetFramerateCap();
const precise_t capbudget = (framecap == 0) ? 0 : (precise_t)((double)precision / (double)framecap + 0.5); // + 0.5 instead of round
// in the case of "match refresh rate" + vsync, don't sleep at all
const boolean vsync_with_match_refresh = cv_vidwait.value && cv_fpscap.value == 0;
if ((elapsed > 0) && (capbudget > elapsed) && !vsync_with_match_refresh)
{
I_SleepDuration(capbudget - elapsed);
}
finishprecise = I_GetPreciseTime();
}
elapsed = finishprecise - enterprecise;
deltasecs = (double)elapsed / (double)precision;
deltatics = deltasecs * (double)NEWTICRATE;
}
}
// =========================================================================
// D_SRB2Main
// =========================================================================
//
// D_ClearState
//
void D_ClearState(void)
{
INT32 i;
demo.title = false;
// okay, stop now
// (otherwise the game still thinks we're playing!)
#ifdef HAVE_CURL
CURLAbortFile();
#endif
SV_StopServer();
SV_ResetServer();
for (i = 0; i < MAXPLAYERS; i++)
CL_ClearPlayer(i);
splitscreen = 0;
// recompute screen size
R_ExecuteSetViewSize();
botingame = false;
botskin = 0;
cv_debug = 0;
emeralds = 0;
// In case someone exits out at the same time they start a time attack run,
// reset modeattacking
modeattacking = ATTACKING_NONE;
// empty some other semi-important state
maptol = 0;
nextmapoverride = 0;
skipstats = 0;
gamemap = 1;
gameaction = ga_nothing;
memset(displayplayers, 0, sizeof(displayplayers));
consoleplayer = 0;
gametype = GT_RACE; // SRB2kart
paused = false;
// clear cmd building stuff
memset(gamekeydown, 0, sizeof(gamekeydown));
memset(joyxmove, 0, sizeof(joyxmove));
memset(joyymove, 0, sizeof(joyymove));
mousex = mousey = 0;
// Reset the palette
if (rendermode != render_none)
V_SetPaletteLump("PLAYPAL");
G_ResetAllDeviceRumbles();
S_StopSounds();
S_ResetKeepAndSpecialMus(); // just in case
//P_FreeLevelState();
G_SetGamestate(GS_NULL);
wipegamestate = GS_NULL;
M_ClearMenus(true);
// map palettes affect this
G_ResetDeviceLED();
}
//
// D_StartTitle
//
void D_StartTitle(void)
{
if (dedicated)
I_Error("D_StartTitle is called on dedicated server");
D_ClearState();
multiplayer = netgame = false; // title menu shouldnt be a netgame or multiplayer lmao
F_StartTitleScreen();
}
//
// D_AddFile
//
static void D_AddFile(const char *file, char **filearray, size_t index)
{
char *newfile;
newfile = malloc(strlen(file) + 1);
if (!newfile)
{
I_Error("No more free memory to AddFile %s",file);
}
strcpy(newfile, file);
filearray[index] = newfile;
}
static void D_CleanFile(char **filearray, size_t count)
{
size_t i;
for (i = 0; i < count; i++)
{
free(filearray[i]);
filearray[i] = NULL;
}
}
// Taken from TSoURDt3rd
// https://github.com/StarManiaKG/The-Story-of-Uncapped-Revengence-Discord-the-3rd/blob/main/src/STAR/star_functions.c
static INT32 D_DetectFileType(const char* filename)
{
if (pathisdirectory(filename) == 1)
return 1;
const size_t len = strlen(filename);
if (fasticmp(&filename[len - 4], ".wad"))
return 2;
else if (fasticmp(&filename[len - 4], ".pk3"))
return 3;
else if (fasticmp(&filename[len - 5], ".kart"))
return 4;
else if (fasticmp(&filename[len - 4], ".lua"))
return 5;
else if (fasticmp(&filename[len - 4], ".soc"))
return 6;
else if (fasticmp(&filename[len - 4], ".cfg"))
return 7;
else if (fasticmp(&filename[len - 4], ".txt"))
return 8;
return 0;
}
// autoload that shit
static void D_AutoloadFile(const char *file, char **filearray, size_t *index)
{
char *newfile;
INT32 fileType = D_DetectFileType(file);
if (*index >= MAX_WADFILES)
{
CONS_Printf("D_AutoloadFile: Failed to add file %s! Too many autoloaded files\n", file);
return;
}
if (!fileType)
{
CONS_Printf("D_AutoloadFile: File %s is unknown or invalid\n", file);
return;
}
if (fileType == 1)
{
CONS_Printf("D_AutoloadFile: File %s is a directory\n", file);
return;
}
if (fileType <= 6)
{
newfile = malloc(strlen(file) + 1);
if (!newfile)
I_Error("D_AutoloadFile: No more free memory to autoload file %s", file);
strcpy(newfile, file);
filearray[*index] = newfile;
(*index)++;
}
else
{
COM_BufAddText(va("exec %s\n", file));
}
}
static char *strremove(char *str, const char *sub)
{
char *p, *q, *r;
if (*sub && (q = r = strstr(str, sub)) != NULL)
{
size_t len = strlen(sub);
while ((r = strstr(p = r + len, sub)) != NULL)
{
while (p < r)
*q++ = *p++;
}
while ((*q++ = *p++) != '\0')
continue;
}
return str;
}
// FIND THEM
static void D_FindAddonsToAutoload(void)
{
FILE *autoloadconfigfile;
const char *autoloadpath;
char *newline;
boolean postload;
char wadsToAutoload[256] = "";
// does it exist tho
autoloadpath = va("%s"PATHSEP"%s", srb2home, AUTOLOADCONFIGFILENAME);
autoloadconfigfile = fopen(autoloadpath, "r");
// If the file is found, run our shit
if (!autoloadconfigfile) // nope outta here
{
autoloadwadcount = postloadwadcount = 0; // so D_AddAutoloadFiles can skip everything since nothings there to autoload
return;
}
while (fgets(wadsToAutoload, sizeof(wadsToAutoload), autoloadconfigfile) != NULL)
{
postload = false;
// skip if commented or empty
if (wadsToAutoload[0] == '\n' ||
wadsToAutoload[0] == '#' ||
wadsToAutoload[0] == '\0')
continue;
// this marks it so that it loads after loading server addons
if (fastncmp(wadsToAutoload, "postload ", 9))
{
strremove(wadsToAutoload, "postload ");
postload = true;
}
// Remove Any Empty or Skipped Lines
newline = strchr(wadsToAutoload, '\n');
if (newline)
*newline = '\0';
// ok so theres still issues with players adding stuff to autoload by accident
// sometimes this stuff contains maps
// you can probably imagine how that goes in a netgame....
int retmap = W_CheckAutoLoadContainsMap(wadsToAutoload);
if (retmap == -1)
{
CONS_Alert(CONS_WARNING, "Autoload: file %s was not found or not valid.\n", wadsToAutoload);
continue;
}
if (retmap > 0)
{
CONS_Alert(CONS_WARNING, "Autoload: file %s contains map data, this WILL cause crashes and desynchs! skipping...\n", wadsToAutoload);
continue;
}
if (!postload && W_CheckPostLoadList(wadsToAutoload) > 0)
{
CONS_Printf("Autoload: forcing postload for file %s\n", wadsToAutoload);
postload = true;
}
// LOAD IT
if (!postload)
{
D_AutoloadFile(wadsToAutoload, autoloadwadfiles, &autoloadwadcount);
}
else
{
D_AutoloadFile(wadsToAutoload, autoloadwadfilespost, &postloadwadcount);
}
}
autoloadwadfiles[autoloadwadcount] = NULL;
autoloadwadfilespost[postloadwadcount] = NULL;
// we dont want memory leaks around here do we?
fclose(autoloadconfigfile);
}
static void D_AddAutoloadFiles(void)
{
// nothing to autoload
if (autoloadwadcount == 0)
return;
CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n");
if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0)
CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n");
D_CleanFile(autoloadwadfiles, autoloadwadcount);
autoloadwadcount = 0;
}
void D_AddPostloadFiles(void)
{
// nothing to postload
if (postloadwadcount == 0 || !netgame)
return;
CONS_Printf("D_AddPostloadFiles(): Loading postloaded addons...\n");
if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0)
CONS_Printf("D_AddPostloadFiles(): Are you sure you put in valid files or what?\n");
D_CleanFile(autoloadwadfilespost, postloadwadcount);
postloadwadcount = 0;
}
// ==========================================================================
// Identify the SRB2 version, and IWAD file to use.
// ==========================================================================
static boolean AddIWAD(const char * file, const char *dir)
{
char *path = va(pandf, dir, file);
if (FIL_ReadFileOK(path))
{
D_AddFile(path, startupiwadfiles, startupiwadcount++);
return true;
}
return false;
}
// Optional saturn extra files
boolean found_extra_kart = false;
boolean found_extra2_kart = false;
boolean found_extra3_kart = false;
static void IdentifyVersion(void)
{
const char *srb2waddir = NULL;
#if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL)
CLEANUP(pfree) const char *allocwaddir = NULL; // here so we dont potentially free stack memory
// change to the directory where 'srb2.srb' is found
allocwaddir = I_LocateWad();
srb2waddir = allocwaddir;
#endif
char tempsrb2path[256] = ".";
if (I_GetCwd(tempsrb2path, 256) == NULL)
strcpy(tempsrb2path, ".");
// get the current directory (possible problem on NT with "." as current dir)
if (!srb2waddir)
{
srb2waddir = tempsrb2path;
}
#if (1) // reduce the amount of findfile by only using full cwd in this func
if (!fastcmp(tempsrb2path, srb2waddir))
#endif
{
strlcpy(srb2path, srb2waddir, sizeof (srb2path));
}
// Load the IWAD
if (!AddIWAD("srb2.srb", srb2path)) // not sure why this uses srb2path and not srb2waddir?
{
I_Error("SRB2.SRB not found! Expected in %s\n", srb2waddir);
}
// will be overwritten in case of -cdrom or unix/win home
snprintf(configfile, sizeof configfile, "%s" PATHSEP CONFIGFILENAME, srb2waddir);
configfile[sizeof configfile - 1] = '\0';
// if you change the ordering of this or add/remove a file, be sure to update the md5
// checking in D_SRB2Main
#ifdef USE_PATCH_DTA
// Add our crappy patches to fix our bugs
if (!AddIWAD("patch.dta", srb2waddir))
{
I_Error("patch.dta not found! Expected in %s\n", srb2waddir);
}
#endif
if (!AddIWAD("gfx.kart", srb2waddir))
{
I_Error("gfx.kart not found! Expected in %s\n", srb2waddir);
}
if (!AddIWAD("textures.kart", srb2waddir))
{
I_Error("textures.kart not found! Expected in %s\n", srb2waddir);
}
if (!AddIWAD("chars.kart", srb2waddir))
{
I_Error("chars.kart not found! Expected in %s\n", srb2waddir);
}
if (!AddIWAD("maps.kart", srb2waddir))
{
I_Error("maps.kart not found! Expected in %s\n", srb2waddir);
}
#ifdef USE_PATCH_KART
if (!AddIWAD("patch.kart", srb2waddir))
{
I_Error("patch.kart not found! Expected in %s\n", srb2waddir);
}
#endif
// completely optional
if (AddIWAD("extra.kart", srb2waddir))
found_extra_kart = true;
// completely optional 2: Back with a vengence
if (AddIWAD("extra2.kart", srb2waddir))
found_extra2_kart = true;
if (AddIWAD("extra3.kart", srb2waddir))
found_extra3_kart = true;
#if !defined (HAVE_SDL) || defined (HAVE_MIXER)
#define MUSICTEST(str) \
musicpath = va(pandf, srb2waddir, str);\
handle = W_OpenWadFile(&musicpath, false); \
if (handle) \
{ \
int ms = W_VerifyNMUSlumps(musicpath, handle, false); \
fclose(handle); \
if (ms == 0) \
I_Error("File " str " has been modified with non-music/sound lumps"); \
if (ms == 1) \
D_AddFile(musicpath, startupiwadfiles, startupiwadcount++); \
}
{
const char *musicpath;
FILE *handle;
MUSICTEST("sounds.kart")
MUSICTEST("music.kart")
}
#undef MUSICTEST
#endif
}
//
// search for maps
//
static void D_CheckMapReplacements(boolean pwad)
{
INT32 i;
char *name;
UINT16 wadnum;
lumpinfo_t *lumpinfo;
size_t numfiles;
wadnum = pwad ? (mainwads+1) : 0;
numfiles = pwad ? numwadfiles : mainwads;
for (; wadnum < numfiles; wadnum++)
{
lumpinfo = wadfiles[wadnum]->lumpinfo;
for (i = 0; i < wadfiles[wadnum]->numlumps; i++, lumpinfo++)
{
name = lumpinfo->name;
P_CheckMapReplacements(name, pwad);
}
}
}
//
// Center the title string, then add the date and time of compilation.
//
static inline void D_MakeTitleString(char *s)
{
char temp[82];
char *t;
const char *u;
INT32 i;
const size_t len = (80-strlen(s))/2;
for (i = 0, t = temp; i < 82; i++)
*t++=' ';
for (t = temp + len, u = s; *u != '\0' ;)
*t++ = *u++;
u = compdate;
for (t = temp + 1, i = 11; i-- ;)
*t++ = *u++;
u = comptime;
for (t = temp + 71, i = 8; i-- ;)
*t++ = *u++;
temp[80] = '\0';
strcpy(s, temp);
}
// extra graphic patches for saturn specific thingies
boolean xtra_speedo = false; // extra speedometer check
boolean xtra_speedo_clr = false; // extra speedometer colour check
boolean achi_speedo = false; // achiiro speedometer check
boolean achi_speedo_clr = false; // extra speedometer colour check
boolean dial_speedo = false; // dial speedometer check
boolean dial_speedo_clr = false; // dial speedometer colour check
boolean kartz_speedo = false; // kartZ speedo
boolean kartz_speedo_smol = false; // kartZ speedo but smol
boolean clr_hud = false; // colour hud check
boolean driftgaugegfx_clr = false; // driftgauge colour check
boolean big_lap = false; // bigger lap counter
boolean big_lap_color = false; // bigger lap counter but colour
boolean statdp = false; // stat display for extended player setup
boolean nametaggfx = false; // Nametag stuffs
boolean driftgaugegfx = false; // Driftgauge stuffs
boolean multiitem_icon = false; // Extra icons for Sneakers, Banana and Jawz
boolean joystickicon = false; // Extra icons for the joystick input display
boolean minidoticon = false; // Dot graphic for minimap player angle display
boolean minilighticon = false; // mkwii-style minimap headlight
//
static void D_CheckSaturnExtraFiles(void)
{
// Possible value that changes depending on whether required files for speedometer are found or not
CV_PossibleValue_t speedo_cons_temp[NUMSPEEDOSTUFF] = {{1, "Default"}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}};
CV_PossibleValue_t driftgaugestyle_cons_temp[NUMDGAUGESTUFF] = {{1, "Default"}, {2, "Small"}, {3, "Big Numbers"}, {4, "Numbers Only"}, {0, NULL}, {0, NULL}};
CV_PossibleValue_t inputdisplay_cons_temp[NUMINPUTDISPLAYSTUFF] = {{0, "Off"}, {1, "Wheel"}, {2, "Stick"}, {0, NULL}, {0, NULL}};
CV_PossibleValue_t minimapdot_cons_temp[NUMMINIMAPDOTSTUFF] = {{0, "Off"}, {0, NULL}, {0, NULL}, {0, NULL}, {0, NULL}};
unsigned last_speedo_i = 0;
unsigned last_inputdisplay_i = 2;
unsigned last_minimapdot_i = 0;
#define PUSHCONS(cons, i, id, name) { ++i; cons[i].value = id; cons[i].strvalue = name; }
// found the funny, add it in!
if (found_extra_kart)
{
mainwads++;
// now check for extra speedometer stuff
if (W_CheckMultipleLumps("SP_SMSTC", "K_TRNULL", "SP_MKMH", "SP_MMPH", "SP_MFRAC", "SP_MPERC", NULL))
{
xtra_speedo = true;
PUSHCONS(speedo_cons_temp, last_speedo_i, 2, "Small");
}
// now check for achii speedometer stuff
if (W_CheckMultipleLumps("SP_AMSTC", "K_TRNULL", "SP_AKMH", "SP_AMPH", "SP_AFRAC", "SP_APERC", NULL))
{
achi_speedo = true;
PUSHCONS(speedo_cons_temp, last_speedo_i, 3, "Achii");
}
// now check for dial speedometer stuff
if (W_CheckMultipleLumps("K_DSPBS1", "K_DSPBS2", "K_DSDIAL",
"K_TRNULL", "SP_DKMH", "SP_DMPH", "SP_DFRAC", "SP_DPERC",
"K_DSPNM0", "K_DSPNM1", "K_DSPNM2", "K_DSPNM3", "K_DSPNM4",
"K_DSPNM5", "K_DSPNM6", "K_DSPNM7", "K_DSPNM8", "K_DSPNM9",
"RANKFIN", NULL))
{
dial_speedo = true;
PUSHCONS(speedo_cons_temp, last_speedo_i, 4, "Dial");
}
// check for bigger lap count
if (W_CheckMultipleLumps("K_STLAPB", "K_STLA2B", NULL))
{
big_lap = true;
}
// kartzspeedo
if (W_CheckMultipleLumps("K_KZSP1", "K_KZSP2", "K_KZSP3", "K_KZSP4", "K_KZSP5",
"K_KZSP6", "K_KZSP7", "K_KZSP8", "K_KZSP9", "K_KZSP10", "K_KZSP11", "K_KZSP12",
"K_KZSP13", "K_KZSP14", "K_KZSP15", "K_KZSP16", "K_KZSP17", "K_KZSP18", "K_KZSP19",
"K_KZSP20", "K_KZSP21", "K_KZSP22", "K_KZSP23", "K_KZSP24", "K_KZSP25", NULL))
{
kartz_speedo = true;
PUSHCONS(speedo_cons_temp, last_speedo_i, 5, "P-Meter");
}
if (W_CheckMultipleLumps("K_KZSS1", "K_KZSS2", "K_KZSS3", "K_KZSS4", "K_KZSS5",
"K_KZSS6", "K_KZSS7", "K_KZSS8", "K_KZSS9", "K_KZSS10", "K_KZSS11", "K_KZSS12",
"K_KZSS13", "K_KZSS14", "K_KZSS15", "K_KZSS16", "K_KZSS17", "K_KZSS18", "K_KZSS19",
"K_KZSS20", "K_KZSS21", "K_KZSS22", "K_KZSS23", "K_KZSS24", "K_KZSS25", NULL))
{
kartz_speedo_smol = true;
PUSHCONS(speedo_cons_temp, last_speedo_i, 6, "P-Meter Small");
}
// stat display for extended player setup
if (W_CheckMultipleLumps("K_STATNB", "K_STATN1", "K_STATN2",
"K_STATN3", "K_STATN4", "K_STATN5", "K_STATN6", NULL))
{
statdp = true;
}
// Nametag stuffs
if (W_CheckMultipleLumps("NTLINE", "NTLINEV", "NTSP", "NTWH", NULL))
{
nametaggfx = true;
}
// driftgauge
if (W_CheckMultipleLumps("K_DGAU","K_DGSU", NULL))
{
driftgaugegfx = true;
}
// extra item icons
if (W_CheckMultipleLumps("K_ITSHO2", "K_ITSHO3", "K_ITBAN2", "K_ITBAN3", "K_ITBAN4", "K_ITJAW2", NULL))
{
multiitem_icon = true;
}
// extra round joystick inputdisplay sprites
if (W_CheckMultipleLumps("JOYBCK", "JOYKNB", "JOYSHD", NULL))
{
joystickicon = true;
PUSHCONS(inputdisplay_cons_temp, last_inputdisplay_i, 3, "StickGFX");
}
// minimap dot
if (W_LumpExists("MMAPDOT"))
{
minidoticon = true;
PUSHCONS(minimapdot_cons_temp, last_minimapdot_i, 1, "Dot");
}
// minimap headlight
if (W_LumpExists("MMAPHDLT"))
{
minilighticon = true;
PUSHCONS(minimapdot_cons_temp, last_minimapdot_i, 2, "Headlight");
}
}
// now check for colour hud stuff
if (found_extra2_kart)
{
mainwads++;
// kart vanilla hud patches but colourizable
if (W_CheckMultipleLumps("K_SCTIME", "K_SCTIMW", "K_SCLAPS", "K_SCLAPW","K_SCBALN", "K_SCBALW",
"K_SCKARM", "K_SCTOUT", "K_ISMULC", "K_ITMULC", "K_ITBC", "K_ITBCD", "K_ISBC", "K_ISBCD", NULL))
{
clr_hud = true;
}
// extra speedo but colour
if (W_LumpExists("SC_SMSTC"))
{
xtra_speedo_clr = true;
}
// achii speedo but colour
if (W_CheckMultipleLumps("SC_AMSTC", "K_TRNULL", "SC_AKMH", "SC_AMPH", "SC_AFRAC", "SC_APERC", NULL))
{
achi_speedo_clr = true;
}
// dial speedo but colour
if (W_CheckMultipleLumps("K_DSPBC1", "K_DSPBC2", "K_DSDIAL",
"K_TRNULL", "SC_DKMH", "SC_DMPH", "SC_DFRAC", "SC_DPERC",
"K_DSPNC0", "K_DSPNC1", "K_DSPNC2", "K_DSPNC3", "K_DSPNC4",
"K_DSPNC5", "K_DSPNC6", "K_DSPNC7", "K_DSPNC8", "K_DSPNC9",
"RANKFIN", NULL))
{
dial_speedo_clr = true;
}
// driftgauge but colour
if (W_CheckMultipleLumps("K_DCAU","K_DCSU", NULL))
{
driftgaugegfx_clr = true;
}
// check for bigger lap count but color** its color bitch
if (W_CheckMultipleLumps("K_SCLAPB", "K_SCLA2B", NULL))
{
big_lap_color = true;
}
}
// can be used for custom hud stuff
// currently used for the v1 beta hud
if (found_extra3_kart)
{
mainwads++;
}
#undef PUSHCONS
memcpy(speedo_cons_t, speedo_cons_temp, sizeof(speedo_cons_t));
memcpy(driftgaugestyle_cons_t, driftgaugestyle_cons_temp, sizeof(driftgaugestyle_cons_t));
memcpy(inputdisplay_cons_t, inputdisplay_cons_temp, sizeof(inputdisplay_cons_t));
memcpy(minimapdot_cons_t, minimapdot_cons_temp, sizeof(minimapdot_cons_t));
}
#include <locale.h>
//
// D_SRB2Main
//
void D_SRB2Main(void)
{
INT32 p;
char srb2[82]; // srb2 title banner
char title[82];
INT32 pstartmap = 1;
boolean autostart = false;
// Print GPL notice for our console users (Linux)
CONS_Printf(
"\n\nSonic Robo Blast 2 Kart\n"
"Copyright (C) 1998-2022 by Kart Krew & STJr\n\n"
"This program comes with ABSOLUTELY NO WARRANTY.\n\n"
"This is free software, and you are welcome to redistribute it\n"
"and/or modify it under the terms of the GNU General Public License\n"
"as published by the Free Software Foundation; either version 2 of\n"
"the License, or (at your option) any later version.\n"
"See the 'LICENSE.txt' file for details.\n\n"
"Sonic the Hedgehog and related characters are trademarks of SEGA.\n"
"We do not claim ownership of SEGA's intellectual property used\n"
"in this program.\n\n");
// keep error messages until the final flush(stderr)
#if !defined(NOTERMIOS)
if (setvbuf(stderr, NULL, _IOFBF, 1000))
I_OutputMsg("setvbuf didnt work\n");
#endif
// get parameters from a response file (eg: srb2 @parms.txt)
M_FindResponseFile();
// MAINCFG is now taken care of where "OBJCTCFG" is handled
G_LoadGameSettings();
// Test Dehacked lists
DEH_Check();
// identify the main IWAD file to use
IdentifyVersion();
#if !defined(NOTERMIOS)
setbuf(stdout, NULL); // non-buffered output
#endif
#if 0 //defined (_DEBUG)
devparm = M_CheckParm("-nodebug") == 0;
#else
devparm = M_CheckParm("-debug") != 0;
#endif
// for dedicated server
#if !defined (DEDICATED)
dedicated = M_CheckParm("-dedicated") != 0;
#endif
strcpy(title, "SRB2Kart");
strcpy(srb2, "SRB2Kart");
D_MakeTitleString(srb2);
if (devparm)
CONS_Printf(M_GetText("Development mode ON.\n"));
// default savegame
strcpy(savegamename, SAVEGAMENAME"%u.ssg");
{
const char *userhome = D_Home(); //Alam: path to home
FILE *tmpfile;
char testfile[MAX_WADPATH];
if (!userhome)
{
#if (defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON)) && !defined (__CYGWIN__)
I_Error("Please set $HOME to your home directory\n");
#else
if (dedicated)
snprintf(configfile, sizeof configfile, "d"CONFIGFILENAME);
else
snprintf(configfile, sizeof configfile, CONFIGFILENAME);
#endif
}
else
{
// use user specific config file
if (M_CheckParm("-workdir") && M_IsNextParm())
snprintf(srb2home, sizeof srb2home, "%s", M_GetNextParm());
else
#ifdef DEFAULTDIR
snprintf(srb2home, sizeof srb2home, "%s" PATHSEP DEFAULTDIR, userhome);
#else // DEFAULTDIR
snprintf(srb2home, sizeof srb2home, "%s", userhome);
#endif // DEFAULTDIR
snprintf(downloaddir, sizeof downloaddir, "%s" PATHSEP "DOWNLOAD", srb2home);
if (dedicated)
snprintf(configfile, sizeof configfile, "%s" PATHSEP "d"CONFIGFILENAME, srb2home);
else
snprintf(configfile, sizeof configfile, "%s" PATHSEP CONFIGFILENAME, srb2home);
// can't use sprintf since there is %u in savegamename
strcatbf(savegamename, srb2home, PATHSEP);
}
configfile[sizeof configfile - 1] = '\0';
// If config isn't writable, tons of behavior will be broken.
// Fail loudly before things get confusing!
snprintf(testfile, sizeof testfile, "%s" PATHSEP "file.tmp", srb2home);
testfile[sizeof testfile - 1] = '\0';
tmpfile = fopen(testfile, "w");
if (tmpfile == NULL)
{
#if defined (_WIN32)
I_Error("Couldn't write game config.\nMake sure the game is installed somewhere it has write permissions.\n\n(Don't use the Downloads folder, Program Files, or your desktop!\nIf unsure, we recommend making a subfolder in your Documents folder.)");
#else
I_Error("Couldn't write game config.\nMake sure you've installed the game somewhere it has write permissions.");
#endif
}
else
{
fclose(tmpfile);
remove(testfile);
}
}
// make sure workdir exists
I_mkdir(srb2home, 0755);
// Create addons dir
snprintf(addonsdir, sizeof addonsdir, "%s%s%s", srb2home, PATHSEP, "addons");
I_mkdir(addonsdir, 0755);
D_SetupProtocol();
// seed M_Random because it is necessary; seed P_Random for scripts that
// might want to use random numbers immediately at start
if (!M_RandomSeedFromOS())
M_RandomSeed((UINT32)time(NULL)); // less good but serviceable
P_SetRandSeed(M_RandomizedSeed());
if (M_CheckParm("-password") && M_IsNextParm())
D_SetPassword(M_GetNextParm());
// FIND THEM
D_FindAddonsToAutoload();
// add any files specified on the command line with -file wadfile
// to the wad list
if (!(M_CheckParm("-connect") && !M_CheckParm("-server")))
{
if (M_CheckParm("-file"))
{
// the parms after p are wadfile/lump names,
// until end of parms or another - preceded parm
while (M_IsNextParm())
{
const char *s = M_GetNextParm();
if (s) // Check for NULL?
D_AddFile(s, startuppwads, startuppwadcount++);
}
}
}
// get map from parms
if (M_CheckParm("-server") || dedicated)
netgame = server = true;
CONS_Printf("Z_Init(): Init zone memory allocation daemon. \n");
Z_Init();
// adapt tables to SRB2's needs, including extra slots for dehacked file support
P_PatchInfoTables();
//---------------------------------------------------- READY TIME
// we need to check for dedicated before initialization of some subsystems
CONS_Printf("I_InitializeTime()...\n");
I_InitializeTime();
setlocale(LC_TIME, "");
// Setup default unlockable conditions
M_SetupDefaultConditionSets();
// load wad, including the main wad file
CONS_Printf("W_InitMultipleFiles(): Adding IWAD and main PWADs.\n");
W_InitMultipleFiles(startupiwadfiles, startupiwadcount, false);
//mainwads = startupiwadcount - musicwads;
D_CleanFile(startupiwadfiles, startupiwadcount);
startupiwadcount = 0;
mainwads = 0;
#ifndef DEVELOP
// Check MD5s of autoloaded files
// Note: Do not add any files that ignore MD5!
W_VerifyFileMD5(mainwads, ASSET_HASH_SRB2_SRB); // srb2.srb/srb2.wad
#ifdef USE_PATCH_DTA
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_PATCH_DTA); // patch.dta
#endif
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_GFX_KART); // gfx.kart
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_TEXTURES_KART); // textures.kart
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_CHARS_KART); // chars.kart
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_MAPS_KART); // maps.kart -- 4 - If you touch this, make sure to touch up the majormods stuff below.
#ifdef USE_PATCH_KART
mainwads++; W_VerifyFileMD5(mainwads, ASSET_HASH_PATCH_KART); // patch.kart
#endif
#else
#ifdef USE_PATCH_DTA
mainwads++; // patch.dta
#endif
mainwads++; // gfx.kart
mainwads++; // textures.kart
mainwads++; // chars.kart
mainwads++; // maps.kart
#ifdef USE_PATCH_KART
mainwads++; // patch.kart
#endif
#endif //ifndef DEVELOP
D_CheckSaturnExtraFiles(); // check all the saturn stuff :3
// Do it before P_InitMapData because PNG patch
// conversion sometimes needs the palette
V_ReloadPalette();
D_CheckMapReplacements(false);
if (startuppwadcount > 0)
{
CONS_Printf("W_InitMultipleFiles(): Adding extra PWADs.\n");
W_InitMultipleFiles(startuppwads, startuppwadcount, true);
// Only search for pwad maps if we actually have a pwad added
D_CheckMapReplacements(true);
D_CleanFile(startuppwads, startuppwadcount);
}
startuppwadcount = 0;
cht_Init();
//---------------------------------------------------- READY SCREEN
// we need to check for dedicated before initialization of some subsystems
CONS_Printf("I_StartupGraphics()...\n");
I_StartupGraphics();
#ifdef HWRENDER
// Lactozilla: Add every hardware mode CVAR and CCMD.
// Has to be done before the configuration file loads,
// but after the OpenGL library loads.
HWR_AddCommands();
#endif
//--------------------------------------------------------- CONSOLE
// setup loading screen
SCR_Startup();
// Do this in background; lots of number crunching
R_InitTranslucencyTables();
// we need the font of the console
CONS_Printf("HU_Init(): Setting up heads up display.\n");
HU_Init();
COM_Init();
CON_Init();
D_RegisterServerCommands();
D_RegisterClientCommands(); // be sure that this is called before D_CheckNetGame
R_RegisterEngineStuff();
S_RegisterSoundStuff();
I_RegisterSysCommands();
//--------------------------------------------------------- CONFIG.CFG
M_FirstLoadConfig(); // WARNING : this do a "COM_BufExecute()"
G_LoadGameData();
VID_PrepareModeList(); // Regenerate Modelist according to cv_fullscreen
// set user default mode or mode set at cmdline
SCR_CheckDefaultMode();
wipegamestate = gamestate;
savedata.lives = 0; // flag this as not-used
// make sure I_Quit() will write back the correct config
// (do not write back the config if it crash before)
loaded_config = true; // so palettechange doesent get called 500 times at startup lol
//------------------------------------------------ COMMAND LINE PARAMS
// this must be done after loading gamedata,
// to avoid setting off the corrupted gamedata code in G_LoadGameData if a SOC with custom gamedata is added
// -- Monster Iestyn 20/02/20
if (M_CheckParm("-warp") && M_IsNextParm())
{
const char *word = M_GetNextParm();
pstartmap = G_FindMapByNameOrCode(word, NULL);
if (! pstartmap)
I_Error("Cannot find a map remotely named '%s'\n", word);
else
{
if (!M_CheckParm("-server"))
G_SetGameModified(true, true);
autostart = true;
}
}
if (M_CheckParm("-noupload"))
COM_BufAddText("downloading 0\n");
CONS_Printf("M_Init(): Init miscellaneous info.\n");
M_Init();
CONS_Printf("R_Init(): Init SRB2 refresh daemon.\n");
R_Init();
#if SOUND == SOUND_DUMMY
sound_disabled = true;
music_disabled = true;
#else
// setting up sound
if (dedicated || M_CheckParm("-noaudio")) // combines -nosound and -nomusic
{
sound_disabled = true;
music_disabled = true;
}
else
{
if (M_CheckParm("-nosound"))
sound_disabled = true;
if (M_CheckParm("-nomusic"))
music_disabled = true;
}
if (!(sound_disabled && music_disabled))
{
CONS_Printf("S_InitSfxChannels(): Setting up sound channels.\n");
I_StartupSound();
I_InitMusic();
S_InitSfxChannels(cv_soundvolume.value);
}
#endif
S_InitMusicDefs();
M_InitEmotes();
CONS_Printf("ST_Init(): Init status bar.\n");
ST_Init();
D_AddAutoloadFiles();
// Set up splitscreen players before joining!
if (!dedicated && (M_CheckParm("-splitscreen") && M_IsNextParm()))
{
UINT8 num = atoi(M_GetNextParm());
if (num >= 1 && num <= 4)
{
CV_StealthSetValue(&cv_splitplayers, num);
splitscreen = num-1;
SplitScreen_OnChange();
}
}
// init all NETWORK
CONS_Printf("D_CheckNetGame(): Checking network game status.\n");
if (D_CheckNetGame())
autostart = true;
if (splitscreen && !M_CheckParm("-connect") && !M_CheckProtoParam("ip")) // Make sure multiplayer & autostart is set if you have splitscreen, even after D_CheckNetGame
multiplayer = autostart = true;
// check for a driver that wants intermission stats
// start the apropriate game based on parms
if (M_CheckParm("-record") && M_IsNextParm())
{
G_RecordDemo(M_GetNextParm());
autostart = true;
}
// user settings come before "+" parameters.
if (dedicated)
COM_ImmedExecute(va("exec \"%s"PATHSEP"kartserv.cfg\"\n", srb2home));
else
COM_ImmedExecute(va("exec \"%s"PATHSEP"kartexec.cfg\" -noerror\n", srb2home));
if (!autostart)
M_PushSpecialParameters(); // push all "+" parameters at the command buffer
// demo doesn't need anymore to be added with D_AddFile()
p = M_CheckParm("-playdemo");
if (!p)
p = M_CheckParm("-timedemo");
if (p && M_IsNextParm())
{
char tmp[MAX_WADPATH];
// add .lmp to identify the EXTERNAL demo file
// it is NOT possible to play an internal demo using -playdemo,
// rather push a playdemo command.. to do.
strcpy(tmp, M_GetNextParm());
// get spaced filename or directory
while (M_IsNextParm())
{
strcat(tmp, " ");
strcat(tmp, M_GetNextParm());
}
FIL_DefaultExtension(tmp, ".lmp");
CONS_Printf(M_GetText("Playing demo %s.\n"), tmp);
if (M_CheckParm("-playdemo"))
{
demo.quitafterplaying = true; // quit after one demo
G_DeferedPlayDemo(tmp);
}
else
G_TimeDemo(tmp);
G_SetGamestate(GS_NULL);
wipegamestate = GS_NULL;
return;
}
#ifdef HAVE_CURL
if (M_CheckProtoParam("replay"))
{
const char *replayurl = M_GetProtoParam();
if (!replayurl)
I_Error("REPLAY: Invalid URL.");
gconst char *replayname = strrchr(replayurl, '/');
if (!replayname)
I_Error("REPLAY: Invalid URL.");
#define REPLAYDIR "/DownloadedReplays/"
I_mkdir(va("%s%s", srb2home, REPLAYDIR), 0755);
CONS_Printf("bruh %s", va("%s%s%s", srb2home, REPLAYDIR, replayname));
// check if file already exists
if (access(va("%s%s%s", srb2home, REPLAYDIR, replayurl), F_OK )!=0)
D_DownloadReplay(replayurl, va("%s%s%s", srb2home, REPLAYDIR, replayname));
// add .lmp to identify the EXTERNAL demo file
// it is NOT possible to play an internal demo using -playdemo,
// rather push a playdemo command.. to do.
G_DeferedPlayDemo(va("%s%s", REPLAYDIR, replayname));
#undef REPLAYDIR
G_SetGamestate(GS_NULL);
wipegamestate = GS_NULL;
return;
}
#endif
if (autostart || netgame)
{
gameaction = ga_nothing;
CV_ClearChangedFlags();
// Do this here so if you run SRB2 with eg +timelimit 5, the time limit counts
// as having been modified for the first game.
M_PushSpecialParameters(); // push all "+" parameter at the command buffer
COM_BufExecute(); // ensure the command buffer gets executed before the map starts (+skin)
strncpy(connectedservername, cv_servername.string, MAXSERVERNAME);
if (M_CheckParm("-gametype") && M_IsNextParm())
{
// from Command_Map_f
INT32 j;
INT16 newgametype = -1;
const char *sgametype = M_GetNextParm();
newgametype = G_GetGametypeByName(sgametype);
if (newgametype == -1) // reached end of the list with no match
{
j = atoi(sgametype); // assume they gave us a gametype number, which is okay too
if (j >= 0 && j < NUMGAMETYPES)
newgametype = (INT16)j;
}
if (newgametype != -1)
{
j = gametype;
gametype = newgametype;
D_GameTypeChanged(j);
}
}
if (M_CheckParm("-skill") && M_IsNextParm())
{
INT32 j;
INT16 newskill = -1;
const char *sskill = M_GetNextParm();
for (j = 0; kartspeed_cons_t[j].strvalue; j++)
{
if (fasticmp(kartspeed_cons_t[j].strvalue, sskill))
{
newskill = (INT16)kartspeed_cons_t[j].value;
break;
}
}
if (!kartspeed_cons_t[j].strvalue) // reached end of the list with no match
{
j = atoi(sskill); // assume they gave us a skill number, which is okay too
if (j >= 0 && j <= 2)
newskill = (INT16)j;
}
if (newskill != -1)
CV_SetValue(&cv_kartspeed, newskill);
}
if (server && !M_CheckParm("+map"))
{
// Prevent warping to nonexistent levels
if (W_CheckNumForName(G_BuildMapName(pstartmap)) == LUMPERROR)
I_Error("Could not warp to %s (map not found)\n", G_BuildMapName(pstartmap));
// Prevent warping to locked levels
// ... unless you're in a dedicated server. Yes, technically this means you can view any level by
// running a dedicated server and joining it yourself, but that's better than making dedicated server's
// lives hell.
else if (!dedicated && M_MapLocked(pstartmap))
I_Error("You need to unlock this level before you can warp to it!\n");
else
D_MapChange(pstartmap, gametype, (boolean)cv_kartencore.value, true, 0, false, false);
}
}
else if (M_CheckParm("-skipintro"))
{
F_StartTitleScreen();
}
else
F_StartIntro(); // Tails 03-03-2002
CON_ToggleOff();
if (dedicated && server)
{
G_SetGamestate(GS_LEVEL);
if (!P_SetupLevel(false, false))
I_Quit(); // fail so reset game stuff
}
#ifdef HAVE_DISCORDRPC
if (!dedicated)
{
DRPC_Init();
}
#endif
}
const char *D_Home(void)
{
const char *userhome = NULL;
#ifdef ANDROID
return "/data/data/org.srb2/";
#endif
if (M_CheckParm("-home") && M_IsNextParm())
userhome = M_GetNextParm();
else
{
#if !(defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON))
if (FIL_FileOK(CONFIGFILENAME))
usehome = false; // Let's NOT use home
else
#endif
userhome = I_GetEnv("HOME"); //Alam: my new HOME for srb2
}
#ifdef _WIN32 //Alam: only Win32 have APPDATA and USERPROFILE
if (!userhome && usehome) //Alam: Still not?
{
char *testhome = NULL;
testhome = I_GetEnv("APPDATA");
if (testhome != NULL
&& (FIL_FileOK(va("%s" PATHSEP "%s" PATHSEP CONFIGFILENAME, testhome, DEFAULTDIR))))
{
userhome = testhome;
}
}
#ifndef __CYGWIN__
if (!userhome && usehome) //Alam: All else fails?
{
char *testhome = NULL;
testhome = I_GetEnv("USERPROFILE");
if (testhome != NULL
&& (FIL_FileOK(va("%s" PATHSEP "%s" PATHSEP CONFIGFILENAME, testhome, DEFAULTDIR))))
{
userhome = testhome;
}
}
#endif// !__CYGWIN__
#endif// _WIN32
if (usehome)
return userhome;
else
return NULL;
}