diff --git a/src/Makefile b/src/Makefile index 3422a0cf7..d7a8345cd 100644 --- a/src/Makefile +++ b/src/Makefile @@ -69,6 +69,7 @@ # VALGRIND=1 - Enable Valgrind memory debugging support. # PROFILEMODE=1 - Enable performance profiling (gprof). # USEASAN=1 - Enable building with Address Sanitizer. +# USEUBSAN=1 - Enable building with Undefined Behavior Sanitizer. # NOLIBBACKTRACE=1 - Disable using Libbacktrace for crashlog traces. # # General flags for building: @@ -243,10 +244,14 @@ ifdef STATIC libs+=-static endif +ifneq (,$(filter $(CC) $(CXX),gcc g++)) + opts+=-mno-ms-bitfields +endif + # build with profiling information ifdef PROFILEMODE opts+=-pg -LDFLAGS+=-pg +libs+=-pg endif ifdef DEBUGMODE @@ -256,29 +261,32 @@ debug_opts=-DNDEBUG opts+=-O3 ifdef USELTO # compile with LTO -ifdef MINGW -opts+=-flto=auto -g -LDFLAGS+=-flto=auto -g -else opts+=-flto=auto -LDFLAGS+=-flto=auto -endif +libs+=-flto=auto endif endif ifdef USEASAN # compile with asan -ifdef MINGW -opts+=-fsanitize=address -g -libs+=-fsanitize=address -g -else opts+=-fsanitize=address libs+=-fsanitize=address endif + +ifdef USEUBSAN +# compile with asan +opts+=-fsanitize=undefined +libs+=-fsanitize=undefined endif -ifeq ($(CC),clang) - LDFLAGS+= -fuse-ld=lld +ifneq (,$(filter $(CC) $(CXX),clang clang++)) + libs+=-fuse-ld=lld +endif + +ifdef MINGW +# mingw needs this passed AFTER lto and the likes were passed +# otherwise libbacktrace may break +opts+=-g +libs+=-g endif # debug_opts also get passed to windres diff --git a/src/Makefile.d/sdl.mk b/src/Makefile.d/sdl.mk index c704a83eb..95fe34e6a 100644 --- a/src/Makefile.d/sdl.mk +++ b/src/Makefile.d/sdl.mk @@ -10,7 +10,7 @@ makedir:=$(makedir)/SDL -opts+=-DDIRECTFULLSCREEN -DHAVE_SDL +opts+=-DHAVE_SDL sources+=$(call List,sdl/Sourcefile) NOUPNP=1 diff --git a/src/Makefile.d/win32.mk b/src/Makefile.d/win32.mk index 8c5e75b8e..4adcfe6e8 100644 --- a/src/Makefile.d/win32.mk +++ b/src/Makefile.d/win32.mk @@ -2,6 +2,8 @@ # Mingw, if you don't know, that's Win32/Win64 # +sources+=$(call List,win32/Sourcefile) + ifndef MINGW64 EXENAME?=srb2kart-saturn_32bit.exe else @@ -95,7 +97,7 @@ LIBBACKTRACE_libs:=-L$(lib)/lib/x86_64 -lbacktrace $(eval $(call _set,LIBBACKTRACE)) else lib:=../libs/drmingw -opts+=-I$(lib)/include +opts+=-I$(lib)/include -DHAVE_DRMINGW libs+=-L$(lib)/lib/win32 -lmgwhelp -lexchndl endif diff --git a/src/Sourcefile b/src/Sourcefile index 9474b797d..352081bc5 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -53,7 +53,7 @@ r_data.c r_draw.c r_fps.cpp r_main.cpp -r_patch.c +r_patch.cpp r_patchrotation.c r_plane.cpp r_segs.cpp diff --git a/src/android/i_system.c b/src/android/i_system.c index b20625587..102bff461 100644 --- a/src/android/i_system.c +++ b/src/android/i_system.c @@ -110,7 +110,7 @@ void I_Error(const char *error, ...) char logbuf[8192]; va_start(argptr, error); - vsprintf(logbuf, error, argptr); + vsnprintf(logbuf, 8192, error, argptr); va_end(argptr); LOGE(logbuf); @@ -166,7 +166,7 @@ void I_OutputMsg(const char *fmt, ...) char logbuf[8192]; va_start(argptr, fmt); - vsprintf(logbuf, fmt, argptr); + vsnprintf(logbuf, 8192, fmt, argptr); va_end(argptr); LOGD(logbuf); diff --git a/src/command.c b/src/command.c index ee3b36247..e73125649 100644 --- a/src/command.c +++ b/src/command.c @@ -700,6 +700,7 @@ static void COM_Echo_f(void) for (i = 1; i < COM_Argc(); i++) CONS_Printf("%s ", COM_Argv(i)); + CONS_Printf("\n"); } @@ -708,11 +709,11 @@ static void COM_Echo_f(void) static void COM_CEcho_f(void) { size_t i; - char cechotext[1024] = ""; + char cechotext[1024] = {0}; for (i = 1; i < COM_Argc(); i++) { - strlcpy(cechotext, COM_Argv(i), sizeof(cechotext)-1); + strlcat(cechotext, COM_Argv(i), sizeof(cechotext)-1); strlcat(cechotext, " ", sizeof(cechotext)-1); } @@ -938,6 +939,8 @@ static void COM_Find_f(void) } help = COM_Argv(1); + if (!help) + return; helplen = strlen(help); CONS_Printf("\x82""Variables:\n"); matchesany = false; @@ -1913,13 +1916,14 @@ void CV_AddValue(consvar_t *var, INT32 increment) max = (M_SecretUnlocked(SECRET_HARDSPEED) ? 3 : 2); } #ifdef PARANOIA - if (currentindice == -1) - I_Error("CV_AddValue: current value %d not found in possible value\n", - var->value); + if (currentindice == -1 || max == 0) + I_Error("CV_AddValue: current value %d not found in possible value\n", var->value); #endif - - newindice = (currentindice + increment + max) % max; - CV_Set(var, var->PossibleValue[newindice].strvalue); + if (max > 0) + { + newindice = (currentindice + increment + max) % max; + CV_Set(var, var->PossibleValue[newindice].strvalue); + } } } else diff --git a/src/console.c b/src/console.c index a01c72062..3959d9b98 100644 --- a/src/console.c +++ b/src/console.c @@ -69,14 +69,9 @@ static boolean consoleready; // console prompt is ready INT32 con_destlines; // vid lines used by console at final position static INT32 con_curlines; // vid lines currently used by console - INT32 con_clipviewtop; // (useless) - static UINT8 con_hudlines; // number of console heads up message lines static UINT32 con_hudtime[MAXHUDLINES]; // remaining time of display for hud msg lines - INT32 con_clearlines; // top screen lines to refresh when view reduced - boolean con_hudupdate; // when messages scroll, we need a backgrnd refresh - // console text output static char *con_line; // console text output current line static size_t con_cx; // cursor position in current line @@ -393,9 +388,6 @@ void CON_Init(void) Lock_state(); - //note: CON_Ticker should always execute at least once before D_Display() - con_clipviewtop = -1; // -1 does not clip - con_hudlines = atoi(cons_hudlines.defaultvalue); Unlock_state(); @@ -727,7 +719,6 @@ void CON_ToggleOff(void) con_curlines = 0; CON_ClearHUD(); con_forcepic = 0; - con_clipviewtop = -1; // remove console clipping of view I_SetTextInput(false); @@ -779,18 +770,6 @@ void CON_Ticker(void) } } - // clip the view, so that the part under the console is not drawn - con_clipviewtop = -1; - if (cons_backpic.value) // clip only when using an opaque background - { - if (con_curlines > 0) - con_clipviewtop = con_curlines - viewwindowy - 1 - 10; - // NOTE: BIG HACK::SUBTRACT 10, SO THAT WATER DON'T COPY LINES OF THE CONSOLE - // WINDOW!!! (draw some more lines behind the bottom of the console) - if (con_clipviewtop < 0) - con_clipviewtop = -1; // maybe not necessary, provided it's < 0 - } - // check if console ready for prompt if (con_destlines >= minheight) { @@ -1100,9 +1079,6 @@ static void CON_Linefeed(void) con_line = &con_buffer[(con_cy%con_totallines)*con_width]; memset(con_line, ' ', con_width); - - // make sure the view borders are refreshed if hud messages scroll - con_hudupdate = true; // see HU_Erase() } // Outputs text into the console text buffer @@ -1282,7 +1258,7 @@ void CONS_Alert(alerttype_t level, const char *fmt, ...) txt = malloc(8192); va_start(argptr, fmt); - vsprintf(txt, fmt, argptr); + vsnprintf(txt, 8192, fmt, argptr); va_end(argptr); switch (level) @@ -1318,7 +1294,7 @@ void CONS_Debug(INT32 debugflags, const char *fmt, ...) txt = malloc(8192); va_start(argptr, fmt); - vsprintf(txt, fmt, argptr); + vsnprintf(txt, 8192, fmt, argptr); va_end(argptr); // Again I am lazy, oh well @@ -1489,9 +1465,6 @@ static void CON_DrawHudlines(void) //V_DrawCharacter(x, y, (p[c]&0xff) | cv_constextsize.value | V_NOSCALESTART, !cv_allcaps.value); y += charheight; } - - // top screen lines that might need clearing when view is reduced - con_clearlines = y; // this is handled by HU_Erase(); } // draw the console background, text, and prompt if enough place @@ -1509,10 +1482,6 @@ static void CON_DrawConsole(void) if (con_curlines <= 0) return; - //FIXME: refresh borders only when console bg is translucent - con_clearlines = con_curlines; // clear console draw from view borders - con_hudupdate = true; // always refresh while console is on - // draw console background if (cons_backpic.value || con_forcepic) { diff --git a/src/console.h b/src/console.h index e704a87f1..79af2e48f 100644 --- a/src/console.h +++ b/src/console.h @@ -30,14 +30,9 @@ extern boolean con_recalc; extern boolean con_startup; -// top clip value for view render: do not draw part of view hidden by console -extern INT32 con_clipviewtop; - // 0 means console if off, or moving out extern INT32 con_destlines; -extern INT32 con_clearlines; // lines of top of screen to refresh -extern boolean con_hudupdate; // hud messages have changed, need refresh extern UINT32 con_scalefactor; // console text scale factor extern consvar_t cons_backcolor, cons_menuhighlight; diff --git a/src/d_clisrv.c b/src/d_clisrv.c index a62ebde7c..61afc0eb7 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -823,7 +823,7 @@ static void resynch_read_player(resynch_pak *rsp) P_SetThingPosition(players[i].mo); } -static inline void resynch_write_ctf(resynchend_pak *rst) +static void resynch_write_ctf(resynchend_pak *rst) { mobj_t *mflag; UINT8 i, j; @@ -863,7 +863,7 @@ static inline void resynch_write_ctf(resynchend_pak *rst) } } -static inline void resynch_read_ctf(resynchend_pak *p) +static void resynch_read_ctf(resynchend_pak *p) { UINT8 i; diff --git a/src/d_main.c b/src/d_main.c index 485103898..9ea10bfa2 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -347,11 +347,65 @@ static void D_Renderview(void) } } + 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; + objectsdrawn = 0; + break; + } + +#ifdef HWRENDER + if (rendermode == render_opengl) + { + HWR_RenderPlayerView(); + } + else if (rendermode == render_soft) +#endif + + R_RenderPlayerView(&players[displayplayers[i]]); + } + + if (rendermode == render_soft) + { + if (i == 0) + R_ApplyViewMorph(); + + V_DoPostProcessor(i, postimgparam[i]); + } + } + // 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 - patch_t *pat = W_CachePatchName("SRB2BACK", PU_CACHE); + patch_t *pat = W_CachePatchName("SRB2BACK", PU_PATCH); INT32 x, y, pw = SHORT(pat->width) * vid.dup, ph = SHORT(pat->height) * vid.dup; for (x = vid.width>>1; x < vid.width; x += pw) @@ -361,65 +415,6 @@ static void D_Renderview(void) } } - for (i = 0; i <= splitscreen; i++) - { - const boolean issplitscreen = (i > 0); - - if (!P_MobjWasRemoved(players[displayplayers[i]].mo) || players[displayplayers[i]].playerstate == PST_DEAD) - { - viewssnum = i; - - if (!issplitscreen) // Initialize for P1 - { - viewwindowy = viewwindowx = 0; - objectsdrawn = 0; - } - -#ifdef HWRENDER - if (rendermode == render_opengl) - { - HWR_RenderPlayerView(); - R_RestoreLevelInterpolators(); - continue; - } -#endif - if (issplitscreen) // Splitscreen-specific - { - 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; - default: - break; - } - } - - R_RenderPlayerView(&players[displayplayers[i]]); - } - - if (!issplitscreen) - R_ApplyViewMorph(); - - V_DoPostProcessor(i, postimgparam[i]); - } - R_RestoreLevelInterpolators(); } @@ -522,19 +517,16 @@ static boolean D_Display(void) case GS_LEVEL: if (!gametic) break; - HU_Erase(); AM_Drawer(); break; case GS_INTERMISSION: Y_IntermissionDrawer(); - HU_Erase(); HU_Drawer(); break; case GS_VOTING: Y_VoteDrawer(); - HU_Erase(); HU_Drawer(); break; @@ -549,7 +541,6 @@ static boolean D_Display(void) case GS_CUTSCENE: F_CutsceneDrawer(); - HU_Erase(); HU_Drawer(); break; @@ -559,7 +550,6 @@ static boolean D_Display(void) case GS_EVALUATION: F_GameEvaluationDrawer(); - HU_Erase(); HU_Drawer(); break; @@ -569,7 +559,6 @@ static boolean D_Display(void) case GS_CREDITS: F_CreditDrawer(); - HU_Erase(); HU_Drawer(); break; @@ -586,7 +575,6 @@ static boolean D_Display(void) { // I don't think HOM from nothing drawing is independent... F_WaitingPlayersDrawer(); - HU_Erase(); HU_Drawer(); } case GS_TIMEATTACK: @@ -890,12 +878,6 @@ void D_SRB2Loop(void) // always update console and hud // otherwise it may take minutes to open it CON_Drawer(); - - if (gamestate == GS_LEVEL) - { - ST_Drawer(); - HU_Drawer(); - } } } @@ -972,6 +954,24 @@ void D_SRB2Loop(void) // D_SRB2Main // ========================================================================= +static void ResetSplitScreen(void) +{ + UINT8 i; + + // recompute screen size + R_ExecuteSetViewSize(); + + if (!demo.playback && !botingame) + { + for (i = 1; i < MAXSPLITSCREENPLAYERS; i++) + { + if (i > splitscreen) + CL_RemoveSplitscreenPlayer(displayplayers[i]); + else + CL_AddSplitscreenPlayer(); + } + } +} // // D_ClearState // @@ -979,8 +979,11 @@ void D_ClearState(void) { INT32 i; + demo.title = false; + // okay, stop now // (otherwise the game still thinks we're playing!) + CURLAbortFile(); SV_StopServer(); SV_ResetServer(); serverlistultimatecount = 0; @@ -989,7 +992,8 @@ void D_ClearState(void) CL_ClearPlayer(i); splitscreen = 0; - SplitScreen_OnChange(); + ResetSplitScreen(); // splitscreen onchange resets us to singleplayer :chaosleep: + botingame = false; botskin = 0; cv_debug = 0; @@ -1008,7 +1012,6 @@ void D_ClearState(void) gameaction = ga_nothing; memset(displayplayers, 0, sizeof(displayplayers)); consoleplayer = 0; - //demosequence = -1; gametype = GT_RACE; // SRB2kart paused = false; @@ -1031,6 +1034,11 @@ void D_ClearState(void) G_SetGamestate(GS_NULL); wipegamestate = GS_NULL; + + M_ClearMenus(true); + + // map palettes affect this + D_ResetDeviceLED(); } // @@ -1038,12 +1046,9 @@ void D_ClearState(void) // void D_StartTitle(void) { - demo.title = false; D_ClearState(); - netgame = false; // title menu shouldnt be a netgame lmao - M_ClearMenus(true); + multiplayer = netgame = false; // title menu shouldnt be a netgame or multiplayer lmao F_StartTitleScreen(); - D_ResetDeviceLED(); } // @@ -1931,9 +1936,7 @@ void D_SRB2Main(void) G_LoadGameData(); -#if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) VID_PrepareModeList(); // Regenerate Modelist according to cv_fullscreen -#endif // set user default mode or mode set at cmdline SCR_CheckDefaultMode(); diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 6f97cb819..92d9fb935 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -964,10 +964,11 @@ void D_RegisterClientCommands(void) // g_input.c CV_RegisterVar(&cv_controlperkey); - CV_RegisterVar(&cv_turnsmooth); for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { + CV_RegisterVar(&cv_turnsmooth[i]); + CV_RegisterVar(&cv_turnaxis[i]); CV_RegisterVar(&cv_moveaxis[i]); CV_RegisterVar(&cv_camturnaxis[i]); @@ -984,6 +985,8 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_xdeadzone[i]); CV_RegisterVar(&cv_ydeadzone[i]); + CV_RegisterVar(&cv_litesteer[i]); + CV_RegisterVar(&cv_usejoystick[i]); CV_RegisterVar(&cv_joyscale[i]); CV_RegisterVar(&cv_rumble[i]); @@ -1991,11 +1994,6 @@ static void Got_NameAndColor(UINT8 **cp, INT32 playernum) } else SetPlayerSkinByNum(playernum, skin); - -#ifdef HAVE_DISCORDRPC - if (playernum == consoleplayer) - DRPC_UpdatePresence(); -#endif } void SendWeaponPref(void) @@ -2489,15 +2487,18 @@ void D_SetupVote(void) INT32 i; UINT8 gt = (cv_kartgametypepreference.value == -1) ? gametype : cv_kartgametypepreference.value; UINT8 secondgt = G_SometimesGetDifferentGametype(gt); - INT16 votebuffer[4] = {-1,-1,-1,0}; + INT16 votebuffer[4] = {-1,-1,-1, 0}; INT16 luamaps[4] = {0, 0, 0, 0}; LUA_HookSetupVote(luamaps, sizeof(luamaps)/sizeof(luamaps[0]), gt, secondgt); // Correct secondgt if needed - UINT8 typeoflevel = mapheaderinfo[luamaps[2]-1]->typeoflevel; - if (luamaps[2] && (typeoflevel & G_TOLFlag(secondgt&(~0x80))) == 0) - secondgt = ((typeoflevel & TOL_RACE) ? GT_RACE : GT_MATCH)|(secondgt&0x80); + if (luamaps[2]) + { + UINT8 typeoflevel = mapheaderinfo[luamaps[2]-1]->typeoflevel; + if ((typeoflevel & G_TOLFlag(secondgt&(~0x80))) == 0) + secondgt = ((typeoflevel & TOL_RACE) ? GT_RACE : GT_MATCH)|(secondgt&0x80); + } if (cv_kartencore.value && gt == GT_RACE) WRITEUINT8(p, (gt|0x80)); @@ -2598,14 +2599,18 @@ ConcatCommandArgv (int start, int end) size += strlen(COM_Argv(i)) + 1; } - final = ZZ_Alloc(size); - p = final; + p = final = ZZ_Alloc(size); + + if (!p) + I_Error("ConcatCommandArgv: Out of memory!\n"); --end;/* handle the final argument separately */ + for (i = start; i < end; ++i) { p += sprintf(p, "%s ", COM_Argv(i)); } + /* at this point "end" is actually the last argument's position */ strcpy(p, COM_Argv(end)); @@ -4216,23 +4221,32 @@ static void Command_MotD_f(void) mymotd = Z_Malloc(sizeof(motd), PU_STATIC, NULL); - strlcpy(mymotd, COM_Argv(1), sizeof motd); + if (!mymotd) + return; + //I_Error("Command_MotD_f: Out of memory!\n"); // idk if this aint a bit too much lel + + strlcpy(mymotd, COM_Argv(1), sizeof(motd)); + for (i = 2; i < j; i++) { - strlcat(mymotd, " ", sizeof motd); - strlcat(mymotd, COM_Argv(i), sizeof motd); + strlcat(mymotd, " ", sizeof(motd)); + strlcat(mymotd, COM_Argv(i), sizeof(motd)); } // Disallow non-printing characters and semicolons. for (i = 0; mymotd[i] != '\0'; i++) + { if (!isprint(mymotd[i]) || mymotd[i] == ';') { Z_Free(mymotd); return; } + } if ((netgame || multiplayer) && client) + { SendNetXCmd(XD_SETMOTD, mymotd, i); // send the actual size of the motd string, not the full buffer's size + } else { strcpy(motd, mymotd); @@ -4431,7 +4445,7 @@ static void Command_Addfile(void) } // Add file on your client directly if it is trivial, or you aren't in a netgame. - if (!(netgame || multiplayer) || musiconly) + if (!netgame || musiconly) { P_AddWadFile(fn, false); return; @@ -4474,7 +4488,7 @@ static void Command_Addfile(void) if (IsPlayerAdmin(consoleplayer) && (!server)) // Request to add file SendNetXCmd(XD_REQADDFILE, buf, buf_p - buf); else - SendNetXCmd(XD_ADDFILE, buf, buf_p - buf);; + SendNetXCmd(XD_ADDFILE, buf, buf_p - buf); } /** Adds something at runtime. diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index d0914be56..78f265e2a 100644 --- a/src/dedicated/i_system.c +++ b/src/dedicated/i_system.c @@ -1442,7 +1442,7 @@ static INT32 errorcount = 0; */ static boolean shutdowning = false; -void I_Error(const char *error, ...) +FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) { va_list argptr; char buffer[8192]; @@ -1468,7 +1468,7 @@ void I_Error(const char *error, ...) if (errorcount > 20) { va_start(argptr, error); - vsprintf(buffer, error, argptr); + vsnprintf(buffer, 8192, error, argptr); va_end(argptr); I_OutputMsg("SRB2Kart %s Recursive Error", buffer); @@ -1482,7 +1482,7 @@ void I_Error(const char *error, ...) // Display error message in the console before we start shutting it down va_start(argptr, error); - vsprintf(buffer, error, argptr); + vsnprintf(buffer, 8192, error, argptr); va_end(argptr); I_OutputMsg("\nI_Error(): %s\n", buffer); diff --git a/src/discord.c b/src/discord.c index 207a249a6..f94cd574d 100644 --- a/src/discord.c +++ b/src/discord.c @@ -49,6 +49,27 @@ discordRequest_t *discordRequestList = NULL; static char self_ip[IP_SIZE+1]; +/*-------------------------------------------------- + * const char *DRPC_HideUsername(const char *input) + * + * See header file for description. + * --------------------------------------------------*/ +const char *DRPC_HideUsername(const char *input) +{ + static char buffer[5]; + int i; + + buffer[0] = input[0]; + + for (i = 1; i < 4; ++i) + { + buffer[i] = '.'; + } + + buffer[4] = '\0'; + return buffer; +} + boolean drpc_init = false; /*-------------------------------------------------- @@ -105,7 +126,7 @@ static void DRPC_HandleReady(const DiscordUser *user) } else { - CONS_Printf("Discord: connected to %s#%s (%s)\n", user->username, user->discriminator, user->userId); + CONS_Printf("Discord: connected to %s (%s)\n", user->username, user->userId); } } @@ -241,8 +262,10 @@ static void DRPC_HandleJoinRequest(const DiscordUser *requestUser) newRequest->username = Z_Calloc(344, PU_STATIC, NULL); snprintf(newRequest->username, 344, "%s", requestUser->username); +#if 0 newRequest->discriminator = Z_Calloc(8, PU_STATIC, NULL); snprintf(newRequest->discriminator, 8, "%s", requestUser->discriminator); +#endif newRequest->userID = Z_Calloc(32, PU_STATIC, NULL); snprintf(newRequest->userID, 32, "%s", requestUser->userId); @@ -308,6 +331,9 @@ void DRPC_RemoveRequest(discordRequest_t *removeRequest) } Z_Free(removeRequest->username); +#if 0 + Z_Free(removeRequest->discriminator); +#endif Z_Free(removeRequest->userID); Z_Free(removeRequest); } diff --git a/src/discord.h b/src/discord.h index 131dc05f9..fa37c306b 100644 --- a/src/discord.h +++ b/src/discord.h @@ -29,7 +29,9 @@ extern struct discordInfo_s { typedef struct discordRequest_s { char *username; // Discord user name. +#if 0 // Good night, sweet prince... char *discriminator; // Discord discriminator (The little hashtag thing after the username). Separated for a "hide discriminators" cvar. +#endif char *userID; // The ID of the Discord user, gets used with Discord_Respond() // HAHAHA, no. @@ -44,6 +46,15 @@ typedef struct discordRequest_s { extern discordRequest_t *discordRequestList; +/*-------------------------------------------------- + * const char *DRPC_HideUsername(const char *input); + * + * Handle usernames while cv_discordstreamer is activated. + * (The loss of discriminators is still a dumbass regression + * that I will never forgive the Discord developers for.) + * --------------------------------------------------*/ + +const char *DRPC_HideUsername(const char *input); /*-------------------------------------------------- void DRPC_RemoveRequest(void); diff --git a/src/doomdef.h b/src/doomdef.h index 30419978b..00b4bc1f0 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -90,12 +90,6 @@ extern FILE *logstream; extern char logfilename[1024]; #endif -// not sure if this belongs here lul -// TODO: figure out whats preventing 32bit windows from working with libbacktrace -#if defined(_WIN32) && !defined(__MINGW64__) -#define HAVE_DRMINGW -#endif - #if defined (HAVE_LIBBACKTRACE) #define CRASH_LOGFILE_NAME "srb2kart-crash-log.txt" #elif defined (HAVE_DRMINGW) diff --git a/src/doomtype.h b/src/doomtype.h index 81c09c007..78867ed69 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -43,7 +43,6 @@ extern "C" { #define UINT64 uint64_t #ifdef __APPLE_CC__ -#define DIRECTFULLSCREEN 1 #define DEBUG_LOG #define NOIPX #endif diff --git a/src/f_finale.c b/src/f_finale.c index 0fe0effc4..ca22349a0 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -963,6 +963,7 @@ void F_StartTitleScreen(void) finalecount = 0; else wipegamestate = GS_TITLESCREEN; + G_SetGamestate(GS_TITLESCREEN); CON_ClearHUD(); diff --git a/src/filesrch.c b/src/filesrch.c index 088911e54..628a221c2 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -44,7 +44,7 @@ consvar_t cv_addons_search_case = {"addons_search_case", "No", CV_SAVE, CV_YesNo static CV_PossibleValue_t addons_search_type_cons_t[] = {{0, "Start"}, {1, "Anywhere"}, {0, NULL}}; consvar_t cv_addons_search_type = {"addons_search_type", "Anywhere", CV_SAVE, addons_search_type_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -char menupath[1024]; +char menupath[MAXFILEPATH]; size_t menupathindex[menudepth]; size_t menudepthleft = menudepth; @@ -111,7 +111,7 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want int found = 0; char *searchname; int depthleft = maxsearchdepth; - char searchpath[1024]; + char searchpath[MAXFILEPATH]; size_t *searchpathindex; dirhandle = (DIR**)malloc(maxsearchdepth * sizeof(DIR*)); diff --git a/src/filesrch.h b/src/filesrch.h index 697020c54..0a2da67b8 100644 --- a/src/filesrch.h +++ b/src/filesrch.h @@ -34,7 +34,8 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want #define menudepth 20 -extern char menupath[1024]; +#define MAXFILEPATH 1024 +extern char menupath[MAXFILEPATH]; extern size_t menupathindex[menudepth]; extern size_t menudepthleft; diff --git a/src/g_demo.c b/src/g_demo.c index 87ae0b61f..96ff33e65 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -74,7 +74,7 @@ static tic_t demostarttime; // for comparative timing purposes //@TODO put these all in a struct for namespacing purposes? static char demoname[128]; -savebuffer_t demobuf; +savebuffer_t demobuf = {0}; static UINT8 *demotime_p, *demoinfo_p; static UINT8 *demoend; static UINT8 demoflags; @@ -85,7 +85,8 @@ struct demovars_s demo; consvar_t cv_resyncdemo = {"resyncdemo", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // extra data stuff (events registered this frame while recording) -static struct { +static struct +{ UINT8 flags; // EZT flags // EZT_COLOR @@ -156,8 +157,8 @@ consvar_t cv_demodateformat = {"netdemo_dateformat", "Automatic", CV_SAVE, demod #define ZT_LATENCY 0x40 #define DEMOMARKER 0x80 // demoend -UINT8 demo_extradata[MAXPLAYERS]; -UINT8 demo_writerng; // 0=no, 1=yes, 2=yes but on a timeout +UINT8 demo_extradata[MAXPLAYERS] = {0}; +UINT8 demo_writerng = 0; // 0=no, 1=yes, 2=yes but on a timeout static ticcmd_t oldcmd[MAXPLAYERS]; #define DW_END 0xFF // End of extradata block @@ -192,7 +193,7 @@ static ticcmd_t oldcmd[MAXPLAYERS]; static mobj_t oldghost[MAXPLAYERS]; -static void G_ResetDemoPlayback(char *pdemoname); +static void G_ResetDemoPlayback(void); // Finds a skin with the closest stats if the expected skin doesn't exist. static INT32 GetSkinNumClosestToStats(UINT8 kartspeed, UINT8 kartweight) @@ -203,6 +204,7 @@ static INT32 GetSkinNumClosestToStats(UINT8 kartspeed, UINT8 kartweight) for (i = 0; i < numskins; i++) { stat_diff = abs(skins[i].kartspeed - kartspeed) + abs(skins[i].kartweight - kartweight); + if (stat_diff < closest_stats) { closest_stats = stat_diff; @@ -249,6 +251,7 @@ void G_ReadDemoExtraData(void) if (players[p].mo) P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL); // Is this how this should work..? } + if (extradata & DXD_SKIN) { UINT8 kartspeed, kartweight; @@ -267,6 +270,7 @@ void G_ReadDemoExtraData(void) players[p].kartspeed = kartspeed; players[p].kartweight = kartweight; } + if (extradata & DXD_COLOR) { // Color @@ -281,47 +285,49 @@ void G_ReadDemoExtraData(void) break; } } + if (extradata & DXD_NAME) { // Name M_Memcpy(player_names[p],demobuf.p,16); demobuf.p += 16; } + if (extradata & DXD_PLAYSTATE) { extradata = READUINT8(demobuf.p); - switch (extradata) { - case DXD_PST_PLAYING: - players[p].pflags |= PF_WANTSTOJOIN; // fuck you - break; + switch (extradata) + { + case DXD_PST_PLAYING: + players[p].pflags |= PF_WANTSTOJOIN; // fuck you + break; + case DXD_PST_SPECTATING: + players[p].pflags &= ~PF_WANTSTOJOIN; // double-fuck you - case DXD_PST_SPECTATING: - players[p].pflags &= ~PF_WANTSTOJOIN; // double-fuck you - if (!playeringame[p]) - { - CL_ClearPlayer(p); - playeringame[p] = true; - G_AddPlayer(p); - players[p].spectator = true; + if (!playeringame[p]) + { + CL_ClearPlayer(p); + playeringame[p] = true; + G_AddPlayer(p); + players[p].spectator = true; - // There's likely an off-by-one error in timing recording or playback of joins. This hacks around it so I don't have to find out where that is. \o/ - if (oldcmd[p].forwardmove) - P_RandomByte(); - } - else - { - players[p].spectator = true; - if (players[p].mo) - P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL); + // There's likely an off-by-one error in timing recording or playback of joins. This hacks around it so I don't have to find out where that is. \o/ + if (oldcmd[p].forwardmove) + P_RandomByte(); + } else - players[p].playerstate = PST_REBORN; - } - break; - - case DXD_PST_LEFT: - CL_RemovePlayer(p, 0); - break; + { + players[p].spectator = true; + if (players[p].mo) + P_DamageMobj(players[p].mo, NULL, NULL, DMG_INSTAKILL); + else + players[p].playerstate = PST_REBORN; + } + break; + case DXD_PST_LEFT: + CL_RemovePlayer(p, 0); + break; } G_ResetViews(); @@ -333,7 +339,6 @@ void G_ReadDemoExtraData(void) P_CheckRacers(); // also SRB2Kart } - p = READUINT8(demobuf.p); } @@ -342,11 +347,11 @@ void G_ReadDemoExtraData(void) UINT32 rng; UINT32 checkrng; - switch (p) + if (p == DW_RNG) { - case DW_RNG: rng = READUINT32(demobuf.p); checkrng = P_GetRandSeed(); + if (checkrng != rng) { if (demosynced) @@ -354,6 +359,7 @@ void G_ReadDemoExtraData(void) CONS_Alert(CONS_WARNING, M_GetText("Demo playback has desynced (RNG)!\n")); CONS_Printf("expected rng %d got %d\n", rng, checkrng); } + demosynced = false; P_SetRandSeed(rng); @@ -395,6 +401,7 @@ void G_WriteDemoExtraData(void) WRITEUINT8(demobuf.p, skins[players[i].skin].kartspeed); WRITEUINT8(demobuf.p, skins[players[i].skin].kartweight); } + if (demo_extradata[i] & DXD_COLOR) { // Color @@ -403,6 +410,7 @@ void G_WriteDemoExtraData(void) M_Memcpy(demobuf.p,name,16); demobuf.p += 16; } + if (demo_extradata[i] & DXD_NAME) { // Name @@ -411,6 +419,7 @@ void G_WriteDemoExtraData(void) M_Memcpy(demobuf.p,name,16); demobuf.p += 16; } + if (demo_extradata[i] & DXD_PLAYSTATE) { demo_writerng = 1; @@ -630,7 +639,7 @@ void G_GhostAddHit(INT32 playernum, mobj_t *victim) ghostext[playernum].flags |= EZT_HIT; ghostext[playernum].hits++; - Z_Realloc(ghostext[playernum].hitlist, ghostext[playernum].hits * sizeof(mobj_t *), PU_STATIC, &ghostext[playernum].hitlist); + ghostext[playernum].hitlist = Z_Realloc(ghostext[playernum].hitlist, ghostext[playernum].hits * sizeof(mobj_t *), PU_LEVEL, &ghostext[playernum].hitlist); P_SetTarget(ghostext[playernum].hitlist + (ghostext[playernum].hits-1), victim); } @@ -866,8 +875,8 @@ void G_WriteGhostTic(mobj_t *ghost, INT32 playernum) } Z_Free(ghostext[playernum].hitlist); - ghostext[playernum].hits = 0; ghostext[playernum].hitlist = NULL; + ghostext[playernum].hits = 0; } if (ghostext[playernum].flags & EZT_SPRITE) @@ -973,6 +982,7 @@ void G_ConsGhostTic(INT32 playernum) if (ziptic & GZT_EXTRA) { // But wait, there's more! ziptic = READUINT8(demobuf.p); + if (ziptic & EZT_COLOR) demobuf.p++; @@ -981,7 +991,8 @@ void G_ConsGhostTic(INT32 playernum) if (ziptic & EZT_HIT) { // Resync mob damage. - UINT16 i, count = READUINT16(demobuf.p); + UINT16 i; + UINT16 count = READUINT16(demobuf.p); thinker_t *th; mobj_t *mobj; @@ -1006,9 +1017,12 @@ void G_ConsGhostTic(INT32 playernum) { if (th->function != (actionf_p1)P_MobjThinker) continue; + mobj = (mobj_t *)th; + if (mobj->type == (mobjtype_t)type && mobj->x == x && mobj->y == y && mobj->z == z) break; + mobj = NULL; // wasn't this one, keep searching. } @@ -1055,6 +1069,7 @@ void G_ConsGhostTic(INT32 playernum) { if (demosynced) CONS_Alert(CONS_WARNING, "Demo playback has desynced (player %s)!\n", player_names[playernum]); + demosynced = false; if (cv_resyncdemo.value) @@ -1092,6 +1107,7 @@ void G_ConsGhostTic(INT32 playernum) CONS_Printf("expected item type %d got %d\n", ghostext[playernum].kartitem, players[playernum].kartstuff[k_itemtype]); CONS_Printf("expected item amount %d got %d\n", ghostext[playernum].kartamount, players[playernum].kartstuff[k_itemamount]); } + demosynced = false; players[playernum].kartstuff[k_itemtype] = ghostext[playernum].kartitem; @@ -1110,7 +1126,7 @@ void G_ConsGhostTic(INT32 playernum) void G_GhostTicker(void) { - demoghost *g,*p; + demoghost *g, *p; for (g = ghosts, p = NULL; g; g = g->next) { @@ -1126,12 +1142,16 @@ void G_GhostTicker(void) if (ziptic == 0) // Only support player 0 info for now { ziptic = READUINT8(g->p); + if (ziptic & DXD_SKIN) g->p += 18; // We _could_ read this info, but it shouldn't change anything in record attack... + if (ziptic & DXD_COLOR) g->p += 16; // Same tbh + if (ziptic & DXD_NAME) g->p += 16; // yea + if (ziptic & DXD_PLAYSTATE && READUINT8(g->p) != DXD_PST_PLAYING) I_Error("Ghost is not a record attack ghost"); //@TODO lmao don't blow up like this } @@ -1191,14 +1211,18 @@ void G_GhostTicker(void) g->oldmo.momx = READINT16(g->p)<<8; g->oldmo.momy = READINT16(g->p)<<8; } + if (ziptic & GZT_MOMZ) g->oldmo.momz = READINT16(g->p)<<8; + g->oldmo.x += g->oldmo.momx; g->oldmo.y += g->oldmo.momy; g->oldmo.z += g->oldmo.momz; } + if (ziptic & GZT_ANGLE) g->oldmo.angle = READUINT8(g->p)<<24; + if (ziptic & GZT_SPRITE) g->oldmo.frame = READUINT8(g->p); @@ -1214,36 +1238,42 @@ void G_GhostTicker(void) if (ziptic & GZT_EXTRA) { // But wait, there's more! ziptic = READUINT8(g->p); + if (ziptic & EZT_COLOR) { g->color = READUINT8(g->p); - switch(g->color) + + switch (g->color) { - default: - case GHC_NORMAL: // Go back to skin color - g->mo->color = g->oldmo.color; - break; - // Handled below - case GHC_SUPER: - case GHC_INVINCIBLE: - break; - case GHC_FIREFLOWER: // Fireflower - g->mo->color = SKINCOLOR_WHITE; - break; + default: + case GHC_NORMAL: // Go back to skin color + g->mo->color = g->oldmo.color; + break; + // Handled below + case GHC_SUPER: + case GHC_INVINCIBLE: + break; + case GHC_FIREFLOWER: // Fireflower + g->mo->color = SKINCOLOR_WHITE; + break; } } + if (ziptic & EZT_FLIP) g->mo->eflags ^= MFE_VERTICALFLIP; + if (ziptic & EZT_SCALE) { g->mo->destscale = READFIXED(g->p); if (g->mo->destscale != g->mo->scale) P_SetScale(g->mo, g->mo->destscale); } + if (ziptic & EZT_THOKMASK) { // Let's only spawn ONE of these per frame, thanks. mobj_t *mobj; INT32 type = -1; + if (g->mo->skin) { switch (ziptic & EZT_THOKMASK) @@ -1273,14 +1303,17 @@ void G_GhostTicker(void) mobj->frame = (states[mobjinfo[type].spawnstate].frame & FF_FRAMEMASK) | tr_trans60<tics = -1; // nope. mobj->color = g->mo->color; + if (g->mo->eflags & MFE_VERTICALFLIP) { mobj->flags2 |= MF2_OBJECTFLIP; mobj->eflags |= MFE_VERTICALFLIP; } + P_SetScale(mobj, g->mo->scale); mobj->destscale = g->mo->scale; } + mobj->floorz = mobj->z; mobj->ceilingz = mobj->z+mobj->height; P_UnsetThingPosition(mobj); @@ -1290,13 +1323,16 @@ void G_GhostTicker(void) P_SetTarget(&mobj->target, g->mo); } } + if (ziptic & EZT_HIT) { // Spawn hit poofs for killing things! - UINT16 i, count = READUINT16(g->p), health; + UINT16 i, health; + UINT16 count = READUINT16(g->p); //UINT32 type; fixed_t x,y,z; angle_t angle; mobj_t *poof; + for (i = 0; i < count; i++) { g->p += 4; // reserved @@ -1306,8 +1342,10 @@ void G_GhostTicker(void) y = READFIXED(g->p); z = READFIXED(g->p); angle = READANGLE(g->p); + if (health != 0 || i >= 4) // only spawn for the first 4 hits per frame, to prevent ghosts from splode-spamming too bad. continue; + poof = P_SpawnMobj(x, y, z, MT_GHOST); poof->angle = angle; poof->flags = MF_NOBLOCKMAP|MF_NOCLIP|MF_NOCLIPHEIGHT|MF_NOGRAVITY; // make an ATTEMPT to curb crazy SOCs fucking stuff up... @@ -1333,30 +1371,33 @@ void G_GhostTicker(void) skippedghosttic: // Tick ghost colors (Super and Mario Invincibility flashing) - switch(g->color) + switch (g->color) { - case GHC_SUPER: // Super Sonic (P_DoSuperStuff) - g->mo->color = SKINCOLOR_SUPER1; - g->mo->color += abs( ( (signed)( (unsigned)leveltime >> 1 ) % 9) - 4); - break; - case GHC_INVINCIBLE: // Mario invincibility (P_CheckInvincibilityTimer) - g->mo->color = (UINT8)(leveltime % MAXSKINCOLORS); - break; - default: - break; + case GHC_SUPER: // Super Sonic (P_DoSuperStuff) + g->mo->color = SKINCOLOR_SUPER1; + g->mo->color += abs( ( (signed)( (unsigned)leveltime >> 1 ) % 9) - 4); + break; + case GHC_INVINCIBLE: // Mario invincibility (P_CheckInvincibilityTimer) + g->mo->color = (UINT8)(leveltime % MAXSKINCOLORS); + break; + default: + break; } // Demo ends after ghost data. if (*g->p == DEMOMARKER) { g->mo->momx = g->mo->momy = g->mo->momz = 0; + if (p) p->next = g->next; else ghosts = g->next; + Z_Free(g); continue; } + p = g; } } @@ -1399,6 +1440,7 @@ void G_StoreRewindInfo(void) if (timetolog-- > 0) return; + timetolog = 8; info = Z_Calloc(sizeof(rewindinfo_t), PU_STATIC, NULL); @@ -1413,6 +1455,7 @@ void G_StoreRewindInfo(void) info->playerinfo[i].ingame = true; memcpy(&info->playerinfo[i].player, &players[i], sizeof(player_t)); + if (players[i].mo) memcpy(&info->playerinfo[i].mobj, players[i].mo, sizeof(mobj_t)); } @@ -1437,10 +1480,10 @@ void G_PreviewRewind(tic_t previewtime) next_info = info; info = info->prev; } + if (info != next_info) tweenvalue = FixedDiv(previewtime - info->leveltime, next_info->leveltime - info->leveltime); - for (i = 0; i < MAXPLAYERS; i++) { if (!playeringame[i] || players[i].spectator) @@ -1481,6 +1524,7 @@ void G_PreviewRewind(tic_t previewtime) players[i].mo->frame = info->playerinfo[i].mobj.frame; players[i].realtime = info->playerinfo[i].player.realtime; + for (j = 0; j < NUMKARTSTUFF; j++) players[i].kartstuff[j] = info->playerinfo[i].player.kartstuff[j]; } @@ -1669,10 +1713,13 @@ void G_BeginRecording(void) demobuf.p += 1; totalfiles = 0; - for (i = mainwads; ++i < numwadfiles; ) - if (wadfiles[i]->important) + + for (i = mainwads; ++i < numwadfiles;) { - nameonly(( filename = va("%s", wadfiles[i]->filename) )); + if (!wadfiles[i]->important) + continue; + + nameonly((filename = va("%s", wadfiles[i]->filename))); WRITESTRINGL(demobuf.p, filename, MAX_WADPATH); WRITEMEM(demobuf.p, wadfiles[i]->md5sum, 16); @@ -1681,17 +1728,17 @@ void G_BeginRecording(void) WRITEUINT8(m, totalfiles); - switch ((demoflags & DF_ATTACKMASK)>>DF_ATTACKSHIFT) + switch ((demoflags & DF_ATTACKMASK) >> DF_ATTACKSHIFT) { - case ATTACKING_NONE: // 0 - break; - case ATTACKING_RECORD: // 1 - demotime_p = demobuf.p; - WRITEUINT32(demobuf.p,UINT32_MAX); // time - WRITEUINT32(demobuf.p,UINT32_MAX); // lap - break; - default: // 3 - break; + case ATTACKING_NONE: // 0 + break; + case ATTACKING_RECORD: // 1 + demotime_p = demobuf.p; + WRITEUINT32(demobuf.p,UINT32_MAX); // time + WRITEUINT32(demobuf.p,UINT32_MAX); // lap + break; + default: // 3 + break; } WRITEUINT32(demobuf.p, P_GetInitSeed()); @@ -1810,6 +1857,7 @@ void G_SetDemoTime(UINT32 ptime, UINT32 plap) { if (!demo.recording || !demotime_p) return; + if (demoflags & DF_RECORDATTACK) { WRITEUINT32(demotime_p, ptime); @@ -1828,7 +1876,8 @@ static void G_LoadDemoExtraFiles(UINT8 **pp) boolean alreadyloaded; UINT8 i, j; - totalfiles = READUINT8((*pp)); + totalfiles = READUINT8((*pp)); // i like pp uwu + for (i = 0; i < totalfiles; ++i) { if (toomany) @@ -1838,6 +1887,7 @@ static void G_LoadDemoExtraFiles(UINT8 **pp) strlcpy(filename, (char *)(*pp), sizeof filename); SKIPSTRING((*pp)); } + READMEM((*pp), md5sum, 16); if (!toomany) @@ -1917,6 +1967,7 @@ static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick) totalfiles = READUINT8((*pp)); filesloaded = 0; + for (i = 0; i < totalfiles; ++i) { if (toomany) @@ -1926,7 +1977,8 @@ static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick) strlcpy(filename, (char *)(*pp), sizeof filename); SKIPSTRING((*pp)); } - READMEM((*pp), md5sum, 16); + + READMEM((*pp), md5sum, 16); // hue hue peepee if (!toomany) { @@ -1971,8 +2023,10 @@ static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick) nmusfilecount = 0; for (j = 0; j < numwadfiles; ++j) + { if (wadfiles[j]->important && j > mainwads) nmusfilecount++; + } if (!error && filesloaded < nmusfilecount) error = DFILE_ERROR_EXTRAFILES; @@ -1986,7 +2040,8 @@ static UINT8 G_CheckDemoExtraFiles(UINT8 **pp, boolean quick) // 4 == new demo has higher rings UINT8 G_CmpDemoTime(char *oldname, char *newname) { - UINT8 *buffer,*p; + CLEANUP(Z_Pfree) UINT8 *buffer = NULL; + UINT8 *p; UINT8 flags; UINT32 oldtime, newtime, oldlap, newlap; UINT16 oldversion; @@ -2018,10 +2073,12 @@ UINT8 G_CmpDemoTime(char *oldname, char *newname) p += 16; // map md5 flags = READUINT8(p); // demoflags p++; // gametype + G_SkipDemoExtraFiles(&p); aflags = flags & (DF_RECORDATTACK|DF_NIGHTSATTACK); I_Assert(aflags); + if (flags & DF_RECORDATTACK) { newtime = READUINT32(p); @@ -2031,62 +2088,69 @@ UINT8 G_CmpDemoTime(char *oldname, char *newname) return 0; Z_Free(buffer); + buffer = NULL; // load old file FIL_DefaultExtension(oldname, ".lmp"); + if (!FIL_ReadFile(oldname, &buffer)) { CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), oldname); return UINT8_MAX; } + p = buffer; // read demo header if (memcmp(p, DEMOHEADER, 12)) { CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname); - Z_Free(buffer); return UINT8_MAX; - } p += 12; // DEMOHEADER + } + + p += 12; // DEMOHEADER p++; // VERSION p++; // SUBVERSION oldversion = READUINT16(p); - switch(oldversion) // demoversion + + switch (oldversion) // demoversion { - case DEMOVERSION: // latest always supported - p += 64; // full demo title - break; -#ifdef DEMO_COMPAT_100 - case 0x0001: - // Old replays gotta go :] - CONS_Alert(CONS_NOTICE, M_GetText("File '%s' outdated version. It will be overwritten. Nyeheheh.\n"), oldname); - Z_Free(buffer); - return UINT8_MAX; + case DEMOVERSION: // latest always supported + p += 64; // full demo title + break; + #ifdef DEMO_COMPAT_100 + case 0x0001: + // Old replays gotta go :] + CONS_Alert(CONS_NOTICE, M_GetText("File '%s' outdated version. It will be overwritten. Nyeheheh.\n"), oldname); + return UINT8_MAX; #endif - // too old, cannot support. - default: - CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname); - Z_Free(buffer); - return UINT8_MAX; + // too old, cannot support. + default: + CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname); + return UINT8_MAX; } + p += 16; // demo checksum + if (memcmp(p, "PLAY", 4)) { CONS_Alert(CONS_NOTICE, M_GetText("File '%s' invalid format. It will be overwritten.\n"), oldname); - Z_Free(buffer); return UINT8_MAX; - } p += 4; // "PLAY" + } + + p += 4; // "PLAY" p += 2; // gamemap p += 16; // mapmd5 flags = READUINT8(p); p++; // gametype G_SkipDemoExtraFiles(&p); + if (!(flags & aflags)) { CONS_Alert(CONS_NOTICE, M_GetText("File '%s' not from same game mode. It will be overwritten.\n"), oldname); - Z_Free(buffer); return UINT8_MAX; } + if (flags & DF_RECORDATTACK) { oldtime = READUINT32(p); @@ -2095,21 +2159,23 @@ UINT8 G_CmpDemoTime(char *oldname, char *newname) else // appease compiler return UINT8_MAX; - Z_Free(buffer); - c = 0; + if (newtime < oldtime || (newtime == oldtime && (newlap < oldlap))) c |= 1; // Better time + if (newlap < oldlap || (newlap == oldlap && newtime < oldtime)) c |= 1<<1; // Better lap time + return c; } void G_LoadDemoInfo(menudemo_t *pdemo) { - UINT8 *infobuffer, *info_p, *extrainfo_p; + UINT8 *info_p, *extrainfo_p; + CLEANUP(Z_Pfree) UINT8 *infobuffer = NULL; UINT8 version, subversion, pdemoflags; UINT16 pdemoversion, count; @@ -2118,7 +2184,6 @@ void G_LoadDemoInfo(menudemo_t *pdemo) CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), pdemo->filepath); pdemo->type = MD_INVALID; sprintf(pdemo->title, "INVALID REPLAY"); - return; } @@ -2129,7 +2194,6 @@ void G_LoadDemoInfo(menudemo_t *pdemo) CONS_Alert(CONS_ERROR, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemo->filepath); pdemo->type = MD_INVALID; sprintf(pdemo->title, "INVALID REPLAY"); - Z_Free(infobuffer); return; } @@ -2144,41 +2208,40 @@ void G_LoadDemoInfo(menudemo_t *pdemo) memset(pdemo->version, 0, sizeof(pdemo->version)); snprintf(pdemo->version, sizeof(pdemo->version), "v%d.%d", version, subversion); - switch(pdemoversion) + switch (pdemoversion) { - case DEMOVERSION: // latest always supported - // demo title - M_Memcpy(pdemo->title, info_p, 64); - info_p += 64; - - break; + case DEMOVERSION: // latest always supported + // demo title + M_Memcpy(pdemo->title, info_p, 64); + info_p += 64; + break; #ifdef DEMO_COMPAT_100 - case 0x0001: - pdemo->type = MD_OUTDATED; - sprintf(pdemo->title, "Legacy Replay"); - break; + case 0x0001: + pdemo->type = MD_OUTDATED; + sprintf(pdemo->title, "Legacy Replay"); + break; #endif - // too old, cannot support. - default: - CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); - pdemo->type = MD_INVALID; - sprintf(pdemo->title, "INVALID REPLAY"); - Z_Free(infobuffer); - return; + // too old, cannot support. + default: + CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); + pdemo->type = MD_INVALID; + sprintf(pdemo->title, "INVALID REPLAY"); + return; } if (version != VERSION || subversion != SUBVERSION) pdemo->type = MD_OUTDATED; info_p += 16; // demo checksum + if (memcmp(info_p, "PLAY", 4)) { CONS_Alert(CONS_ERROR, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemo->filepath); pdemo->type = MD_INVALID; sprintf(pdemo->title, "INVALID REPLAY"); - Z_Free(infobuffer); return; } + info_p += 4; // "PLAY" pdemo->map = READINT16(info_p); info_p += 16; // mapmd5 @@ -2189,7 +2252,6 @@ void G_LoadDemoInfo(menudemo_t *pdemo) if (!(pdemoflags & DF_MULTIPLAYER)) { CONS_Alert(CONS_ERROR, M_GetText("%s is not a multiplayer replay and can't be listed on this menu fully yet.\n"), pdemo->filepath); - Z_Free(infobuffer); return; } #ifdef DEMO_COMPAT_100 @@ -2198,7 +2260,6 @@ void G_LoadDemoInfo(menudemo_t *pdemo) CONS_Alert(CONS_ERROR, M_GetText("%s is a legacy multiplayer replay and cannot be played.\n"), pdemo->filepath); pdemo->type = MD_INVALID; sprintf(pdemo->title, "INVALID REPLAY"); - Z_Free(infobuffer); return; } #endif @@ -2213,6 +2274,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) // Pared down version of CV_LoadNetVars to find the kart speed pdemo->kartspeed = 1; // Default to normal speed count = READUINT16(info_p); + while (count--) { UINT16 netid; @@ -2225,10 +2287,11 @@ void G_LoadDemoInfo(menudemo_t *pdemo) if (netid == cv_kartspeed.netid) { - UINT8 j; - for (j = 0; kartspeed_cons_t[j].strvalue; j++) + for (UINT8 j = 0; kartspeed_cons_t[j].strvalue; j++) + { if (!stricmp(kartspeed_cons_t[j].strvalue, svalue)) pdemo->kartspeed = kartspeed_cons_t[j].value; + } } else if (netid == cv_basenumlaps.netid && pdemo->gametype == GT_RACE) pdemo->numlaps = atoi(svalue); @@ -2255,22 +2318,28 @@ void G_LoadDemoInfo(menudemo_t *pdemo) M_Memcpy(temp,extrainfo_p,16); extrainfo_p += 16; pdemo->standings[count].skin = UINT8_MAX; + for (i = 0; i < numskins; i++) + { if (stricmp(skins[i].name, temp) == 0) { pdemo->standings[count].skin = i; break; } + } // Color M_Memcpy(temp,extrainfo_p,16); extrainfo_p += 16; + for (i = 0; i < MAXSKINCOLORS; i++) + { if (!stricmp(KartColor_Names[i],temp)) // SRB2kart { pdemo->standings[count].color = i; break; } + } // Score/time/whatever pdemo->standings[count].timeorscore = READUINT32(extrainfo_p); @@ -2282,7 +2351,6 @@ void G_LoadDemoInfo(menudemo_t *pdemo) } // I think that's everything we need? - Z_Free(infobuffer); } #if defined (_WIN32) @@ -2422,28 +2490,30 @@ void G_LoadDemoTitle(menudemo_t *pdemo) memset(pdemo->date, 0, sizeof(pdemo->date)); - switch(pdemoversion) + switch (pdemoversion) { - case DEMOVERSION: // latest always supported - // demo title - M_Memcpy(pdemo->title, info_p, 64); + case DEMOVERSION: // latest always supported + // demo title + M_Memcpy(pdemo->title, info_p, 64); - // demo date - char *demodate; - demodate = G_GetDemoDate(pdemo); - if (demodate) - strncpy(pdemo->date, demodate, sizeof(pdemo->date)); - free(demodate); - break; + // demo date + char *demodate; + demodate = G_GetDemoDate(pdemo); + + if (demodate) + strncpy(pdemo->date, demodate, sizeof(pdemo->date)); + + free(demodate); + break; #ifdef DEMO_COMPAT_100 - case 0x0001: - sprintf(pdemo->title, "Legacy Replay"); - break; + case 0x0001: + sprintf(pdemo->title, "Legacy Replay"); + break; #endif - // too old, cannot support. - default: - CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); - sprintf(pdemo->title, "INVALID REPLAY"); + // too old, cannot support. + default: + CONS_Alert(CONS_ERROR, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemo->filepath); + sprintf(pdemo->title, "INVALID REPLAY"); } } @@ -2465,8 +2535,9 @@ void G_DoPlayDemo(char *defdemoname) { UINT8 i, p; lumpnum_t l; - char skin[17],color[17],*n,*pdemoname; - UINT8 version,subversion; + char skin[17], color[17], *n; + CLEANUP(Z_Pfree) char *pdemoname; + UINT8 version, subversion; UINT32 randseed; char msg[1024]; #if defined(SKIPERRORS) && !defined(DEVELOP) @@ -2488,11 +2559,13 @@ void G_DoPlayDemo(char *defdemoname) } else { - n = defdemoname+strlen(defdemoname); + n = defdemoname + strlen(defdemoname); + while (*n != '/' && *n != '\\' && n != defdemoname) n--; if (n != defdemoname) n++; + pdemoname = ZZ_Alloc(strlen(n)+1); strcpy(pdemoname,n); @@ -2510,6 +2583,7 @@ void G_DoPlayDemo(char *defdemoname) M_StartMessage(msg, NULL, MM_NOTHING); return; } + demobuf.p = demobuf.buffer; } // load demo resource from WAD @@ -2533,53 +2607,58 @@ void G_DoPlayDemo(char *defdemoname) // read demo header gameaction = ga_nothing; demo.playback = true; + if (memcmp(demobuf.p, DEMOHEADER, 12)) { snprintf(msg, 1024, M_GetText("%s is not a SRB2Kart replay file.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } + demobuf.p += 12; // DEMOHEADER version = READUINT8(demobuf.p); subversion = READUINT8(demobuf.p); demo.version = READUINT16(demobuf.p); - switch(demo.version) - { - case DEMOVERSION: // latest always supported - // demo title - M_Memcpy(demo.titlename, demobuf.p, 64); - demobuf.p += 64; - break; + switch (demo.version) + { + case DEMOVERSION: // latest always supported + // demo title + M_Memcpy(demo.titlename, demobuf.p, 64); + demobuf.p += 64; + break; #ifdef DEMO_COMPAT_100 - case 0x0001: - break; + case 0x0001: + break; #endif - // too old, cannot support. - default: - snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname); - CONS_Alert(CONS_ERROR, "%s", msg); - M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); - return; + // too old, cannot support. + default: + snprintf(msg, 1024, M_GetText("%s is an incompatible replay format and cannot be played.\n"), pdemoname); + CONS_Alert(CONS_ERROR, "%s", msg); + M_StartMessage(msg, NULL, MM_NOTHING); + G_ResetDemoPlayback(); + return; } + demobuf.p += 16; // demo checksum + if (memcmp(demobuf.p, "PLAY", 4)) { snprintf(msg, 1024, M_GetText("%s is the wrong type of recording and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } + demobuf.p += 4; // "PLAY" gamemap = READINT16(demobuf.p); demobuf.p += 16; // mapmd5 - demoflags = READUINT8(demobuf.p); + #ifdef DEMO_COMPAT_100 if (demo.version == 0x0001) { @@ -2588,7 +2667,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is an alpha multiplayer replay and cannot be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } } @@ -2611,41 +2690,43 @@ void G_DoPlayDemo(char *defdemoname) { switch (error) { - case DFILE_ERROR_NOTLOADED: - snprintf(msg, 1024, - M_GetText("Required files for this demo are not loaded.\n\nUse\n\"playdemo %s -addfiles\"\nto load them and play the demo.\n"), - pdemoname); - break; + case DFILE_ERROR_NOTLOADED: + snprintf(msg, 1024, + "Required files for this demo are not loaded.\n\nUse\n\"playdemo %s -addfiles\"\nto load them and play the demo.\n", + pdemoname); + break; - case DFILE_ERROR_OUTOFORDER: - snprintf(msg, 1024, - M_GetText("Required files for this demo are loaded out of order.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"), - pdemoname); - break; + case DFILE_ERROR_OUTOFORDER: + snprintf(msg, 1024, + "Required files for this demo are loaded out of order.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", + pdemoname); + break; - case DFILE_ERROR_INCOMPLETEOUTOFORDER: - snprintf(msg, 1024, - M_GetText("Required files for this demo are not loaded, and some are out of order.\n\nUse\n\"playdemo %s -addfiles\"\nto load needed files and play the demo.\n"), - pdemoname); - break; + case DFILE_ERROR_INCOMPLETEOUTOFORDER: + snprintf(msg, 1024, + "Required files for this demo are not loaded, and some are out of order.\n\nUse\n\"playdemo %s -addfiles\"\nto load needed files and play the demo.\n", + pdemoname); + break; - case DFILE_ERROR_CANNOTLOAD: - snprintf(msg, 1024, - M_GetText("Required files for this demo cannot be loaded.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"), - pdemoname); - break; + case DFILE_ERROR_CANNOTLOAD: + snprintf(msg, 1024, + "Required files for this demo cannot be loaded.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", + pdemoname); + break; - case DFILE_ERROR_EXTRAFILES: - snprintf(msg, 1024, - M_GetText("You have additional files loaded beyond the demo's file list.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n"), - pdemoname); - break; + case DFILE_ERROR_EXTRAFILES: + snprintf(msg, 1024, + "You have additional files loaded beyond the demo's file list.\n\nUse\n\"playdemo %s -force\"\nto play the demo anyway.\n", + pdemoname); + break; } CONS_Alert(CONS_ERROR, "%s", msg); + if (!CON_Ready()) // In the console they'll just see the notice there! No point pulling them out. M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + + G_ResetDemoPlayback(); return; } } @@ -2662,19 +2743,20 @@ void G_DoPlayDemo(char *defdemoname) switch (modeattacking) { - case ATTACKING_NONE: // 0 - break; - case ATTACKING_RECORD: // 1 - hu_demotime = READUINT32(demobuf.p); - hu_demolap = READUINT32(demobuf.p); - break; - default: // 3 - modeattacking = ATTACKING_NONE; - break; + case ATTACKING_NONE: // 0 + break; + case ATTACKING_RECORD: // 1 + hu_demotime = READUINT32(demobuf.p); + hu_demolap = READUINT32(demobuf.p); + break; + default: // 3 + modeattacking = ATTACKING_NONE; + break; } // Random seed randseed = READUINT32(demobuf.p); + #ifdef DEMO_COMPAT_100 if (demo.version != 0x0001) #endif @@ -2708,7 +2790,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s features a character that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } @@ -2718,17 +2800,19 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s features a course that is not currently loaded.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } // Set color for (i = 0; i < MAXSKINCOLORS; i++) + { if (!stricmp(KartColor_Names[i],color)) // SRB2kart { players[0].skincolor = i; break; } + } // net var data CV_LoadNetVars(&demobuf.p); @@ -2739,12 +2823,10 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } - Z_Free(pdemoname); - memset(&oldcmd,0,sizeof(oldcmd)); memset(&oldghost,0,sizeof(oldghost)); memset(&ghostext,0,sizeof(ghostext)); @@ -2779,15 +2861,13 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s contains no data to be played.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } - Z_Free(pdemoname); - - memset(&oldcmd,0,sizeof(oldcmd)); - memset(&oldghost,0,sizeof(oldghost)); - memset(&ghostext,0,sizeof(ghostext)); + memset(&oldcmd, 0, sizeof(oldcmd)); + memset(&oldghost, 0, sizeof(oldghost)); + memset(&ghostext, 0, sizeof(ghostext)); #if defined(SKIPERRORS) && !defined(DEVELOP) if ((VERSION != version || SUBVERSION != subversion) && !skiperrors) @@ -2819,6 +2899,7 @@ void G_DoPlayDemo(char *defdemoname) while (p != 0xFF) { spectator = false; + if (p & DEMO_SPECTATOR) { spectator = true; @@ -2829,10 +2910,11 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with spectators, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } } + slots[numslots] = p; numslots++; if (modeattacking && numslots > 1) @@ -2840,7 +2922,7 @@ void G_DoPlayDemo(char *defdemoname) snprintf(msg, 1024, M_GetText("%s is a Record Attack replay with multiple players, and is thus invalid.\n"), pdemoname); CONS_Alert(CONS_ERROR, "%s", msg); M_StartMessage(msg, NULL, MM_NOTHING); - G_ResetDemoPlayback(pdemoname); + G_ResetDemoPlayback(); return; } @@ -2862,12 +2944,15 @@ void G_DoPlayDemo(char *defdemoname) // Color M_Memcpy(color,demobuf.p,16); demobuf.p += 16; + for (i = 0; i < MAXSKINCOLORS; i++) + { if (!stricmp(KartColor_Names[i],color)) // SRB2kart { players[p].skincolor = i; break; } + } // Score, since Kart uses this to determine where you start on the map players[p].score = READUINT32(demobuf.p); @@ -2885,9 +2970,9 @@ void G_DoPlayDemo(char *defdemoname) // end of player read (the 0xFF marker) // so this is where we are to read our lua variables (if possible!) - if (demoflags & DF_LUAVARS) // again, used for compability, lua shit will be saved to replays regardless of if it's even been loaded + if (demoflags & DF_LUAVARS) // again, used for compability, lua shit will be saved to replays regardless of if it's even been loaded { - if (!gL) // No Lua state! ...I guess we'll just start one... + if (!gL) // No Lua state! ...I guess we'll just start one... LUA_ClearState(); // No modeattacking check, DF_LUAVARS won't be present here. @@ -2942,10 +3027,12 @@ void G_AddGhost(char *defdemoname) { INT32 i; lumpnum_t l; - char name[17],skin[17],color[17],*n,*pdemoname,md5[16]; + char name[17], skin[17], color[17], *n, md5[16]; + CLEANUP(Z_Pfree) char *pdemoname = NULL; demoghost *gh; + UINT8 *p; UINT8 flags; - UINT8 *buffer,*p; + CLEANUP(Z_Pfree) UINT8 *buffer = NULL; mapthing_t *mthing; UINT16 count, ghostversion; skin_t *ghskin = &skins[0]; @@ -2955,13 +3042,15 @@ void G_AddGhost(char *defdemoname) skin[16] = '\0'; color[16] = '\0'; - n = defdemoname+strlen(defdemoname); + n = defdemoname + strlen(defdemoname); + while (*n != '/' && *n != '\\' && n != defdemoname) n--; if (n != defdemoname) n++; + pdemoname = ZZ_Alloc(strlen(n)+1); - strcpy(pdemoname,n); + strcpy(pdemoname, n); // Internal if no extension, external if one exists if (FIL_CheckExtension(defdemoname)) @@ -2970,16 +3059,15 @@ void G_AddGhost(char *defdemoname) if (!FIL_ReadFileTag(defdemoname, &buffer, PU_LEVEL)) { CONS_Alert(CONS_ERROR, M_GetText("Failed to read file '%s'.\n"), defdemoname); - Z_Free(pdemoname); return; } + p = buffer; } // load demo resource from WAD else if ((l = W_CheckNumForName(defdemoname)) == LUMPERROR) { CONS_Alert(CONS_ERROR, M_GetText("Failed to read lump '%s'.\n"), defdemoname); - Z_Free(pdemoname); return; } else // it's an internal demo @@ -2989,8 +3077,6 @@ void G_AddGhost(char *defdemoname) if (memcmp(p, DEMOHEADER, 12)) { CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Not a SRB2Kart replay.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); return; } @@ -2999,38 +3085,36 @@ void G_AddGhost(char *defdemoname) p++; // SUBVERSION ghostversion = READUINT16(p); - switch(ghostversion) + + switch (ghostversion) { - case DEMOVERSION: // latest always supported - p += 64; // title - break; + case DEMOVERSION: // latest always supported + p += 64; // title + break; #ifdef DEMO_COMPAT_100 - case 0x0001: - break; + case 0x0001: + break; #endif - // too old, cannot support. - default: - CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo version incompatible.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); - return; + // too old, cannot support. + default: + CONS_Alert(CONS_NOTICE, "Ghost %s: Demo version incompatible.\n", pdemoname); + return; } M_Memcpy(md5, p, 16); p += 16; // demo checksum + for (gh = ghosts; gh; gh = gh->next) + { if (!memcmp(md5, gh->checksum, 16)) // another ghost in the game already has this checksum? { // Don't add another one, then! CONS_Debug(DBG_SETUP, "Rejecting duplicate ghost %s (MD5 was matched)\n", pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); return; } + } if (memcmp(p, "PLAY", 4)) { - CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: Demo format unacceptable.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); + CONS_Alert(CONS_NOTICE, "Ghost %s: Demo format unacceptable.\n", pdemoname); return; } @@ -3042,9 +3126,7 @@ void G_AddGhost(char *defdemoname) if (!(flags & DF_GHOST)) { - CONS_Alert(CONS_NOTICE, M_GetText("Ghost %s: No ghost data in this demo.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); + CONS_Alert(CONS_NOTICE, "Ghost %s: No ghost data in this demo.\n", pdemoname); return; } @@ -3057,15 +3139,16 @@ void G_AddGhost(char *defdemoname) if (ghostversion != 0x0001) #endif G_SkipDemoExtraFiles(&p); // Don't wanna modify the file list for ghosts. - switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT) + + switch ((flags & DF_ATTACKMASK) >> DF_ATTACKSHIFT) { - case ATTACKING_NONE: // 0 - break; - case ATTACKING_RECORD: // 1 - p += 8; // demo time, lap - break; - default: // 3 - break; + case ATTACKING_NONE: // 0 + break; + case ATTACKING_RECORD: // 1 + p += 8; // demo time, lap + break; + default: // 3 + break; } p += 4; // random seed @@ -3118,8 +3201,6 @@ void G_AddGhost(char *defdemoname) if (*p == DEMOMARKER) { CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Replay is empty.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); return; } @@ -3130,8 +3211,6 @@ void G_AddGhost(char *defdemoname) if (READUINT8(p) != 0) { CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); return; } @@ -3155,8 +3234,6 @@ void G_AddGhost(char *defdemoname) if (READUINT8(p) != 0xFF) { CONS_Alert(CONS_NOTICE, M_GetText("Failed to add ghost %s: Invalid player slot.\n"), pdemoname); - Z_Free(pdemoname); - Z_Free(buffer); return; } #ifdef DEMO_COMPAT_100 @@ -3164,11 +3241,13 @@ void G_AddGhost(char *defdemoname) #endif for (i = 0; i < numskins; i++) + { if (!stricmp(skins[i].name,skin)) { ghskin = &skins[i]; break; } + } if (i == numskins) { @@ -3183,21 +3262,26 @@ void G_AddGhost(char *defdemoname) gh->buffer = buffer; M_Memcpy(gh->checksum, md5, 16); gh->p = p; + buffer = NULL; // buffer can't be freed now! ghosts = gh; gh->version = ghostversion; mthing = playerstarts[0]; I_Assert(mthing); + { // A bit more complex than P_SpawnPlayer because ghosts aren't solid and won't just push themselves out of the ceiling. - fixed_t z,f,c; + fixed_t z, f, c; + gh->mo = P_SpawnMobj(mthing->x << FRACBITS, mthing->y << FRACBITS, 0, MT_GHOST); gh->mo->angle = FixedAngle(mthing->angle*FRACUNIT); f = gh->mo->floorz; c = gh->mo->ceilingz - mobjinfo[MT_PLAYER].height; + if (!!(mthing->options & MTF_AMBUSH) ^ !!(mthing->options & MTF_OBJECTFLIP)) { z = c; + if (mthing->options >> ZSHIFT) z -= ((mthing->options >> ZSHIFT) << FRACBITS); if (z < f) @@ -3206,13 +3290,16 @@ void G_AddGhost(char *defdemoname) else { z = f; + if (mthing->options >> ZSHIFT) z += ((mthing->options >> ZSHIFT) << FRACBITS); if (z > c) z = c; } + gh->mo->z = z; } + gh->mo->state = states+S_KART_STND1; // SRB2kart - was S_PLAY_STND gh->mo->sprite = gh->mo->state->sprite; gh->mo->frame = (gh->mo->state->frame & FF_FRAMEMASK) | tr_trans20<mo->color = ((skin_t*)gh->mo->skin)->prefcolor; + for (i = 0; i < MAXSKINCOLORS; i++) + { if (!stricmp(KartColor_Names[i],color)) // SRB2kart { gh->mo->color = (UINT8)i; break; } + } + gh->oldmo.color = gh->mo->color; CONS_Printf(M_GetText("Added ghost %s from %s\n"), name, pdemoname); - Z_Free(pdemoname); } // A simplified version of G_AddGhost... void G_UpdateStaffGhostName(lumpnum_t l) { - UINT8 *buffer,*p; + UINT8 *p; + CLEANUP(Z_Pfree) UINT8 *buffer = NULL; UINT16 ghostversion; UINT8 flags; @@ -3251,7 +3342,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) // read demo header if (memcmp(p, DEMOHEADER, 12)) { - goto fail; + return; } p += 12; // DEMOHEADER @@ -3259,27 +3350,25 @@ void G_UpdateStaffGhostName(lumpnum_t l) p++; // SUBVERSION ghostversion = READUINT16(p); - switch(ghostversion) + switch (ghostversion) { - case DEMOVERSION: // latest always supported - p += 64; // full demo title - break; - + case DEMOVERSION: // latest always supported + p += 64; // full demo title + break; #ifdef DEMO_COMPAT_100 - case 0x0001: - break; + case 0x0001: + break; #endif - - // too old, cannot support. - default: - goto fail; + // too old, cannot support. + default: + return; } p += 16; // demo checksum if (memcmp(p, "PLAY", 4)) { - goto fail; + return; } p += 4; // "PLAY" @@ -3289,7 +3378,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) flags = READUINT8(p); if (!(flags & DF_GHOST)) { - goto fail; // we don't NEED to do it here, but whatever + return; // we don't NEED to do it here, but whatever } #ifdef DEMO_COMPAT_100 @@ -3304,13 +3393,13 @@ void G_UpdateStaffGhostName(lumpnum_t l) switch ((flags & DF_ATTACKMASK)>>DF_ATTACKSHIFT) { - case ATTACKING_NONE: // 0 - break; - case ATTACKING_RECORD: // 1 - p += 8; // demo time, lap - break; - default: // 3 - break; + case ATTACKING_NONE: // 0 + break; + case ATTACKING_RECORD: // 1 + p += 8; // demo time, lap + break; + default: // 3 + break; } p += 4; // random seed @@ -3322,7 +3411,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) // Player name M_Memcpy(dummystaffname, p,16); dummystaffname[16] = '\0'; - goto fail; // Not really a failure but whatever + return; // Not really a failure but whatever } #endif @@ -3330,6 +3419,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) // Ehhhh don't need ghostversion here (?) so I'll reuse the var here ghostversion = READUINT16(p); + while (ghostversion--) { p += 2; @@ -3339,14 +3429,12 @@ void G_UpdateStaffGhostName(lumpnum_t l) // Assert first player is in and then read name if (READUINT8(p) != 0) - goto fail; - M_Memcpy(dummystaffname, p,16); + return; + + M_Memcpy(dummystaffname, p, 16); dummystaffname[16] = '\0'; // Ok, no longer any reason to care, bye -fail: - Z_Free(buffer); - return; } // @@ -3390,12 +3478,7 @@ void G_DoneLevelLoad(void) // called from stopdemo command, map command, and g_checkdemoStatus. void G_StopDemo(void) { - Z_Free(demobuf.buffer); - demobuf.buffer = NULL; - demo.playback = false; - if (demo.title) - modeattacking = ATTACKING_NONE; - demo.title = false; + G_ResetDemoPlayback(); demo.timing = false; singletics = false; @@ -3411,22 +3494,12 @@ void G_StopDemo(void) demo.rewinding = false; CL_ClearRewinds(); - if (gamestate == GS_LEVEL && rendermode != render_none) - { - V_SetPaletteLump("PLAYPAL"); // Reset the palette - R_ReInitColormaps(0, LUMPERROR); - } if (gamestate == GS_INTERMISSION) Y_EndIntermission(); // cleanup if (gamestate == GS_VOTING) Y_EndVote(); - M_ClearMenus(true); - - G_SetGamestate(GS_NULL); - wipegamestate = GS_NULL; - SV_StopServer(); - SV_ResetServer(); + D_ClearState(); } // Stops timing a demo. @@ -3518,9 +3591,8 @@ void G_ResetDemoRecording(void) demo.recording = false; } -static void G_ResetDemoPlayback(char *pdemoname) +static void G_ResetDemoPlayback(void) { - Z_Free(pdemoname); Z_Free(demobuf.buffer); demobuf.buffer = NULL; demo.playback = false; @@ -3569,7 +3641,8 @@ void G_SaveDemo(void) size_t i, strindex = 0; boolean dash = true; - for (i = 0; demo.titlename[i] && i < 127; i++) + //for (i = 0; demo.titlename[i] && i < 127; i++) ????? + for (i = 0; i < 64 && demo.titlename[i]; i++) { if ((demo.titlename[i] >= 'a' && demo.titlename[i] <= 'z') || (demo.titlename[i] >= '0' && demo.titlename[i] <= '9')) @@ -3584,7 +3657,7 @@ void G_SaveDemo(void) strindex++; dash = false; } - else if (!dash) + else if (strindex && !dash) { demo_slug[strindex] = '-'; strindex++; @@ -3592,12 +3665,24 @@ void G_SaveDemo(void) } } - demo_slug[strindex] = 0; - if (dash) demo_slug[strindex-1] = 0; + if (dash && strindex) + { + strindex--; + } + demo_slug[strindex] = '\0'; - writepoint = strstr(demoname, "-") + 1; - demo_slug[128 - (writepoint - demoname) - 4] = 0; - sprintf(writepoint, "%s.lmp", demo_slug); + if (demo_slug[0] != '\0') + { + // Slug is valid, write the chosen filename. + writepoint = strstr(demoname, "-"); + if (!writepoint) + return; + + writepoint++; + + size_t flen = 128 - (writepoint - demoname) - 4; + snprintf(writepoint, flen, "%s.lmp", demo_slug); + } } length = *(UINT32 *)demoinfo_p; diff --git a/src/g_demo.h b/src/g_demo.h index 36458b240..3ce32c054 100644 --- a/src/g_demo.h +++ b/src/g_demo.h @@ -67,7 +67,7 @@ typedef enum { } menudemotype_e; typedef struct menudemo_s { - char filepath[256]; + char filepath[1023 + 256]; // see M_PrepReplayList and sizeof menupath menudemotype_e type; char title[65]; // Null-terminated for string prints diff --git a/src/g_game.c b/src/g_game.c index 7470f3fc9..796c154d5 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -452,6 +452,13 @@ consvar_t cv_ydeadzone[MAXSPLITSCREENPLAYERS] = { {"joy4_ydeadzone", "0.5", CV_FLOAT|CV_SAVE, deadzone_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} }; +consvar_t cv_litesteer[MAXSPLITSCREENPLAYERS] = { + {"litesteer", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"litesteer2", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"litesteer3", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"litesteer4", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL} +}; + static CV_PossibleValue_t driftsparkpulse_t[] = {{0, "MIN"}, {FRACUNIT*3, "MAX"}, {0, NULL}}; consvar_t cv_driftsparkpulse = {"driftsparkpulse", "1.4", CV_FLOAT | CV_SAVE, driftsparkpulse_t, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -1014,8 +1021,8 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) else th = 0; - if (th < SLOWTURNTICS) - tspeed = cv_turnsmooth.value == 2 ? 2 : 0; // slow turn + if (th < (cv_turnsmooth[forplayer].value * 3)) + tspeed = cv_turnsmooth[forplayer].value == 2 ? 2 : 0; // slow turn else tspeed = 1; @@ -1024,30 +1031,32 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) // let movement keys cancel each other out if (turnright && !(turnleft)) { - cmd->angleturn = (INT16)(cmd->angleturn - (angleturn[tspeed])); - cmd->driftturn = (INT16)(cmd->driftturn - (angleturn[tspeed])); + cmd->angleturn -= angleturn[tspeed]; side += sidemove[1]; } else if (turnleft && !(turnright)) { - cmd->angleturn = (INT16)(cmd->angleturn + (angleturn[tspeed])); - cmd->driftturn = (INT16)(cmd->driftturn + (angleturn[tspeed])); + cmd->angleturn += angleturn[tspeed]; side -= sidemove[1]; } if (analogjoystickmove && axis != 0) { - // JOYAXISRANGE should be 1023 (divide by 1024) - cmd->angleturn = (INT16)(cmd->angleturn - (((axis * angleturn[1]) >> 10))); // ANALOG! - cmd->driftturn = (INT16)(cmd->driftturn - (((axis * angleturn[1]) >> 10))); - side += ((axis * sidemove[0]) >> 10); + cmd->angleturn -= (axis * KART_FULLTURN) / JOYAXISRANGE; + side += (axis * sidemove[0]) / JOYAXISRANGE; } if (cv_mouseturn.value) { //THIS WORKS WTF???????? - cmd->angleturn = (INT16)(cmd->angleturn - ((mousex*(encoremode ? -1 : 1)*8))); - cmd->driftturn = (INT16)(cmd->driftturn - ((mousex*(encoremode ? -1 : 1)*8))); + cmd->angleturn -= (mousex*(encoremode ? -1 : 1)*8); + } + + // Digital users can input diagonal-back for shallow turns. + if (cv_litesteer[forplayer].value && InputDown(gc_aimbackward, ssplayer) + && abs(cmd->angleturn) == KART_FULLTURN) // My keyboard hits 1024 but my keyboard only hits 1023, video games + { + cmd->angleturn /= 2; } if (objectplacing) // SRB2Kart: spectators need special controls // not anymore huehuehue @@ -1160,10 +1169,8 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) else if (cmd->angleturn < (-angleturn[1])) cmd->angleturn = (-angleturn[1]); - if (cmd->driftturn > (angleturn[1])) - cmd->driftturn = (angleturn[1]); - else if (cmd->driftturn < (-angleturn[1])) - cmd->driftturn = (-angleturn[1]); + // until here both are the very same + cmd->driftturn = cmd->angleturn; if (player->mo) cmd->angleturn = K_GetKartTurnValue(player, cmd->angleturn); @@ -4054,7 +4061,11 @@ char *G_BuildMapTitle(INT32 mapnum) title = Z_Malloc(len, PU_STATIC, NULL); + if (!title) + return NULL; + sprintf(title, "%s", mapheaderinfo[mapnum-1]->lvlttl); + if (zonetext) sprintf(title + strlen(title), " %s", zonetext); if (actnum) sprintf(title + strlen(title), " %s", actnum); } diff --git a/src/g_game.h b/src/g_game.h index 4812a2c1f..249ecbff1 100644 --- a/src/g_game.h +++ b/src/g_game.h @@ -72,6 +72,8 @@ extern consvar_t cv_custom3axis[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_xdeadzone[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_ydeadzone[MAXSPLITSCREENPLAYERS]; +extern consvar_t cv_litesteer[MAXSPLITSCREENPLAYERS]; + extern consvar_t cv_ghost_besttime, cv_ghost_bestlap, cv_ghost_last, cv_ghost_guest, cv_ghost_staff; // Hud offsets @@ -153,7 +155,6 @@ typedef enum // mouseaiming (looking up/down with the mouse or keyboard) #define KB_LOOKSPEED (1<<25) #define MAXPLMOVE (50) -#define SLOWTURNTICS (cv_turnsmooth.value * 3) // build an internal map name MAPxx from map number const char *G_BuildMapName(INT32 map); diff --git a/src/g_input.c b/src/g_input.c index 09ed3303a..e8bc8223e 100644 --- a/src/g_input.c +++ b/src/g_input.c @@ -37,7 +37,13 @@ static CV_PossibleValue_t turnsmooth_cons_t[] = {{2, "Slow"}, {1, "Fast"}, {0, " consvar_t cv_mousesens = {"mousesens", "20", CV_SAVE, mousesens_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_mouseysens = {"mouseysens", "20", CV_SAVE, mousesens_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_controlperkey = {"controlperkey", "One", CV_SAVE, onecontrolperkey_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_turnsmooth = {"turnsmoothing", "Slow", CV_SAVE, turnsmooth_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; + +consvar_t cv_turnsmooth[MAXSPLITSCREENPLAYERS] = { + {"turnsmoothing", "Slow", CV_SAVE, turnsmooth_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"turnsmoothing2", "Slow", CV_SAVE, turnsmooth_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"turnsmoothing3", "Slow", CV_SAVE, turnsmooth_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}, + {"turnsmoothing4", "Slow", CV_SAVE, turnsmooth_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL} +}; static void G_ResetPlayerDeviceRumble(INT32 player); static void rumble_off_handle(void); diff --git a/src/g_input.h b/src/g_input.h index 970560a35..ec4a9d795 100644 --- a/src/g_input.h +++ b/src/g_input.h @@ -110,7 +110,8 @@ typedef enum // mouse values are used once extern consvar_t cv_mousesens, cv_mouseysens; -extern consvar_t cv_controlperkey, cv_turnsmooth; +extern consvar_t cv_controlperkey; +extern consvar_t cv_turnsmooth[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_rumble[MAXSPLITSCREENPLAYERS]; extern consvar_t cv_gamepadled[MAXSPLITSCREENPLAYERS]; diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index e48e2772a..edbd83b77 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -804,7 +804,7 @@ static void HWR_PrecacheLevelSprites(void) void HWR_PrecacheLevel(void) { - if (rendermode != render_opengl) + if (gamestate != GS_LEVEL) return; // Precache flats. diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c index 2b8ace584..4797f21de 100644 --- a/src/hardware/hw_draw.c +++ b/src/hardware/hw_draw.c @@ -31,11 +31,6 @@ #include "../st_stuff.h" #include -#include "../i_video.h" // for rendermode != render_glide - -#ifndef O_BINARY -#define O_BINARY 0 -#endif typedef struct { @@ -51,75 +46,13 @@ typedef struct UINT8 image_descriptor; //18 } ATTRPACK TGAHeader; // sizeof is 18 -static UINT8 softwaretranstogl[11] = { 0, 25, 51, 76,102,127,153,178,204,229,255}; -static UINT8 softwaretranstogl_hi[11] = { 0, 51,102,153,204,255,255,255,255,255,255}; -static UINT8 softwaretranstogl_lo[11] = { 0, 12, 24, 36, 48, 60, 71, 83, 95,111,127}; +static const UINT8 softwaretranstogl[11] = { 0, 25, 51, 76,102,127,153,178,204,229,255}; +static const UINT8 softwaretranstogl_hi[11] = { 0, 51,102,153,204,255,255,255,255,255,255}; +static const UINT8 softwaretranstogl_lo[11] = { 0, 12, 24, 36, 48, 60, 71, 83, 95,111,127}; static const float FLOATBASEVIDWIDTH = (float)BASEVIDWIDTH; static const float FLOATBASEVIDHEIGHT = (float)BASEVIDHEIGHT; -// -// -----------------+ -// HWR_DrawPatch : Draw a 'tile' graphic -// Notes : x,y : positions relative to the original Doom resolution -// : textes(console+score) + menus + status bar -// -----------------+ -void HWR_DrawPatch(patch_t *gpatch, INT32 x, INT32 y, INT32 option) -{ - FOutVector v[4]; - FBITFIELD flags; - GLPatch_t *hwrPatch; - -// 3--2 -// | /| -// |/ | -// 0--1 - float sdup = FIXED_TO_FLOAT(vid.fdup)*2.0f; - float pdup = FIXED_TO_FLOAT(vid.fdup)*2.0f; - - // make patch ready in hardware cache - HWR_GetPatch(gpatch); - hwrPatch = ((GLPatch_t *)gpatch->hardware); - - switch (option & V_SCALEPATCHMASK) - { - case V_NOSCALEPATCH: - pdup = 2.0f; - break; - case V_SMALLSCALEPATCH: - pdup = 2.0f * FIXED_TO_FLOAT(vid.smalldup*FRACUNIT); - break; - case V_MEDSCALEPATCH: - pdup = 2.0f * FIXED_TO_FLOAT(vid.meddup*FRACUNIT); - break; - } - - if (option & V_NOSCALESTART) - sdup = 2.0f; - - v[0].x = v[3].x = (x*sdup-gpatch->leftoffset*pdup)/vid.width - 1; - v[2].x = v[1].x = (x*sdup+(gpatch->width - gpatch->leftoffset)*pdup)/vid.width - 1; - v[0].y = v[1].y = 1-(y*sdup-gpatch->topoffset*pdup)/vid.height; - v[2].y = v[3].y = 1-(y*sdup+(gpatch->height - gpatch->topoffset)*pdup)/vid.height; - - v[0].z = v[1].z = v[2].z = v[3].z = 1.0f; - - v[0].s = v[3].s = 0.0f; - v[2].s = v[1].s = hwrPatch->max_s; - v[0].t = v[1].t = 0.0f; - v[2].t = v[3].t = hwrPatch->max_t; - - flags = PF_Translucent|PF_NoDepthTest; - - if (option & V_WRAPX) - flags |= PF_ForceWrapX; - if (option & V_WRAPY) - flags |= PF_ForceWrapY; - - // clip it since it is used for bunny scroll in doom I - GL_DrawPolygon(NULL, v, 4, flags); -} - void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, fixed_t vscale, INT32 option, const UINT8 *colormap, INT32 bflags) { FOutVector v[4]; @@ -154,15 +87,15 @@ void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t p switch (option & V_SCALEPATCHMASK) { - case V_NOSCALEPATCH: - dup = 1.0f; - break; - case V_SMALLSCALEPATCH: - dup = (float)vid.smalldup; - break; - case V_MEDSCALEPATCH: - dup = (float)vid.meddup; - break; + case V_NOSCALEPATCH: + dup = 1.0f; + break; + case V_SMALLSCALEPATCH: + dup = (float)vid.smalldup; + break; + case V_MEDSCALEPATCH: + dup = (float)vid.meddup; + break; } fscalew = fscaleh = FIXED_TO_FLOAT(pscale); @@ -336,15 +269,15 @@ void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, switch (option & V_SCALEPATCHMASK) { - case V_NOSCALEPATCH: - dup = 1.0f; - break; - case V_SMALLSCALEPATCH: - dup = (float)vid.smalldup; - break; - case V_MEDSCALEPATCH: - dup = (float)vid.meddup; - break; + case V_NOSCALEPATCH: + dup = 1.0f; + break; + case V_SMALLSCALEPATCH: + dup = (float)vid.smalldup; + break; + case V_MEDSCALEPATCH: + dup = (float)vid.meddup; + break; } fscale = FIXED_TO_FLOAT(pscale); @@ -573,7 +506,7 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) if (color & 0xFF00) // Do COLORMAP fade. { - if (HWR_ShouldUsePaletteRendering() && cv_glscreentextures.value) + if (cv_glscreentextures.value && HWR_ShouldUsePaletteRendering()) { const hwdscreentexture_t scr_tex = HWD_SCREENTEXTURE_GENERIC2; @@ -585,12 +518,10 @@ void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength) GL_UnSetShader(); return; } - else - { - Surf.PolyColor.rgba = UINT2RGBA(0x01010160); - Surf.PolyColor.s.alpha = (strength*8); - poly_flags |= PF_Translucent; - } + + Surf.PolyColor.rgba = UINT2RGBA(0x01010160); + Surf.PolyColor.s.alpha = (strength*8); + poly_flags |= PF_Translucent; } else // Do TRANSMAP** fade. { @@ -636,133 +567,6 @@ void HWR_DrawConsoleBack(UINT32 color, INT32 height) } -// ========================================================================== -// R_DRAW.C STUFF -// ========================================================================== - -// ------------------ -// HWR_DrawViewBorder -// Fill the space around the view window with a Doom flat texture, draw the -// beveled edges. -// 'clearlines' is useful to clear the heads up messages, when the view -// window is reduced, it doesn't refresh all the view borders. -// ------------------ -void HWR_DrawViewBorder(INT32 clearlines) -{ - INT32 x, y; - INT32 top, side; - INT32 baseviewwidth, baseviewheight; - INT32 basewindowx, basewindowy; - patch_t *patch; - - if (!clearlines) - clearlines = BASEVIDHEIGHT; // refresh all - - // calc view size based on original game resolution - baseviewwidth = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_viewwidth), vid.fdup)); //(cv_viewsize.value * BASEVIDWIDTH/10)&~7; - baseviewheight = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_viewheight), vid.fdup)); - top = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_baseviewwindowy), vid.fdup)); - side = FixedInt(FixedDiv(FLOAT_TO_FIXED(gl_baseviewwindowx), vid.fdup)); - - // top - HWR_DrawFlatFill(0, 0, - BASEVIDWIDTH, (top < clearlines ? top : clearlines), - st_borderpatchnum); - - // left - if (top < clearlines) - HWR_DrawFlatFill(0, top, side, - (clearlines-top < baseviewheight ? clearlines-top : baseviewheight), - st_borderpatchnum); - - // right - if (top < clearlines) - HWR_DrawFlatFill(side + baseviewwidth, top, side, - (clearlines-top < baseviewheight ? clearlines-top : baseviewheight), - st_borderpatchnum); - - // bottom - if (top + baseviewheight < clearlines) - HWR_DrawFlatFill(0, top + baseviewheight, - BASEVIDWIDTH, BASEVIDHEIGHT, st_borderpatchnum); - - // - // draw the view borders - // - - basewindowx = (BASEVIDWIDTH - baseviewwidth)>>1; - if (baseviewwidth == BASEVIDWIDTH) - basewindowy = 0; - else - basewindowy = top; - - // top edge - if (clearlines > basewindowy - 8) - { - patch = W_CachePatchNum(viewborderlump[BRDR_T], PU_PATCH); - for (x = 0; x < baseviewwidth; x += 8) - HWR_DrawPatch(patch, basewindowx + x, basewindowy - 8, - 0); - } - - // bottom edge - if (clearlines > basewindowy + baseviewheight) - { - patch = W_CachePatchNum(viewborderlump[BRDR_B], PU_PATCH); - for (x = 0; x < baseviewwidth; x += 8) - HWR_DrawPatch(patch, basewindowx + x, - basewindowy + baseviewheight, 0); - } - - // left edge - if (clearlines > basewindowy) - { - patch = W_CachePatchNum(viewborderlump[BRDR_L], PU_PATCH); - for (y = 0; y < baseviewheight && basewindowy + y < clearlines; - y += 8) - { - HWR_DrawPatch(patch, basewindowx - 8, basewindowy + y, - 0); - } - } - - // right edge - if (clearlines > basewindowy) - { - patch = W_CachePatchNum(viewborderlump[BRDR_R], PU_PATCH); - for (y = 0; y < baseviewheight && basewindowy+y < clearlines; - y += 8) - { - HWR_DrawPatch(patch, basewindowx + baseviewwidth, - basewindowy + y, 0); - } - } - - // Draw beveled corners. - if (clearlines > basewindowy - 8) - HWR_DrawPatch(W_CachePatchNum(viewborderlump[BRDR_TL], - PU_PATCH), - basewindowx - 8, basewindowy - 8, 0); - - if (clearlines > basewindowy - 8) - HWR_DrawPatch(W_CachePatchNum(viewborderlump[BRDR_TR], - PU_PATCH), - basewindowx + baseviewwidth, basewindowy - 8, 0); - - if (clearlines > basewindowy+baseviewheight) - HWR_DrawPatch(W_CachePatchNum(viewborderlump[BRDR_BL], - PU_PATCH), - basewindowx - 8, basewindowy + baseviewheight, 0); - - if (clearlines > basewindowy + baseviewheight) - HWR_DrawPatch(W_CachePatchNum(viewborderlump[BRDR_BR], - PU_PATCH), - basewindowx + baseviewwidth, - basewindowy + baseviewheight, 0); -} - - - // ========================================================================== // AM_MAP.C DRAWING STUFF // ========================================================================== @@ -1084,11 +888,13 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) if (fx >= vid.width || fy >= vid.height) return; + if (fx < 0) { fw += fx; fx = 0; } + if (fy < 0) { fh += fy; @@ -1100,6 +906,7 @@ void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color) if (fx + fw > vid.width) fw = fvw - fx; + if (fy + fh > vid.height) fh = fvh - fy; @@ -1168,7 +975,7 @@ static inline boolean saveTGA(const char *file_name, void *buffer, INT32 i; UINT8 *buf8 = buffer; - fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + fd = open(file_name, O_WRONLY | O_CREAT | O_TRUNC, 0666); if (fd < 0) return false; diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index c88b075a1..45f25c2a6 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -65,8 +65,6 @@ // Globals // ========================================================================== -#define ABS(x) ((x) < 0 ? -(x) : (x)) - // false if shaders have not been initialized yet, or if shaders are not available boolean gl_shadersavailable = false; @@ -77,11 +75,6 @@ boolean gl_drawing_stencil = false; static INT32 current_bsp_culling_distance = 0; -// base values set at SetViewSize -float gl_baseviewwindowy, gl_baseviewwindowx; -static float gl_viewwindowy, gl_viewwindowx; // top left corner of view window -float gl_viewwidth, gl_viewheight; // viewport clipping boundaries (screen coords) - FTransform atransform; // Float variants of viewx, viewy, viewz, etc. @@ -284,6 +277,7 @@ static void CV_glshaders_OnChange(void) { // can't do palette rendering without shaders, so update the state if needed HWR_TogglePaletteRendering(); + HWR_PrecacheLevel(); } M_UpdateOGLMenu(); } @@ -301,18 +295,21 @@ static void CV_gltextureformat_OnChange(void) { ONLY_IF_GL_LOADED GL_SetSpecialState(HWD_SET_TEXTURE_FORMAT, cv_gltexturedepth.value); + HWR_PrecacheLevel(); } static void CV_filtermode_OnChange(void) { ONLY_IF_GL_LOADED GL_SetSpecialState(HWD_SET_TEXTUREFILTERMODE, cv_glfiltermode.value); + HWR_PrecacheLevel(); } static void CV_anisotropic_OnChange(void) { ONLY_IF_GL_LOADED GL_SetSpecialState(HWD_SET_TEXTUREANISOTROPICMODE, cv_glanisotropicmode.value); + HWR_PrecacheLevel(); } static void CV_glpaletterendering_OnChange(void) @@ -325,7 +322,9 @@ static void CV_glpaletterendering_OnChange(void) { HWR_CompileShaders(); HWR_TogglePaletteRendering(); + HWR_PrecacheLevel(); } + M_UpdateOGLMenu(); } @@ -3377,6 +3376,9 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t fixed_t slopez; float offset = 0; + if (!spr->mobj) + return; + R_GetShadowZ(spr->mobj, &floorslope); mobjfloor = HWR_OpaqueFloorAtPos( @@ -3388,14 +3390,7 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t angle_t shadowdir; // Set direction - if (splitscreen && R_GetViewNumber() == 1) - shadowdir = localangle[1] + FixedAngle(cv_cam_rotate[1].value); - else if (splitscreen > 1 && R_GetViewNumber() == 2) - shadowdir = localangle[2] + FixedAngle(cv_cam_rotate[2].value); - else if (splitscreen > 2 && R_GetViewNumber() == 3) - shadowdir = localangle[3] + FixedAngle(cv_cam_rotate[3].value); - else - shadowdir = localangle[0] + FixedAngle(cv_cam_rotate[0].value); + shadowdir = localangle[viewssnum] + FixedAngle(cv_cam_rotate[viewssnum].value); // Find floorheight floorheight = HWR_OpaqueFloorAtPos( @@ -3407,18 +3402,17 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t // Don't draw it, then! if (spr->mobj->z < floorheight) return; - else - { - fixed_t floorz; - floorz = HWR_OpaqueFloorAtPos( - spr->mobj->x + P_ReturnThrustX(spr->mobj, shadowdir, spr->mobj->z - floorheight), - spr->mobj->y + P_ReturnThrustY(spr->mobj, shadowdir, spr->mobj->z - floorheight), - spr->mobj->z, spr->mobj->height); - // The shadow would be falling on a wall? Don't draw it, then. - // Would draw midair otherwise. - if (floorz < floorheight) - return; - } + + fixed_t floorz; + floorz = HWR_OpaqueFloorAtPos( + spr->mobj->x + P_ReturnThrustX(spr->mobj, shadowdir, spr->mobj->z - floorheight), + spr->mobj->y + P_ReturnThrustY(spr->mobj, shadowdir, spr->mobj->z - floorheight), + spr->mobj->z, spr->mobj->height); + + // The shadow would be falling on a wall? Don't draw it, then. + // Would draw midair otherwise. + if (floorz < floorheight) + return; floorheight = FixedInt(spr->mobj->z - floorheight); @@ -3428,12 +3422,11 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t floorheight = FixedInt(spr->mobj->z - mobjfloor); // technically this_scale gets multiplied and added to sprite y/x scale, but this thing needs it for some crap so ill just throw it in here again - const boolean hires = (spr->mobj && spr->mobj->skin && K_GetMobjSkin(spr->mobj)->flags & SF_HIRES); + this_scale = FixedToFloat(spr->mobj->scale); - if (spr->mobj) - this_scale = FixedToFloat(spr->mobj->scale); - if (hires) - this_scale = this_scale * FixedToFloat(K_GetMobjSkin(spr->mobj)->highresscale); + const skin_t *moskin = K_GetMobjSkin(spr->mobj); + if (moskin && moskin->flags & SF_HIRES) + this_scale *= FixedToFloat(moskin->highresscale); // create the sprite billboard // @@ -4054,7 +4047,7 @@ static void HWR_DrawPrecipitationSprite(gl_vissprite_t *spr) const precipmobj_t *sprmo = spr->precip; - if (UNLIKELY(!sprmo || !sprmo->subsector)) + if (UNLIKELY(!sprmo->subsector)) return; // cache sprite graphics @@ -4335,7 +4328,7 @@ static int CompareDrawNodePlanes(const void *p1, const void *p2) const INT32 n1 = *(const INT32*)p1; const INT32 n2 = *(const INT32*)p2; - return ABS(drawnodes[n2].u.plane.fixedheight - viewz) - ABS(drawnodes[n1].u.plane.fixedheight - viewz); + return abs(drawnodes[n2].u.plane.fixedheight - viewz) - abs(drawnodes[n1].u.plane.fixedheight - viewz); } // @@ -5316,10 +5309,10 @@ static void HWR_DrawSkyBackground(void) // -----------------+ static inline void HWR_ClearView(void) { - GL_GClipRect((INT32)gl_viewwindowx, - (INT32)gl_viewwindowy, - (INT32)(gl_viewwindowx + gl_viewwidth), - (INT32)(gl_viewwindowy + gl_viewheight), + GL_GClipRect(viewwindowx, + viewwindowy, + (viewwindowx + viewwidth), + (viewwindowy + viewheight), ZCLIP_PLANE, FAR_ZCLIP_DEFAULT); GL_ClearBuffer(false, true, true, NULL); } @@ -5329,19 +5322,6 @@ static inline void HWR_ClearView(void) // -----------------+ void HWR_SetViewSize(void) { - // setup view size - gl_viewwidth = (float)vid.width; - gl_viewheight = (float)vid.height; - - if (splitscreen) - gl_viewheight /= 2; - - if (splitscreen > 1) - gl_viewwidth /= 2; - - gl_baseviewwindowy = 0; - gl_baseviewwindowx = 0; - GL_FlushScreenTextures(); } @@ -5352,7 +5332,9 @@ static void HWR_SetTransformAiming(FTransform *trans) if (cv_glshearing.value) { fixed_t fixedaiming = AIMINGTODY(aimingangle); - trans->viewaiming = FixedToFloat(fixedaiming); + trans->viewaiming = FixedToFloat(fixedaiming) * ((float)vid.width / vid.height) / ((float)BASEVIDWIDTH / BASEVIDHEIGHT); + if (splitscreen == 1) // only for 2 player splitscreen + trans->viewaiming *= 2.125; // splitscreen adjusts fov with 0.8, so compensate (but only halfway, since splitscreen means only half the screen is used) trans->shearing = true; gl_aimingangle = 0; } @@ -5594,20 +5576,6 @@ extern "C" { // ========================================================================== static void HWR_RenderFrame(player_t *player, boolean skybox) { - // set window position - gl_viewwindowx = gl_baseviewwindowx; - gl_viewwindowy = gl_baseviewwindowy; - - if ((splitscreen == 1 && viewssnum == 1) || (splitscreen > 1 && viewssnum > 1)) - { - gl_viewwindowy += gl_viewheight; - } - - if (splitscreen > 1 && viewssnum & 1) - { - gl_viewwindowx += gl_viewwidth; - } - // check for new console commands. NetUpdate(); @@ -5623,10 +5591,10 @@ static void HWR_RenderFrame(player_t *player, boolean skybox) if (!skybox && cv_glrenderdistance.value) { - GL_GClipRect((INT32)gl_viewwindowx, - (INT32)gl_viewwindowy, - (INT32)(gl_viewwindowx + gl_viewwidth), - (INT32)(gl_viewwindowy + gl_viewheight), + GL_GClipRect(viewwindowx, + viewwindowy, + (viewwindowx + viewwidth), + (viewwindowy + viewheight), ZCLIP_PLANE, clipping_distances[cv_glrenderdistance.value - 1]); current_bsp_culling_distance = bsp_culling_distances[cv_glrenderdistance.value - 1]; } diff --git a/src/hardware/hw_main.h b/src/hardware/hw_main.h index 4060b6540..30906b611 100644 --- a/src/hardware/hw_main.h +++ b/src/hardware/hw_main.h @@ -42,10 +42,6 @@ extern "C" { void HWR_Startup(void); void HWR_Shutdown(void); -extern float gl_viewwidth, gl_viewheight, gl_baseviewwindowx, gl_baseviewwindowy; - -extern float gl_basewindowcenterx, gl_basewindowcentery; - extern unsigned msaa; extern boolean a2c; @@ -89,7 +85,6 @@ extern ps_metric_t ps_hw_batchdrawtime; extern boolean gl_shadersavailable; // hw_draw.c -void HWR_DrawPatch(patch_t *gpatch, INT32 x, INT32 y, INT32 option); void HWR_DrawStretchyFixedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, fixed_t vscale, INT32 option, const UINT8 *colormap, INT32 bflags); void HWR_DrawCroppedPatch(patch_t *gpatch, fixed_t x, fixed_t y, fixed_t pscale, INT32 option, fixed_t sx, fixed_t sy, fixed_t w, fixed_t h); void HWR_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 color); @@ -98,7 +93,6 @@ void HWR_DrawDiag(INT32 x, INT32 y, INT32 wh, INT32 color); void HWR_drawAMline(const fline_t *fl, INT32 color); void HWR_FadeScreenMenuBack(UINT16 color, UINT8 strength); void HWR_DrawConsoleBack(UINT32 color, INT32 height); -void HWR_DrawViewBorder(INT32 clearlines); void HWR_DrawFlatFill(INT32 x, INT32 y, INT32 w, INT32 h, lumpnum_t flatlumpnum); UINT8 *HWR_GetScreenshot(INT32 scale); diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index e77cf43ef..6a9825402 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -114,7 +114,6 @@ void UnloadModel(model_t *model) if (model->materials) Z_Free(model->materials); - DeleteVBOs(model); Z_Free(model); } @@ -194,7 +193,6 @@ model_t *LoadModel(const char *filename, int ztag) strcpy(model->mdlFilename, filename); Optimize(model); - GeneratePolygonNormals(model, ztag); // Default material properties for (i = 0 ; i < model->numMaterials; i++) @@ -246,13 +244,6 @@ void GenerateVertexNormals(model_t *model) M_Memcpy(newNormals, frame->normals, sizeof(float)*3*mesh->numTriangles*3); -/* if (!systemSucks) - { - memTag = Z_GetTag(frame->tangents); - float *newTangents = (float*)Z_Malloc(sizeof(float)*3*mesh->numTriangles*3, memTag); - M_Memcpy(newTangents, frame->tangents, sizeof(float)*3*mesh->numTriangles*3); - }*/ - for (k = 0; k < mesh->numVertices; k++) { float x, y, z; @@ -288,32 +279,15 @@ void GenerateVertexNormals(model_t *model) if (vCount > 1) { -// Vector::Normalize(&normal); newNormals[3 * k + 0] = (float)normal.x; newNormals[3 * k + 1] = (float)normal.y; newNormals[3 * k + 2] = (float)normal.z; - -/* if (!systemSucks) - { - Vector::vector_t tangent; - Vector::Tangent(&normal, &tangent); - newTangents[3 * k + 0] = tangent.x; - newTangents[3 * k + 1] = tangent.y; - newTangents[3 * k + 2] = tangent.z; - }*/ } } oldNormals = frame->normals; frame->normals = newNormals; Z_Free(oldNormals); - -/* if (!systemSucks) - { - float *oldTangents = frame->tangents; - frame->tangents = newTangents; - Z_Free(oldTangents); - }*/ } } } @@ -404,15 +378,11 @@ void Optimize(model_t *model) newMesh->numTriangles = numTriangles; newMesh->numVertices = numTriangles * 3; newMesh->uvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, 0); -// if (node->material->lightmap) -// newMesh->lightuvs = (float*)Z_Malloc(sizeof(float)*2*numTriangles*3, memTag, 0); newMesh->frames = (mdlframe_t*)Z_Calloc(sizeof(mdlframe_t), memTag, 0); curFrame = &newMesh->frames[0]; curFrame->material = curMat; curFrame->normals = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); -// if (!systemSucks) -// curFrame->tangents = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); curFrame->vertices = (float*)Z_Malloc(sizeof(float)*3*numTriangles*3, memTag, 0); curFrame->colors = (char*)Z_Malloc(sizeof(char)*4*numTriangles*3, memTag, 0); @@ -436,12 +406,6 @@ void Optimize(model_t *model) curMesh->uvs, sizeof(float)*2*curMesh->numTriangles*3); -/* if (node->material->lightmap) - { - M_Memcpy(&newMesh->lightuvs[uvCount], - curMesh->lightuvs, - sizeof(float)*2*curMesh->numTriangles*3); - }*/ uvCount += 2*curMesh->numTriangles*3; dest = (float*)newMesh->frames[0].vertices; @@ -456,15 +420,6 @@ void Optimize(model_t *model) src, sizeof(float)*3*curMesh->numTriangles*3); -/* if (!systemSucks) - { - dest = (float*)newMesh->frames[0].tangents; - src = (float*)curMesh->frames[0].tangents; - M_Memcpy(&dest[vertCount], - src, - sizeof(float)*3*curMesh->numTriangles*3); - }*/ - vertCount += 3 * curMesh->numTriangles * 3; destByte = (char*)newMesh->frames[0].colors; @@ -494,103 +449,3 @@ void Optimize(model_t *model) model->meshes = newMeshes; model->numMeshes = numMeshes; } - -void GeneratePolygonNormals(model_t *model, int ztag) -{ - int i; - for (i = 0; i < model->numMeshes; i++) - { - int j; - mesh_t *mesh = &model->meshes[i]; - - if (!mesh->frames) - continue; - - for (j = 0; j < mesh->numFrames; j++) - { - int k; - mdlframe_t *frame = &mesh->frames[j]; - const float *vertices = frame->vertices; - vector_t *polyNormals; - - frame->polyNormals = (vector_t*)Z_Malloc(sizeof(vector_t) * mesh->numTriangles, ztag, 0); - - polyNormals = frame->polyNormals; - - for (k = 0; k < mesh->numTriangles; k++) - { - /// TODO: normalize vectors - (void)vertices; - (void)polyNormals; -// Vector::Normal(vertices, polyNormals); - vertices += 3 * 3; - polyNormals++; - } - } - } -} - -// -// Reload -// -// Reload VBOs -// -#if 0 -static void Reload(void) -{ -/* model_t *node; - for (node = modelHead; node; node = node->next) - { - int i; - for (i = 0; i < node->numMeshes; i++) - { - mesh_t *mesh = &node->meshes[i]; - - if (mesh->frames) - { - int j; - for (j = 0; j < mesh->numFrames; j++) - CreateVBO(mesh, &mesh->frames[j]); - } - else if (mesh->tinyframes) - { - int j; - for (j = 0; j < mesh->numFrames; j++) - CreateVBO(mesh, &mesh->tinyframes[j]); - } - } - }*/ -} -#endif - -void DeleteVBOs(model_t *model) -{ - (void)model; -/* for (int i = 0; i < model->numMeshes; i++) - { - mesh_t *mesh = &model->meshes[i]; - - if (mesh->frames) - { - for (int j = 0; j < mesh->numFrames; j++) - { - mdlframe_t *frame = &mesh->frames[j]; - if (!frame->vboID) - continue; - bglDeleteBuffers(1, &frame->vboID); - frame->vboID = 0; - } - } - else if (mesh->tinyframes) - { - for (int j = 0; j < mesh->numFrames; j++) - { - tinyframe_t *frame = &mesh->tinyframes[j]; - if (!frame->vboID) - continue; - bglDeleteBuffers(1, &frame->vboID); - frame->vboID = 0; - } - } - }*/ -} diff --git a/src/hardware/hw_model.h b/src/hardware/hw_model.h index 1803f4c5c..fcd574bd4 100644 --- a/src/hardware/hw_model.h +++ b/src/hardware/hw_model.h @@ -28,8 +28,6 @@ typedef struct float ambient[4], diffuse[4], specular[4], emissive[4]; float shininess; boolean spheremap; -// Texture::texture_t *texture; -// Texture::texture_t *lightmap; } material_t; typedef struct @@ -40,7 +38,6 @@ typedef struct float *tangents; char *colors; unsigned int vboID; - vector_t *polyNormals; } mdlframe_t; typedef struct @@ -70,7 +67,6 @@ typedef struct mesh_s typedef struct tag_s { char name[64]; -// matrix_t transform; } tag_t; typedef struct model_s @@ -96,9 +92,7 @@ model_t *LoadModel(const char *filename, int ztag); void UnloadModel(model_t *model); void Optimize(model_t *model); void GenerateVertexNormals(model_t *model); -void GeneratePolygonNormals(model_t *model, int ztag); void CreateVBOTiny(mesh_t *mesh, tinyframe_t *frame); void CreateVBO(mesh_t *mesh, mdlframe_t *frame); -void DeleteVBOs(model_t *model); #endif diff --git a/src/http-mserv.c b/src/http-mserv.c index 18690f28a..8e35f905d 100644 --- a/src/http-mserv.c +++ b/src/http-mserv.c @@ -253,6 +253,9 @@ HMS_connect (const char *format, ...) cc = curl_easy_setopt(curl, CURLOPT_TIMEOUT, (long)cv_masterserver_timeout.value); if (cc != CURLE_OK) I_OutputMsg("libcurl: %s\n", buffer->errbuf); + cc = curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 30L); + if (cc != CURLE_OK) I_OutputMsg("libcurl: %s\n", buffer->errbuf); + cc = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HMS_on_read); if (cc != CURLE_OK) I_OutputMsg("libcurl: %s\n", buffer->errbuf); diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 0132659e4..0e29a5124 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -431,7 +431,7 @@ void HU_Start(void) void HU_Shiftform(void) { - shiftxform = cv_keyboardlayout.value == 3 ? french_shiftxform : english_shiftxform; + shiftxform = (cv_keyboardlayout.value == 3) ? french_shiftxform : english_shiftxform; } //====================================================================== @@ -465,8 +465,8 @@ static INT16 addy = 0; // use this to make the messages scroll smoothly when one static void HU_removeChatText_Mini(void) { // MPC: Don't create new arrays, just iterate through an existing one - size_t i; - for(i=0;i 0) stop_spamming[i]--; } // handle chat timers - for (i=0; (i 0) chat_timers[i]--; @@ -1231,7 +1231,7 @@ static void HU_SendChatMessage(void) nodenum[2] = '\0'; // check for undesirable characters in our "number" - if (((nodenum[0] < '0') || (nodenum[0] > '9')) || ((nodenum[1] < '0') || (nodenum[1] > '9'))) + if (((nodenum[0] < '0') || (nodenum[0] > '9')) || ((nodenum[1] < '0') || (nodenum[1] > '9'))) { // check if nodenum[1] is a space if (nodenum[1] == ' ') @@ -1499,7 +1499,7 @@ static void HU_drawMiniChat(void) if (splitscreen > 1) boxw = max(64, boxw/2); - for (; i>0; i--) + for (; i > 0; i--) { char *msg = CHAT_WordWrap(x+2, boxw-(charwidth*2), V_SNAPTOBOTTOM|V_SNAPTOLEFT|V_ALLOWLOWERCASE, chat_mini[i-1]); size_t j = 0; @@ -1572,7 +1572,7 @@ static void HU_drawMiniChat(void) i = 0; prev_linereturn = false; - for (; i<=(chat_nummsg_min-1); i++) // iterate through our hot messages + for (; i <= (chat_nummsg_min-1); i++) // iterate through our hot messages { INT32 clrflag = 0; INT32 timer = ((cv_chattime.value*TICRATE)-chat_timers[i]) - cv_chattime.value*TICRATE+9; // see below... @@ -1749,7 +1749,6 @@ static void HU_drawChatLog(INT32 offset) Z_Free(msg); } - if (((chat_scroll >= chat_maxscroll) || (chat_scrollmedown)) && !(justscrolleddown || justscrolledup || chat_scrolltime)) // was already at the bottom of the page before new maxscroll calculation and was NOT scrolling. { atbottom = true; // we should scroll @@ -2284,6 +2283,7 @@ static void HU_DrawSongCreditsBox(void) V_DrawFill(x, y, strwidth*dup, BOXCREDITHEIGHT*dup, 28|flags|(bgt<= viewwindowy + viewheight) - R_VideoErase(yoffset, vid.width); // erase entire line - else - { - R_VideoErase(yoffset, viewwindowx); // erase left border - // erase right border - R_VideoErase(yoffset + viewwindowx + viewwidth, viewwindowx); - } - } - con_hudupdate = false; // if it was set.. - } -#ifdef HWRENDER - else if (rendermode != render_none) - { - // refresh just what is needed from the view borders - HWR_DrawViewBorder(secondframelines); - con_hudupdate = secondframe; - } -#endif -} - //====================================================================== // IN-LEVEL MULTIPLAYER RANKINGS //====================================================================== @@ -2540,17 +2470,91 @@ Ping_conversion (UINT32 lag) // HU_drawPing // +static void HU_drawOldPing(INT32 x, INT32 y, UINT32 lag, INT32 flags, boolean gentleman) +{ + const INT32 measureid = cv_pingmeasurement.value ? 1 : 0; + + if (vid.width >= 640) // how sad, we're using a shit resolution. + { + if (measureid == 1) + { + V_DrawRightAlignedSmallString(x+12, y+13, V_ALLOWLOWERCASE|flags, va("%dms", Ping_conversion(lag))); + } + else if (measureid == 0) + { + V_DrawRightAlignedSmallString(x+12, y+13, flags, va("d%d", Ping_conversion(lag))); + } + } + + if (cv_pingicon.value) + { + UINT8 numbars = 0; // how many ping bars do we draw? + UINT8 barcolor = 31; // color we use for the bars (green, yellow, red or black) + SINT8 i = 0; + SINT8 yoffset = 6; + + switch (lag) + { + case 0 ... 1: + numbars = 3; + barcolor = 215; // Blue + break; + case 2 ... 3: + numbars = 3; + barcolor = 184; // Green + break; + case 4 ... 6: + numbars = 2; // Apparently ternaries w/ multiple statements don't look good in C so I decided against it. + barcolor = 103; // Yellow + break; + case 7 ... 9: + numbars = 1; + barcolor = 155; // Red + break; + default: // Brazil + numbars = 0; + barcolor = 31; // black + break; + } + + if (gentleman) + { + barcolor = 194; // make it purplish + // bars get indirectly set earlier + } + + for (i = 0; (i < 3); i++) // Draw the ping bar + { + V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-4, 2, 8-yoffset, 31|flags); + if (i < numbars) + V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-3, 1, 8-yoffset-1, barcolor|flags); + + yoffset -= 2; + } + } +} + +static void HU_drawKartPing(INT32 x, INT32 y, UINT32 lag, INT32 flags, boolean gentleman) +{ + const INT32 measureid = cv_pingmeasurement.value ? 1 : 0; + + if (measureid == 1) + V_DrawScaledPatch(x+11 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); + + if (cv_pingicon.value) + { + INT32 gfxnum = Ping_gfx_num(lag); // gfx to draw + V_DrawScaledPatch(x+2, y, flags, pinggfx[gfxnum]); + } + + x = V_DrawPingNum(x + (measureid == 1 ? 11 - pingmeasure[measureid]->width : 10), y+9, flags, Ping_conversion(lag), Ping_gfx_colormap(lag, gentleman)); + + if (measureid == 0) + V_DrawScaledPatch(x+1 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); +} + void HU_drawPlayerPing(INT32 x, INT32 y, INT32 pnum, INT32 flags) { - INT32 measureid = cv_pingmeasurement.value ? 1 : 0; - INT32 gfxnum; // gfx to draw - - //SRB2/Kart v1.0 style - UINT8 numbars = 0; // how many ping bars do we draw? - UINT8 barcolor = 31; // color we use for the bars (green, yellow, red or black) - SINT8 i = 0; - SINT8 yoffset = 6; - UINT32 lag = playerpingtable[pnum]; const boolean gentleman = (cv_mindelay.value && (lag < (tic_t)simulated_lag)); @@ -2561,74 +2565,11 @@ void HU_drawPlayerPing(INT32 x, INT32 y, INT32 pnum, INT32 flags) if (cv_pingstyle.value == 0) // kart { - gfxnum = Ping_gfx_num(lag); - - if (measureid == 1) - V_DrawScaledPatch(x+11 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); - - if (cv_pingicon.value) - V_DrawScaledPatch(x+2, y, flags, pinggfx[gfxnum]); - - x = V_DrawPingNum(x + (measureid == 1 ? 11 - pingmeasure[measureid]->width : 10), y+9, flags, Ping_conversion(lag), Ping_gfx_colormap(lag, gentleman)); - - if (measureid == 0) - V_DrawScaledPatch(x+1 - pingmeasure[measureid]->width, y+9, flags, pingmeasure[measureid]); + HU_drawKartPing(x, y, lag, flags, gentleman); } else if (cv_pingstyle.value == 1) // old style ping { - if (vid.width >= 640) // how sad, we're using a shit resolution. - { - if (measureid == 1) - { - V_DrawRightAlignedSmallString(x+12, y+13, V_ALLOWLOWERCASE|flags, va("%dms", Ping_conversion(lag))); - } - else if (measureid == 0) - { - V_DrawRightAlignedSmallString(x+12, y+13, flags, va("d%d", Ping_conversion(lag))); - } - } - - if (cv_pingicon.value) - { - switch (lag) - { - case 0 ... 1: - numbars = 3; - barcolor = 215; // Blue - break; - case 2 ... 3: - numbars = 3; - barcolor = 184; // Green - break; - case 4 ... 6: - numbars = 2; // Apparently ternaries w/ multiple statements don't look good in C so I decided against it. - barcolor = 103; // Yellow - break; - case 7 ... 9: - numbars = 1; - barcolor = 155; // Red - break; - default: // Brazil - numbars = 0; - barcolor = 31; // black - break; - } - - if (gentleman) - { - barcolor = 194; // make it purplish - // bars get indirectly set earlier - } - - for (i = 0; (i < 3); i++) // Draw the ping bar - { - V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-4, 2, 8-yoffset, 31|flags); - if (i < numbars) - V_DrawFill(x+2 *(i-1)+7, y+8+yoffset-3, 1, 8-yoffset-1, barcolor|flags); - - yoffset -= 2; - } - } + HU_drawOldPing(x, y, lag, flags, gentleman); } } @@ -2904,12 +2845,8 @@ void HU_SetCEchoFlags(INT32 flags) void HU_DoCEcho(const char *msg) { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstringop-truncation" // This is fine, we set null byte later - strncpy(cechotext, msg, sizeof(cechotext)); -#pragma GCC diagnostic pop - strncat(cechotext, "\\", sizeof(cechotext) - strlen(cechotext) - 1); - cechotext[sizeof(cechotext) - 1] = '\0'; + strlcpy(cechotext, msg, sizeof(cechotext)); + strlcat(cechotext, "\\", sizeof(cechotext)); // just print it to console if (cv_cechotoggle.value == 2) @@ -2918,8 +2855,20 @@ void HU_DoCEcho(const char *msg) strncpy(temp, cechotext, sizeof(temp)); for (char *p = temp; *p != '\0'; ++p) + { if (*p == '\\') + { *p = '\n'; + ++p; + char *skip_p = p; // Point at which we will move part of string after all \'s + + while (*p == '\\') + ++p; + + memmove(skip_p, p, strlen(p)+1); // move the rest of string with null byte + p = skip_p; // Restore p + } + } CONS_Printf("%s\n", temp); diff --git a/src/hu_stuff.h b/src/hu_stuff.h index d134f319e..64d369a33 100644 --- a/src/hu_stuff.h +++ b/src/hu_stuff.h @@ -117,7 +117,6 @@ void HU_TickSongCredits(void); void HU_DrawSongCredits(void); void HU_Drawer(void); char HU_dequeueChatChar(void); -void HU_Erase(void); void HU_clearChatChars(void); void HU_drawPlayerPing(INT32 x, INT32 y, INT32 pnum, INT32 flags); // Lat': Ping drawer for scoreboard. //void HU_DrawTeamTabRankings(playersort_t *tab, INT32 whiteplayer); diff --git a/src/i_addrinfo.c b/src/i_addrinfo.c deleted file mode 100644 index f9d860bd1..000000000 --- a/src/i_addrinfo.c +++ /dev/null @@ -1,680 +0,0 @@ -// SONIC ROBO BLAST 2 -//----------------------------------------------------------------------------- -// Copyright (C) 2011-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 i_addrinfo.c -/// \brief getaddr stubs, for lesser OSes -/// -/// Some systems/SDKs, like PSL1GHT v2 does not have addrinfo functions -/// So a stub is needed -#include -#include -#include -#ifdef _WIN32 -#ifdef USE_WINSOCK2 -#include -#else -#include -#endif -#else -#include -#include -#include -#endif - -#include "i_addrinfo.h" - -/* - * This addrinfo stub have a testcases: - * To test the stub, use this command to compile the stub testcase: - * gcc -g -DTESTCASE -Dtest_stub -Wall -W i_addrinfo.c -o stub - * To test the real getaddrinfo API, use this command to get real one: - * gcc -g -DTESTCASE -Utest_stub -Wall -W i_addrinfo.c -o real - * For Win32,you need the WinSock library, version 1.1 or 2.2 - * for 1.1, add -lwsock32 - * i686-w64-mingw32-gcc -g -DTESTCASE -Dtest_stub -UUSE_WINSOCK2 -Wall -W i_addrinfo.c -o stub.exe -lwsock32 - * for 2.2, add -DUSE_WINSOCK2 -lws2_32 - * i686-w64-mingw32-gcc -g -DTESTCASE -Utest_stub -DUSE_WINSOCK2 -Wall -W i_addrinfo.c -o real.exe -lws2_32 - */ - -#ifndef I_getaddrinfo - -#include - -#ifdef _WIN32 -// it seems windows doesn't define that... maybe some other OS? OS/2 -static int inet_aton(const char *cp, struct in_addr *addr) -{ - if( cp == NULL || addr == NULL ) - { - return(0); - } - if (strcmp(cp, "255.255.255.225") == 0) - { - addr->s_addr = htonl(INADDR_BROADCAST); - return 0; - } - return (addr->s_addr = inet_addr(cp)) != htonl(INADDR_NONE); -} -#endif - -#ifdef USE_WINSOCK2 -static HMODULE ipv6dll = NULL; -typedef int (WSAAPI *p_getaddrinfo) (const char *, const char *, - const struct my_addrinfo *, - struct my_addrinfo **); -typedef void (WSAAPI *p_freeaddrinfo) (struct my_addrinfo *); - -static p_getaddrinfo WS_getaddrinfo = NULL; -static p_freeaddrinfo WS_freeaddrinfo = NULL; - -static HMODULE WS_getfunctions(HMODULE tmp) -{ - if (tmp != NULL) - { - WS_getaddrinfo = (p_getaddrinfo)(LPVOID)GetProcAddress(tmp, "getaddrinfo"); - if (WS_getaddrinfo == NULL) - return NULL; - WS_freeaddrinfo = (p_freeaddrinfo)(LPVOID)GetProcAddress(tmp, "freeaddrinfo"); - if (WS_freeaddrinfo == NULL) - { - WS_getaddrinfo = NULL; - return NULL; - } - } - return tmp; -} - -static void WS_addrinfosetup(void) -{ - if (WS_getaddrinfo && WS_freeaddrinfo) - return; // already have the functions - // why not hold it into ipv6dll? becase we already link with ws2_32, silly! - if (WS_getfunctions(GetModuleHandleA("ws2_32.dll")) == NULL) - ipv6dll = WS_getfunctions(LoadLibraryA("wship6.dll")); -} - -void WS_addrinfocleanup(void) -{ - if (ipv6dll) - FreeLibrary(ipv6dll); - ipv6dll = NULL; - WS_getaddrinfo = NULL; - WS_freeaddrinfo = NULL; -} -#else -void WS_addrinfocleanup(void) {} -#endif - -int I_getaddrinfo(const char *node, const char *service, - const struct my_addrinfo *hints, - struct my_addrinfo **res) -{ - struct hostent *nodename = NULL; - bool hostlookup = true, passivemode = false; - int flags = 0; - int socktype = 0; - int sockport = 0; - struct my_addrinfo *ai; - struct sockaddr_in *addr; - struct in_addr ipv4; - size_t addrlen = 1; - size_t ailen = 1, i = 0, j; - size_t famsize = sizeof(struct sockaddr_in); -#ifdef USE_WINSOCK2 - WS_addrinfosetup(); - if (WS_getaddrinfo) - return WS_getaddrinfo(node, service, hints, res); -#endif - - // param check - if (node == NULL && service == NULL) - return EAI_NONAME; - //note: testcase show NULL as res crashes libc - if (res == NULL) - return -1; - - // check hints - if (hints) - { - // no support for IPv6 - if (hints->ai_family != AF_INET && hints->ai_family != AF_UNSPEC) - return -1; //EAI_FAMILY -#ifdef AI_NUMERICHOST - // do not look up hostnames - if ((hints->ai_flags & AI_NUMERICHOST) == AI_NUMERICHOST) - { - hostlookup = false; - flags |= AI_NUMERICHOST; - } -#endif -#ifdef AI_PASSIVE - // return loopback or any address? - if ((hints->ai_flags & AI_PASSIVE) == AI_PASSIVE) - { - passivemode = true; - flags |= AI_PASSIVE; - } -#endif - // why no support for canon names? lazy - //AI_CANONNAME - // what kind of socket? - socktype = hints->ai_socktype; - } - else - { -#ifdef AI_V4MAPPED - flags |= AI_V4MAPPED; -#endif -#ifdef AI_ADDRCONFIG - flags |= AI_ADDRCONFIG; -#endif - } - - // we need gethostbyname to convert numeric strings - if (node && hostlookup) - { - if (node == NULL) - return -1; - nodename = gethostbyname(node); - if (nodename == NULL) - { - if (inet_aton(node, &ipv4) != 0) - addrlen = 1; - else - return -1; - } - else while (nodename->h_addr_list[addrlen] != NULL) - addrlen++; - } - else if (node) - { - if (inet_aton(node, &ipv4) != 0) - addrlen = 1; - else if (!hostlookup) - return EAI_NONAME; - } - else - addrlen = 1; - - if (service) //AI_NUMERICSERV - sockport = atoi(service); - - if (socktype == 0) - ailen = addrlen*3; - else - ailen = addrlen; - - ai = calloc(ailen, sizeof(struct my_addrinfo)); - if (ai == NULL) - return -1; - else - *res = ai; - - addr = calloc(ailen*2, famsize); - if (addr == NULL) - { - free(ai); - return -1; - } - else - ai->ai_addr = memset(addr, 0x00, ailen*ai->ai_addrlen); - - for (i = 0; i < ailen; i++) - { - ai = *res+i; - ai->ai_flags = flags; - ai->ai_family = AF_INET; - ai->ai_socktype = socktype; - switch (ai->ai_socktype) - { - case SOCK_STREAM: - ai->ai_protocol = IPPROTO_TCP; - break; - case SOCK_DGRAM: - ai->ai_protocol = IPPROTO_UDP; - break; - default: - ai->ai_protocol = 0; - } - ai->ai_addrlen = famsize; - ai->ai_addr = (struct sockaddr *)&addr[i]; - //ai_cannonname - ai->ai_next = ai+1; - } - ai->ai_next = NULL; - ai = *res; - - for (i = 0, j = 0; i < ailen; i++, j++) - { - ai = *res+i; - addr[i].sin_port = htons((UINT16)sockport); - if (nodename) - { - memcpy(&addr[i].sin_addr, nodename->h_addr_list[j], ai->ai_addrlen); - addr[i].sin_family = nodename->h_addrtype; - } - else if (node) - { - memcpy(&addr[i].sin_addr, &ipv4, ai->ai_addrlen); - addr[i].sin_family = AF_INET; - } - else - { - if (passivemode) - addr[i].sin_addr.s_addr = htonl(INADDR_ANY); - else - addr[i].sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr[i].sin_family = AF_INET; - } - if (socktype == 0) - { - ai->ai_socktype = SOCK_STREAM; - ai->ai_protocol = IPPROTO_TCP; - memcpy(&addr[i+1], &addr[i], ai->ai_addrlen); - i++; ai++; - ai->ai_socktype = SOCK_DGRAM; - ai->ai_protocol = IPPROTO_UDP; - memcpy(&addr[i+1], &addr[i], ai->ai_addrlen); - i++; ai++; - ai->ai_socktype = SOCK_RAW; - ai->ai_protocol = IPPROTO_IP; - } - } - return 0; -} -#endif - -#ifndef I_freeaddrinfo -void I_freeaddrinfo(struct my_addrinfo *res) -{ -#ifdef USE_WINSOCK2 - if (WS_freeaddrinfo) - { - WS_freeaddrinfo(res); - return; - } -#endif - if (!res) - return; - free(res->ai_addr); - free(res); -} -#endif - -#ifdef TESTCASE -#include - -#ifdef USE_WINSOCK2 -#define inet_ntop inet_ntopA -#define HAVE_NTOP -static const char* inet_ntopA(int af, const void *cp, char *buf, socklen_t len) -{ - DWORD Dlen = len, AFlen = 0; - SOCKADDR_STORAGE any; - LPSOCKADDR anyp = (LPSOCKADDR)&any; - LPSOCKADDR_IN any4 = (LPSOCKADDR_IN)&any; - LPSOCKADDR_IN6 any6 = (LPSOCKADDR_IN6)&any; - - if (!buf) - { - WSASetLastError(STATUS_INVALID_PARAMETER); - return NULL; - } - - if (af != AF_INET && af != AF_INET6) - { - WSASetLastError(WSAEAFNOSUPPORT); - return NULL; - } - - ZeroMemory(&any, sizeof(SOCKADDR_STORAGE)); - any.ss_family = af; - - switch (af) - { - case AF_INET: - { - CopyMemory(&any4->sin_addr, cp, sizeof(IN_ADDR)); - AFlen = sizeof(SOCKADDR_IN); - break; - } - case AF_INET6: - { - CopyMemory(&any6->sin6_addr, cp, sizeof(IN6_ADDR)); - AFlen = sizeof(SOCKADDR_IN6); - break; - } - } - - if (WSAAddressToStringA(anyp, AFlen, NULL, buf, &Dlen) == SOCKET_ERROR) - return NULL; - return buf; -} -#elif defined (_WIN32) -// w32api, ws2tcpip.h, r1.12 -static inline char* gai_strerror(int ecode) -{ - static char message[1024+1]; - DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM - | FORMAT_MESSAGE_IGNORE_INSERTS - | FORMAT_MESSAGE_MAX_WIDTH_MASK; - DWORD dwLanguageId = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT); - FormatMessageA(dwFlags, NULL, ecode, dwLanguageId, message, 1024, NULL); - return message; -} -#else -#define HAVE_NTOP -#endif - -#ifndef INET_ADDRSTRLEN -#define INET_ADDRSTRLEN 16 -#endif - -static inline void printflags(int ai_flags) -{ - printf("flags: %x(", ai_flags); - if (ai_flags == 0) - printf("NONE|"); -#ifdef AI_PASSIVE - if ((ai_flags & AI_PASSIVE) == AI_PASSIVE) - printf("AI_PASSIVE|"); - ai_flags &= ~AI_PASSIVE; -#endif -#ifdef AI_CANONNAME - if ((ai_flags & AI_CANONNAME) == AI_CANONNAME) - printf("AI_CANONNAME|"); - ai_flags &= ~AI_CANONNAME; -#endif -#ifdef AI_NUMERICHOST - if ((ai_flags & AI_NUMERICHOST) == AI_NUMERICHOST) - printf("AI_NUMERICHOST|"); - ai_flags &= ~AI_NUMERICHOST; -#endif -#ifdef AI_V4MAPPED - if ((ai_flags & AI_V4MAPPED) == AI_V4MAPPED) - printf("AI_V4MAPPED|"); - ai_flags &= ~AI_V4MAPPED; -#endif -#ifdef AI_ALL - if ((ai_flags & AI_ALL) == AI_ALL) - printf("AI_ALL|"); - ai_flags &= ~AI_ALL; -#endif -#ifdef AI_ADDRCONFIG - if ((ai_flags & AI_ADDRCONFIG) == AI_ADDRCONFIG) - printf("AI_ADDRCONFIG|"); - ai_flags &= ~AI_ADDRCONFIG; -#endif -#ifdef AI_IDN - if ((ai_flags & AI_IDN) == AI_IDN) - printf("AI_IDN|"); - ai_flags &= ~AI_IDN; -#endif -#ifdef AI_CANONIDN - if ((ai_flags & AI_CANONIDN) == AI_CANONIDN) - printf("AI_CANONIDN|"); - ai_flags &= ~AI_CANONIDN; -#endif -#ifdef AI_IDN_ALLOW_UNASSIGNED - if ((ai_flags & AI_IDN_ALLOW_UNASSIGNED) == AI_IDN_ALLOW_UNASSIGNED) - printf("AI_IDN_ALLOW_UNASSIGNED|"); - ai_flags &= ~AI_IDN_ALLOW_UNASSIGNED; -#endif -#ifdef AI_IDN_USE_STD3_ASCII_RULES - if ((ai_flags & AI_IDN_USE_STD3_ASCII_RULES) == AI_IDN_USE_STD3_ASCII_RULES) - printf("AI_IDN_USE_STD3_ASCII_RULES|"); - ai_flags &= ~AI_PASSIVE; -#endif -#ifdef AI_NUMERICSERV - if ((ai_flags & AI_NUMERICSERV) == AI_NUMERICSERV) - printf("AI_NUMERICSERV|"); - ai_flags &= ~AI_NUMERICSERV; -#endif - printf("%x", ai_flags); - printf(")\n"); -} - -static inline void printsocktype(int ai_socktype) -{ - printf("socktype: %d(", ai_socktype); - switch (ai_socktype) - { - case 0: - printf("SOCK_ Woe32"); - break; - case SOCK_STREAM: - printf("SOCK_STREAM"); - break; - case SOCK_DGRAM: - printf("SOCK_DGRAM"); - break; - case SOCK_RAW: - printf("SOCK_RAW"); - break; - default: - printf("SOCK_ERROR\n"); - exit(-1); - } - printf(")\n"); -} - -static inline void printprotocol(int ai_protocol) -{ - printf("protocol: %d(", ai_protocol); - switch (ai_protocol) - { - case IPPROTO_IP: - printf("IPPROTO_IP"); - break; - case IPPROTO_TCP: - printf("IPPROTO_TCP"); - break; - case IPPROTO_UDP: - printf("IPPROTO_UDP"); - break; - default: - printf("IPPROTO_ERROR\n"); - exit(-1); - } - printf(")\n"); -} - -static inline void printaddr(int ai_family, const struct sockaddr *ai_addr) -{ - char str[INET_ADDRSTRLEN+1] = "FAKE"; - printf("family: %d(", ai_family); - switch (ai_family) - { - case AF_UNSPEC: - printf("AF_UNSPEC"); - break; - case AF_INET: - printf("AF_INET"); - break; -#ifdef AF_INET6 - case AF_INET6: - printf("AF_INET6"); - break; -#endif - default: - printf("AF_ERROR\n"); - exit(-1); - } - printf(")\n"); - if (ai_family == AF_INET && ai_addr) - { - const struct sockaddr_in *ip4 = (void *)ai_addr; -#ifdef HAVE_NTOP - inet_ntop(ai_family, &ip4->sin_addr, str, INET_ADDRSTRLEN); -#else - strncpy(str, inet_ntoa(ip4->sin_addr), INET_ADDRSTRLEN); -#endif - printf("port: %d\n", ntohs(ip4->sin_port)); - } - printf("addr: %s\n", str); -} - -void printaddrinfo(const struct my_addrinfo *data) -{ - if(data == NULL) - { - printf("no data\n"); - return; - } - else - printf("starting addrinfo dump\n"); - while (data != NULL) - { - printflags(data->ai_flags); - printsocktype(data->ai_socktype); - printaddr(data->ai_family, data->ai_addr); - printprotocol(data->ai_protocol); - //addrlen - data = data->ai_next; - } -} - -int main(int argc, char **argv) -{ - struct my_addrinfo *res = NULL, hints; - int gaie; - - (void)argc; - (void)argv; - memset(&hints, 0x00, sizeof(struct my_addrinfo)); - hints.ai_family = AF_INET; - -#ifdef _WIN32 - { -#ifdef USE_WINSOCK2 - const WORD VerNeed = MAKEWORD(2,2); -#else - const WORD VerNeed = MAKEWORD(1,1); -#endif - WSADATA WSAData; - WSAStartup(VerNeed, &WSAData); - } -#endif - printf("-----------------------------------------------------------\n"); -#ifndef _WIN32 //NULL as res crashes Win32 - gaie = I_getaddrinfo(NULL, NULL, &hints, NULL); - if (gaie != EAI_NONAME) - printf("NULLs test returned: %s(%d)\n", gai_strerror(gaie), gaie); - I_freeaddrinfo(res); -#endif -#if 0 //NULL as res crashes - gaie = I_getaddrinfo("localhost", "5029", NULL, NULL); - if (gaie == 0) - printf("NULL crashes: %s(%d)\n", gai_strerror(gaie), gaie); - I_freeaddrinfo(res); -#endif - gaie = I_getaddrinfo("localhost", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo(NULL, "5029", &hints, &res); - //if (gaie != 0) - printf("NULLs test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("localhost", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - gaie = I_getaddrinfo("localhost", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo(NULL, "5029", &hints, &res); - //if (gaie != 0) - printf("NULLs test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("localhost", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - hints.ai_socktype = SOCK_DGRAM; - hints.ai_protocol = IPPROTO_UDP; - gaie = I_getaddrinfo("localhost", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo(NULL, "5029", &hints, &res); - //if (gaie != 0) - printf("NULLs test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("localhost", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - hints.ai_flags = AI_NUMERICHOST; - gaie = I_getaddrinfo("localhost", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo(NULL, "5029", &hints, &res); - //if (gaie != 0) - printf("NULLs test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("localhost", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - gaie = I_getaddrinfo("127.0.0.1", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("127.0.0.1", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - gaie = I_getaddrinfo("255.255.255.255", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("255.255.255.255", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - printf("-----------------------------------------------------------\n"); - hints.ai_flags = AI_PASSIVE; - gaie = I_getaddrinfo("0.0.0.0", NULL, &hints, &res); - //if (gaie != 0) - printf("NULL service test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - gaie = I_getaddrinfo("0.0.0.0", "5029", &hints, &res); - //if (gaie != 0) - printf("no hints test returned: %s(%d)\n", gai_strerror(gaie), gaie); - printaddrinfo(res); - I_freeaddrinfo(res); res = NULL; - return 0; -} -#endif diff --git a/src/i_addrinfo.h b/src/i_addrinfo.h deleted file mode 100644 index 7c3afc614..000000000 --- a/src/i_addrinfo.h +++ /dev/null @@ -1,71 +0,0 @@ -// SONIC ROBO BLAST 2 -//----------------------------------------------------------------------------- -// Copyright (C) 2011-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 i_addrinfo.h -/// \brief getaddrinfo stub - -#ifndef __I_ADDRINFO__ -#define __I_ADDRINFO__ - -#ifdef __GNUG__ -#pragma interface -#endif - -#ifndef AI_PASSIVE -#define AI_PASSIVE 0x01 -#endif -#ifndef AI_NUMERICHOST -#define AI_NUMERICHOST 0x04 -#endif -#ifndef AI_V4MAPPED -#define AI_V4MAPPED 0x08 -#endif -#ifndef AI_ADDRCONFIG -#define AI_ADDRCONFIG 0x20 -#endif - -#ifdef _WIN32 -#ifndef EAI_NONAME -#define EAI_NONAME WSAHOST_NOT_FOUND -#endif -#endif - -#ifndef EAI_NONAME -#define EAI_NONAME -2 -#endif - -#ifdef _WIN32 // already use the stub for Win32 -// w32api, ws2tcpip.h, r1.12 -struct my_addrinfo { - int ai_flags; - int ai_family; - int ai_socktype; - int ai_protocol; - size_t ai_addrlen; - char *ai_canonname; - struct sockaddr *ai_addr; - struct my_addrinfo *ai_next; -}; -#else -#define my_addrinfo addrinfo -#endif - -void WS_addrinfocleanup(void); - -#ifndef my_addrinfo -void I_freeaddrinfo(struct my_addrinfo *res); -int I_getaddrinfo(const char *node, const char *service, - const struct my_addrinfo *hints, - struct my_addrinfo **res); -#elif !defined (test_stub) -#define I_getaddrinfo getaddrinfo -#define I_freeaddrinfo freeaddrinfo -#endif - - -#endif diff --git a/src/i_tcp.c b/src/i_tcp.c index f6152e3cd..09cba908f 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -29,42 +29,36 @@ #ifdef _WIN32 #define USE_WINSOCK -#if defined (_WIN64) || defined (HAVE_IPV6) -#define USE_WINSOCK2 -#else //_WIN64/HAVE_IPV6 -#define USE_WINSOCK1 -#endif #endif //WIN32 OS -#ifdef USE_WINSOCK2 +#ifdef USE_WINSOCK #include +#define addrinfo_t ADDRINFOA +#else +#define addrinfo_t struct addrinfo #endif #include "doomdef.h" +#ifndef USE_WINSOCK + #include + #ifdef __APPLE_CC__ + #ifndef _BSD_SOCKLEN_T_ + #define _BSD_SOCKLEN_T_ + #endif //_BSD_SOCKLEN_T_ + #endif //__APPLE_CC__ + #include + #include + #include + #include +#endif //normal BSD API + +#include #include -#ifdef USE_WINSOCK1 - #include -#else - #ifndef USE_WINSOCK - #include - #ifdef __APPLE_CC__ - #ifndef _BSD_SOCKLEN_T_ - #define _BSD_SOCKLEN_T_ - #endif //_BSD_SOCKLEN_T_ - #endif //__APPLE_CC__ - #include - #include - #include - #include - #endif //normal BSD API - #include - - #if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) - #include - #endif // UNIXCOMMON -#endif +#if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) + #include +#endif // UNIXCOMMON #ifdef USE_WINSOCK // some undefined under win32 @@ -152,7 +146,6 @@ static UINT8 UPNP_support = TRUE; #define close closesocket #endif -#include "i_addrinfo.h" #define DEFAULTPORT "5029" #if defined (USE_WINSOCK) @@ -169,10 +162,6 @@ typedef unsigned long SOCKET_TYPE; #define IPV6_MULTICAST_ADDRESS "ff15::57e1:1a12" -#ifdef USE_WINSOCK1 -typedef int socklen_t; -#endif - typedef struct { mysockaddr_t address; @@ -232,9 +221,8 @@ static char *get_WSAErrorStr(int e) #define strerror get_WSAErrorStr #endif -#ifdef USE_WINSOCK2 +#ifdef USE_WINSOCK #define inet_ntop inet_ntopA -#define HAVE_NTOP static const char* inet_ntopA(short af, const void *cp, char *buf, socklen_t len) { DWORD Dlen = len, AFlen = 0; @@ -278,8 +266,6 @@ static const char* inet_ntopA(short af, const void *cp, char *buf, socklen_t len return NULL; return buf; } -#elif !defined (USE_WINSOCK1) -#define HAVE_NTOP #endif #ifdef HAVE_MINIUPNPC // based on old XChat patch @@ -360,7 +346,6 @@ static const char *SOCK_AddrToStr(mysockaddr_t *sk) static char s[64]; // 255.255.255.255:65535 or // [ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535 -#ifdef HAVE_NTOP #ifdef HAVE_IPV6 int v6 = (sk->any.sa_family == AF_INET6); #else @@ -398,15 +383,7 @@ static const char *SOCK_AddrToStr(mysockaddr_t *sk) #endif else if(sk->any.sa_family == AF_INET && sk->ip4.sin_port != 0) strcat(s, va(":%d", ntohs(sk->ip4.sin_port))); -#else - if (sk->any.sa_family == AF_INET) - { - strcpy(s, inet_ntoa(sk->ip4.sin_addr)); - if (sk->ip4.sin_port != 0) strcat(s, va(":%d", ntohs(sk->ip4.sin_port))); - } - else - sprintf(s, "Unknown type"); -#endif + return s; } @@ -868,15 +845,11 @@ static SOCKET_TYPE UDP_Bind(int family, struct sockaddr *addr, socklen_t addrlen #ifdef USE_WINSOCK { // Alam_GBC: disable the new UDP connection reset behavior for Win2k and up -#ifdef USE_WINSOCK2 DWORD dwBytesReturned = 0; BOOL bfalse = FALSE; rc = WSAIoctl(s, SIO_UDP_CONNRESET, &bfalse, sizeof(bfalse), NULL, 0, &dwBytesReturned, NULL, NULL); -#else - unsigned long falseval = false; - rc = ioctl(s, SIO_UDP_CONNRESET, &falseval); -#endif + if (rc == -1) { e = errno; @@ -1046,7 +1019,7 @@ static SOCKET_TYPE UDP_Bind(int family, struct sockaddr *addr, socklen_t addrlen static boolean UDP_Socket(void) { size_t s; - struct my_addrinfo *ai, *runp, hints; + addrinfo_t *ai, *runp, hints; int gaie; #ifdef HAVE_IPV6 const INT32 b_ipv6 = M_CheckParm("-ipv6"); @@ -1075,7 +1048,7 @@ static boolean UDP_Socket(void) { while (M_IsNextParm()) { - gaie = I_getaddrinfo(M_GetNextParm(), serv, &hints, &ai); + gaie = getaddrinfo(M_GetNextParm(), serv, &hints, &ai); if (gaie == 0) { runp = ai; @@ -1089,13 +1062,13 @@ static boolean UDP_Socket(void) } runp = runp->ai_next; } - I_freeaddrinfo(ai); + freeaddrinfo(ai); } } } else { - gaie = I_getaddrinfo("0.0.0.0", serv, &hints, &ai); + gaie = getaddrinfo("0.0.0.0", serv, &hints, &ai); if (gaie == 0) { runp = ai; @@ -1116,7 +1089,7 @@ static boolean UDP_Socket(void) } runp = runp->ai_next; } - I_freeaddrinfo(ai); + freeaddrinfo(ai); } } @@ -1128,7 +1101,7 @@ static boolean UDP_Socket(void) { while (M_IsNextParm()) { - gaie = I_getaddrinfo(M_GetNextParm(), serv, &hints, &ai); + gaie = getaddrinfo(M_GetNextParm(), serv, &hints, &ai); if (gaie == 0) { runp = ai; @@ -1142,13 +1115,13 @@ static boolean UDP_Socket(void) } runp = runp->ai_next; } - I_freeaddrinfo(ai); + freeaddrinfo(ai); } } } else { - gaie = I_getaddrinfo("::", serv, &hints, &ai); + gaie = getaddrinfo("::", serv, &hints, &ai); if (gaie == 0) { runp = ai; @@ -1162,7 +1135,7 @@ static boolean UDP_Socket(void) } runp = runp->ai_next; } - I_freeaddrinfo(ai); + freeaddrinfo(ai); } } } @@ -1216,11 +1189,7 @@ boolean I_InitTcpDriver(void) if (!init_tcp_driver) { #ifdef USE_WINSOCK -#ifdef USE_WINSOCK2 const WORD VerNeed = MAKEWORD(2,2); -#else - const WORD VerNeed = MAKEWORD(1,1); -#endif WSADATA WSAData; const int WSAresult = WSAStartup(VerNeed, &WSAData); if (WSAresult != 0) @@ -1247,21 +1216,14 @@ boolean I_InitTcpDriver(void) if (WSAresult != WSAVERNOTSUPPORTED) CONS_Debug(DBG_NETPLAY, "WinSock(TCP/IP) error: %s\n",WSError); } -#ifdef USE_WINSOCK2 - if(LOBYTE(WSAData.wVersion) != 2 || + + if (LOBYTE(WSAData.wVersion) != 2 || HIBYTE(WSAData.wVersion) != 2) { WSACleanup(); CONS_Debug(DBG_NETPLAY, "No WinSock(TCP/IP) 2.2 driver detected\n"); } -#else - if (LOBYTE(WSAData.wVersion) != 1 || - HIBYTE(WSAData.wVersion) != 1) - { - WSACleanup(); - CONS_Debug(DBG_NETPLAY, "No WinSock(TCP/IP) 1.1 driver detected\n"); - } -#endif + CONS_Debug(DBG_NETPLAY, "WinSock description: %s\n",WSAData.szDescription); CONS_Debug(DBG_NETPLAY, "WinSock System Status: %s\n",WSAData.szSystemStatus); #endif @@ -1301,7 +1263,6 @@ void I_ShutdownTcpDriver(void) CONS_Printf("I_ShutdownTcpDriver: "); #ifdef USE_WINSOCK - WS_addrinfocleanup(); WSACleanup(); #endif CONS_Printf("shut down\n"); @@ -1310,24 +1271,24 @@ void I_ShutdownTcpDriver(void) static boolean SOCK_GetAddr(struct sockaddr_in *sin, const char *address, const char *port, boolean test) { - struct my_addrinfo *ai = NULL, *runp, hints; + addrinfo_t *ai = NULL, *runp, hints; int gaie; size_t i; if (!port || !port[0]) port = DEFAULTPORT; - memset (&hints, 0x00, sizeof (hints)); + memset(&hints, 0x00, sizeof (hints)); hints.ai_flags = AI_ADDRCONFIG; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; - gaie = I_getaddrinfo(address, port, &hints, &ai); + gaie = getaddrinfo(address, port, &hints, &ai); if (gaie != 0) { - I_freeaddrinfo(ai); + freeaddrinfo(ai); return false; } @@ -1356,7 +1317,7 @@ static boolean SOCK_GetAddr(struct sockaddr_in *sin, const char *address, const if (runp != NULL) memcpy(sin, runp->ai_addr, runp->ai_addrlen); - I_freeaddrinfo(ai); + freeaddrinfo(ai); return (runp != NULL); } @@ -1554,7 +1515,7 @@ static boolean SOCK_SetUnbanTime(time_t timestamp) static boolean SOCK_SetBanAddress(const char *address, const char *mask) { - struct my_addrinfo *ai, *runp, hints; + addrinfo_t *ai, *runp, hints; int gaie; if (!address) @@ -1566,7 +1527,7 @@ static boolean SOCK_SetBanAddress(const char *address, const char *mask) hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; - gaie = I_getaddrinfo(address, "0", &hints, &ai); + gaie = getaddrinfo(address, "0", &hints, &ai); if (gaie != 0) return false; @@ -1611,7 +1572,7 @@ static boolean SOCK_SetBanAddress(const char *address, const char *mask) runp = runp->ai_next; } - I_freeaddrinfo(ai); + freeaddrinfo(ai); return true; } @@ -1660,8 +1621,6 @@ boolean I_InitTcpNetwork(void) // FIXME: for dedicated server, numnodes needs to be set to 0 upon start if (dedicated) doomcom->numnodes = 0; -/* else if (M_IsNextParm()) - doomcom->numnodes = (INT16)atoi(M_GetNextParm());*/ else doomcom->numnodes = 1; @@ -1746,5 +1705,3 @@ boolean I_InitTcpNetwork(void) return ret; } - -#include "i_addrinfo.c" diff --git a/src/i_video.h b/src/i_video.h index 822a1bada..852645c30 100644 --- a/src/i_video.h +++ b/src/i_video.h @@ -94,8 +94,8 @@ INT32 VID_SetMode(INT32 modenum); \return name of video mode */ const char *VID_GetModeName(INT32 modenum); -void VID_PrepareModeList(void); /// note hack for SDL +void VID_PrepareModeList(void); /** \brief can video system do fullscreen */ diff --git a/src/k_hud.c b/src/k_hud.c index 71af43f5d..54b81a0f4 100644 --- a/src/k_hud.c +++ b/src/k_hud.c @@ -4333,7 +4333,7 @@ static void K_drawInput(void) target = 0; else // turning of multiple strengths! { - target = ((abs(cmd->driftturn) - 1)/125)+1; + target = ((abs(cmd->driftturn) - 1)/200)+1; // was 125, do we need another toggle for this? Zzz... if (target > 4) target = 4; if (cmd->driftturn < 0) diff --git a/src/k_kart.c b/src/k_kart.c index 6b4e333ab..7f755e235 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -608,9 +608,6 @@ void K_GenerateKartColormap(UINT8 *dest_colormap, INT32 skinnum, UINT8 color, bo if (color >= MAXTRANSLATIONS) I_Error("Invalid skin color #%hu.", (UINT16)color); - if (skinnum < 0 && skinnum > TC_DEFAULT) - I_Error("Invalid translation colormap index %d.", skinnum); - starttranscolor = (skinnum != TC_DEFAULT) ? K_GetSkinArray(local)[skinnum].starttranscolor : DEFAULT_STARTTRANSCOLOR; if (starttranscolor >= NUM_PALETTE_ENTRIES) diff --git a/src/lua_script.c b/src/lua_script.c index cd9ba1f85..e59841940 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -288,6 +288,10 @@ void LUA_LoadLump(UINT16 wad, UINT16 lump) lumpinfo_t *lump_p = &wadfiles[wad]->lumpinfo[lump]; len += 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name name = malloc(len+1); + + if (!name) + I_Error("LUA_LoadLump: Out of memory!\n"); + sprintf(name, "%s|%s", wadfiles[wad]->filename, lump_p->fullname); name[len] = '\0'; } @@ -797,8 +801,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { mobj_t *mobj = *((mobj_t **)lua_touserdata(gL, myindex)); if (!mobj) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_MOBJ); WRITEUINT32(*p, mobj->mobjnum); } @@ -808,8 +816,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { player_t *player = *((player_t **)lua_touserdata(gL, myindex)); if (!player) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_PLAYER); WRITEUINT8(*p, player - players); } @@ -819,8 +831,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { mapthing_t *mapthing = *((mapthing_t **)lua_touserdata(gL, myindex)); if (!mapthing) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_MAPTHING); WRITEUINT16(*p, mapthing - mapthings); } @@ -830,8 +846,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { vertex_t *vertex = *((vertex_t **)lua_touserdata(gL, myindex)); if (!vertex) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_VERTEX); WRITEUINT16(*p, vertex - vertexes); } @@ -841,8 +861,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { line_t *line = *((line_t **)lua_touserdata(gL, myindex)); if (!line) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_LINE); WRITEUINT16(*p, line - lines); } @@ -852,8 +876,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { side_t *side = *((side_t **)lua_touserdata(gL, myindex)); if (!side) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_SIDE); WRITEUINT16(*p, side - sides); } @@ -863,8 +891,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { subsector_t *subsector = *((subsector_t **)lua_touserdata(gL, myindex)); if (!subsector) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_SUBSECTOR); WRITEUINT16(*p, subsector - subsectors); } @@ -874,8 +906,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { sector_t *sector = *((sector_t **)lua_touserdata(gL, myindex)); if (!sector) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_SECTOR); WRITEUINT16(*p, sector - sectors); } @@ -885,8 +921,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { pslope_t *slope = *((pslope_t **)lua_touserdata(gL, myindex)); if (!slope) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_SLOPE); WRITEUINT16(*p, slope->id); } @@ -896,8 +936,12 @@ static UINT8 ArchiveValue(UINT8 **p, int TABLESINDEX, int myindex) { mapheader_t *header = *((mapheader_t **)lua_touserdata(gL, myindex)); if (!header) + { WRITEUINT8(*p, ARCH_NULL); - else { + return 3; + } + else + { WRITEUINT8(*p, ARCH_MAPHEADER); WRITEUINT16(*p, header - *mapheaderinfo); } @@ -1003,19 +1047,23 @@ static void ArchiveTables(UINT8 **p) e = ArchiveValue(p, TABLESINDEX, -2); // key should be either a number or a string, ArchiveValue can handle this. if (e == 2) // invalid key type (function, thread, lightuserdata, or anything we don't recognise) { - lua_pushvalue(gL, -2); - CONS_Alert(CONS_ERROR, "Index '%s' (%s) of table %d could not be archived!\n", lua_tostring(gL, -1), luaL_typename(gL, -1), i); - lua_pop(gL, 1); + CONS_Alert(CONS_ERROR, "Index '%s' (%s) of table %d could not be archived!\n", lua_tostring(gL, -2), luaL_typename(gL, -2), i); } + else if (e == 3) // nil key due to invalid userdata. NOT an error. + { + lua_pop(gL, 1); + continue; + } + // Write value e = ArchiveValue(p, TABLESINDEX, -1); if (e == 1) + { n++; // the table contained a new table we'll have to archive. :( + } else if (e == 2) // invalid value type { - lua_pushvalue(gL, -2); - CONS_Alert(CONS_ERROR, "Type of value for table %d entry '%s' (%s) could not be archived!\n", i, lua_tostring(gL, -1), luaL_typename(gL, -1)); - lua_pop(gL, 1); + CONS_Alert(CONS_ERROR, "Type of value for table %d entry '%s' (%s) could not be archived!\n", i, lua_tostring(gL, -2), luaL_typename(gL, -1)); } lua_pop(gL, 1); diff --git a/src/m_argv.c b/src/m_argv.c index a3708d033..2ec1b188a 100644 --- a/src/m_argv.c +++ b/src/m_argv.c @@ -69,16 +69,18 @@ INT32 M_CheckProtoParam(const char *check) for (i = 1; i < myargc; i++) { - if (strncmp(myargv[i], "srb2kart://", 11) == 0) + if (strncmp(myargv[i], "srb2kart://", 11) == 0) { - if (strncmp(myargv[i]+11, check, strlen(check))==0) + if (strncmp(myargv[i]+11, check, strlen(check)) == 0) { found = i; return i; } } } + found = 0; + return 0; } @@ -93,7 +95,7 @@ const char *M_GetProtoParam(void) for (i = 1; i < myargc; i++) { - if (strncmp(myargv[i], "srb2kart://", 11) == 0) + if (strncmp(myargv[i], "srb2kart://", 11) == 0) { string = strchr(myargv[i], '/'); string = strchr(string+1, '/'); diff --git a/src/m_emotes.cpp b/src/m_emotes.cpp index 9ae434547..57058ef23 100644 --- a/src/m_emotes.cpp +++ b/src/m_emotes.cpp @@ -92,7 +92,7 @@ void M_LoadEmotes(UINT16 wadnum) if (emote_name.size() > MAXEMOTENAME) { CONS_Alert(CONS_WARNING, "EMOTES: Emote name is too long, truncating. (file %s, line %d)\n", wadfiles[wadnum]->filename, linenum); - emote_name = emote_name.substr(0, MAXEMOTENAME); + emote_name.resize(MAXEMOTENAME); } emote = &emotes[emote_name]; @@ -139,7 +139,7 @@ void M_LoadEmotes(UINT16 wadnum) if (framelumpname.size() > 8) { CONS_Alert(CONS_WARNING, "EMOTES: Frame %d name is too long. (file %s, line %d)", numframes, wadfiles[wadnum]->filename, linenum); - framelumpname = framelumpname.substr(0, 8); + framelumpname.resize(8); } std::strncpy(emote->frames[numframes], framelumpname.c_str(), framelumpname.size()+1); diff --git a/src/m_menu.c b/src/m_menu.c index 95824c7dd..6eaccdce0 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -702,7 +702,13 @@ static void M_CheckStringItem(void) // Just in case memset(menu_text_input_buf, 0, sizeof menu_text_input_buf); - M_TextInputInit(&menuinput, menu_text_input_buf, sizeof menu_text_input_buf); + + // special case: name input, cap it to prevent writing outside the textbox + // kinda ugly but itll work + if (cv == &cv_playername) + M_TextInputInit(&menuinput, menu_text_input_buf, MAXPLAYERNAME +1); + else + M_TextInputInit(&menuinput, menu_text_input_buf, sizeof menu_text_input_buf); M_TextInputSetString(&menuinput, cv->string); } @@ -3107,7 +3113,7 @@ static void M_AddonsInternal(void) break; } - strlcpy(menupath, pathname, 1024); + strlcpy(menupath, pathname, MAXFILEPATH); menupathindex[(menudepthleft = menudepth-1)] = strlen(menupath) + 1; if (menupath[menupathindex[menudepthleft]-2] != PATHSEP[0]) @@ -3220,9 +3226,9 @@ static void M_DrawTemperature(INT32 x, fixed_t t) static char *M_AddonsHeaderPath(void) { UINT32 len; - static char header[1024]; + static char header[MAXFILEPATH]; - strlcpy(header, va("%s folder%s", cv_addons_option.string, menupath+menupathindex[menudepth-1]-1), 1024); + strlcpy(header, va("%s folder%s", cv_addons_option.string, menupath+menupathindex[menudepth-1]-1), MAXFILEPATH); len = strlen(header); if (len > 34) { @@ -3958,9 +3964,7 @@ static void PrepReplayList(boolean reset) Lock_search_state(); - if (demolist_all) - Z_Free(demolist_all); - + Z_Free(demolist_all); demolist_all = Z_Calloc(sizeof(menudemo_t) * sizedirmenu, PU_STATIC, NULL); for (i = 0; i < sizedirmenu; i++) @@ -3978,9 +3982,9 @@ static void PrepReplayList(boolean reset) else { demolist_all[i].type = MD_NOTLOADED; - // FIXME - do something with buffer sizes. menupath is 1024 chars but filepath is only - // 256. I'm not really sure what to do here but don't want to leave warnings... - snprintf(demolist_all[i].filepath, 255, "%.254s%s", menupath, dirmenu[i] + DIR_STRING); + snprintf(demolist_all[i].filepath, sizeof(demolist_all[i].filepath), + // 255 = UINT8 limit. dirmenu entries are restricted to this length (see DIR_LEN). + "%s%.255s", menupath, dirmenu[i] + DIR_STRING); sprintf(demolist_all[i].title, "....."); } } @@ -4335,7 +4339,7 @@ static void DrawReplayHutReplayInfo(void) static void M_DrawReplayHut(void) { INT32 x, y, cursory = 0; - INT16 i; + INT32 i; INT16 replaylistitem = currentMenu->numitems-2; boolean processed_one_this_frame = false; const INT32 scaledviewheight = (vid.height/vid.dup); @@ -4408,7 +4412,7 @@ static void M_DrawReplayHut(void) V_DrawCenteredString(160, 100, V_ALLOWLOWERCASE, msg); } - for (i = 0; i < (INT16)replayqueryfound; i++) + for (i = 0; i < (INT32)replayqueryfound; i++) { INT32 localy = y+i*10; INT32 localx = x; @@ -7175,17 +7179,21 @@ static void M_DrawLevelSelectOnly(boolean leftfade, boolean rightfade) namescroll = 0; } - if (renderisnewtic) namescroll++; + if (renderisnewtic) + namescroll++; char *addonname = wadfiles[mapwads[cv_nextmap.value-1]]->filename; INT32 len; INT32 charlimit = min((size_t)(21 + (dupadjust/5)), sizeof(namescrollbuf)-1); + nameonly(addonname); len = strlen(addonname); + if (len > charlimit) M_ScrollString(addonname, len, namescrollbuf, charlimit, namescroll); else - strncpy(namescrollbuf, addonname, sizeof(namescrollbuf)); + strncpy(namescrollbuf, addonname, sizeof(namescrollbuf) - 1); + V_DrawThinString(x+w+5, y+i-8, V_TRANSLUCENT|MENUCAPS, namescrollbuf); // variable reuse... } @@ -8275,12 +8283,12 @@ static void M_DrawSetupMultiPlayerMenu(void) sprframe = &sprdef->spriteframes[frame]; - //minenice's speen css, it's a piece of shit but hey + // minenice's speen css, it's a piece of shit but hey speenframe = (I_GetTime()*cv_skinselectspin.value/TICRATE + 1)%8; - //this is a very shitty solution for checking if a sprite needs flipping - //but it works - if ((sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe]) && (speenframe > 4)) + // this is a very shitty solution for checking if a sprite needs flipping + // but it works + if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) flags = V_FLIP; // This sprite is left/right flipped! patch = (patch_t *)W_CachePatchNum(sprframe->lumppat[speenframe], PU_PATCH); @@ -9442,9 +9450,8 @@ static void M_VideoModeMenu(INT32 choice) memset(modedescs, 0, sizeof(modedescs)); -#if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) VID_PrepareModeList(); // FIXME: hack -#endif + vidm_nummodes = 0; vidm_selected = 0; nummodes = VID_NumModes(); @@ -9636,7 +9643,7 @@ static void M_DrawLocalSkinMenu(void) //this is a very shitty solution for checking if a sprite needs flipping //but it works - if ((sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe]) && (speenframe > 4)) + if ((speenframe > 4) && (sprframe->lumppat[speenframe] == sprframe->lumppat[8-speenframe])) { flags = V_FLIP; // This sprite is left/right flipped! } @@ -10335,9 +10342,9 @@ static const char *M_GetDiscordName(discordRequest_t *r) return ""; if (cv_discordstreamer.value) - return r->username; + return DRPC_HideUsername(r->username); - return va("%s#%s", r->username, r->discriminator); + return r->username; } // (this goes in k_hud.c when merged into v2) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 74ee714dd..6bda9c733 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -645,10 +645,20 @@ static menuitem_t OP_ControlsMenu[] = {IT_CALL | IT_STRING, NULL, "Player 3 Controls...", &M_Setup3PControlsMenu, 30}, {IT_CALL | IT_STRING, NULL, "Player 4 Controls...", &M_Setup4PControlsMenu, 40}, - {IT_SUBMENU | IT_STRING, NULL, "Mouse Options...", &OP_MouseOptionsDef, 60}, + {IT_SUBMENU | IT_STRING, NULL, "Mouse Options...", &OP_MouseOptionsDef, 55}, - {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 80}, - {IT_STRING | IT_CVAR, NULL, "Digital turn easing", &cv_turnsmooth, 90}, + {IT_STRING | IT_CVAR, NULL, "Controls per key", &cv_controlperkey, 75}, + + {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P1)", &cv_turnsmooth[0], 85}, + {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P2)", &cv_turnsmooth[1], 95}, + {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P3)", &cv_turnsmooth[2], 105}, + {IT_STRING | IT_CVAR, NULL, "Digital turn easing (P4)", &cv_turnsmooth[3], 115}, + + // i hate our menus sincerly + {IT_STRING | IT_CVAR, NULL, "Lite Steer (P1)", &cv_litesteer[0], 135}, + {IT_STRING | IT_CVAR, NULL, "Lite Steer (P2)", &cv_litesteer[1], 145}, + {IT_STRING | IT_CVAR, NULL, "Lite Steer (P3)", &cv_litesteer[2], 155}, + {IT_STRING | IT_CVAR, NULL, "Lite Steer (P4)", &cv_litesteer[3], 165}, }; static const char* OP_ControlsTooltips[] = @@ -659,7 +669,15 @@ static const char* OP_ControlsTooltips[] = "Setup player 4 controls.", "Options for mouse control.", "Allowed amount of controls per key.", - "Turn smoothing for non-analog turning.", + "Turn smoothing for non-analog turning (Player 1).", + "Turn smoothing for non-analog turning (Player 2).", + "Turn smoothing for non-analog turning (Player 3).", + "Turn smoothing for non-analog turning (Player 4).", + + "Hold DOWN on d-pad/keyboard for shallow turns (Player 1).", + "Hold DOWN on d-pad/keyboard for shallow turns (Player 2).", + "Hold DOWN on d-pad/keyboard for shallow turns (Player 3).", + "Hold DOWN on d-pad/keyboard for shallow turns (Player 4).", }; static menuitem_t OP_AllControlsMenu[] = @@ -950,16 +968,16 @@ static const char* OP_ExpTooltips[] = NULL, "How far Mobj interpolation should take effect.", "When weather is on this will cut the object amount used in half.", - "Sets minimum sector brightness, useful for dark areas", + "Sets minimum sector brightness, useful for dark areas.", //"Should the directional lightning be randomized each map?\nTakes effect on next map load.", "Toggle being able to see the sky.", - "Change the FPS counter sampling method\nInaccurate updates slower and might miss frame drops and such\nAccurate updates faster and is more accurate, but might be less readable", // how to ingles?? - "Skips rendering frames if game logic takes too long preventing issues during performance drops." // idk im shit as describing things + "Change the FPS counter sampling method\nInaccurate updates slower\nand might miss sudden framerate changes and drops,\nproviding a more averaged result.\nAccurate updates faster, but might be less readable.", // how to ingles?? + "Skips rendering frames if game logic takes too long\npreventing gameplay issues during performance drops.", // idk im shit as describing things "Different methods of scaling the votescreen backgrounds.", #ifdef HWRENDER "Should the game do Screen Textures? Provides a good boost to frames\nat the cost of some visual effects not working when disabled.", #ifdef USE_FBO_OGL - "Allows the game to downsample from a higher resolution than your display\nin OpenGL renderer mode. Requires a GPU with atleast OpenGL 3.0 support.", + "Allows the game to downsample from a higher resolution\nthan your display in OpenGL renderer mode.\nRequires a GPU with atleast OpenGL 2.1 support.", #endif "Change the bit depth of the Lookup Palette in Palette rendering mode\n 16 bits is like software looks ingame\nwhile 24 bits is how software looks in screenshots.", #endif @@ -1357,15 +1375,15 @@ static menuitem_t OP_Player4CamOptionsMenu[] = static const char* OP_PlayerCamOptionsTooltips[] = { NULL, - "Should the Camera flip on gravity flipped sections?.", + "Should the Camera flip on gravity flipped sections?", "Camera distance relative to the Player.", - "Height of the Camera", - "Pitch Camera on Upwards or Downhill Slopes", - "Speed of the Camera", - "Should looking back inherit the Players Momentum?\nEither inherit Player Momentum or double of it\nmay make looking back while boosting or going in high speed less jarring", + "Height of the Camera.", + "Pitch Camera on Upwards or Downhill Slopes.", + "Speed of the Camera.", + "Should looking back inherit the Players Momentum?\nEither inherit Player Momentum or double of it\nmay make looking back while boosting or going in high speed less jarring.", "Allows looking up/down by holding\naim forward/backward while standing still.", - "Speed of the Freecam/Spectator Camera", - "Toggle between Third or First Person camera", + "Speed of the Freecam/Spectator Camera.", + "Toggle between Third or First Person camera.", }; // Ok it's still called chatoptions but we'll put ping display in here to be clean @@ -1745,7 +1763,7 @@ static const char* OP_PlayerDistortTooltips[] = "Distance object rotation should be visable.", "Player rotation when sliptiding.", "Rotation of a player's boost trails and drift sparks.", - "Should banans rotate when thrown?\nAnd should they stay rotated when on the ground?.", + "Should banans rotate when thrown?\nAnd should they stay rotated when on the ground?", "Player squash and stretch.", "Player landing sound effect.", "Kart hopping while drifting. This is purely visual.", @@ -2424,7 +2442,7 @@ menu_t OP_MainDef = NULL }; -menu_t OP_ControlsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_ControlsMenu, &OP_MainDef, 60, 30, OP_ControlsTooltips); +menu_t OP_ControlsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_ControlsMenu, &OP_MainDef, 40, 15, OP_ControlsTooltips); //WTF menu_t OP_MouseOptionsDef = DEFAULTMENUSTYLE("M_CONTRO", OP_MouseOptionsMenu, &OP_ControlsDef, 60, 30, OP_MouseTooltips); menu_t OP_AllControlsDef = CONTROLMENUSTYLE(OP_AllControlsMenu, &OP_ControlsDef); diff --git a/src/m_textinput.c b/src/m_textinput.c index 882d35e35..049222701 100644 --- a/src/m_textinput.c +++ b/src/m_textinput.c @@ -239,8 +239,8 @@ void M_TextInputClear(textinput_t *input) void M_TextInputSetString(textinput_t *input, const char *c) { memset(input->buffer, 0, input->buffer_size); - strcpy(input->buffer, c); - input->cursor = input->select = input->length = strlen(c); + strncpy(input->buffer, c, input->buffer_size); + input->cursor = input->select = input->length = strlen(input->buffer); } static boolean M_TextInputHandleBase(textinput_t *input, INT32 key, boolean emotes) diff --git a/src/p_map.c b/src/p_map.c index 4a880ad42..9e428d999 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -708,7 +708,7 @@ static boolean PIT_CheckThing(mobj_t *thing) HU_SetCEchoFlags(0); HU_SetCEchoDuration(5); HU_DoCEcho(va("%s\\was hit by a kitchen sink.\\\\\\\\", player_names[thing->player-players])); - I_OutputMsg("%s was hit by a kitchen sink.\n", player_names[thing->player-players]); + //I_OutputMsg("%s was hit by a kitchen sink.\n", player_names[thing->player-players]); P_DamageMobj(thing, tmthing, tmthing->target, DMG_INSTAKILL); P_KillMobj(tmthing, thing, thing); } @@ -977,7 +977,7 @@ static boolean PIT_CheckThing(mobj_t *thing) HU_SetCEchoFlags(0); HU_SetCEchoDuration(5); HU_DoCEcho(va("%s\\was hit by a kitchen sink.\\\\\\\\", player_names[tmthing->player-players])); - I_OutputMsg("%s was hit by a kitchen sink.\n", player_names[tmthing->player-players]); + //I_OutputMsg("%s was hit by a kitchen sink.\n", player_names[tmthing->player-players]); P_DamageMobj(tmthing, thing, thing->target, DMG_INSTAKILL); P_KillMobj(thing, tmthing, tmthing); } diff --git a/src/p_mobj.c b/src/p_mobj.c index c16d5ce4c..2bd58e8cf 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -11889,7 +11889,7 @@ void P_SpawnHoops(mapthing_t *mthing) z += P_GetSectorFloorZAt(sec, x, y); - hoopcenter->z -= hoopcenter->height/2; + hoopcenter->z = z - hoopcenter->height/2; P_UnsetThingPosition(hoopcenter); hoopcenter->x = x; diff --git a/src/p_saveg.c b/src/p_saveg.c index a4b343554..d3a162e2d 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -61,7 +61,7 @@ typedef enum // // P_ArchivePlayer // -static inline void P_ArchivePlayer(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_ArchivePlayer(savebuffer_t *save) { const player_t *player = &players[consoleplayer]; INT32 pllives = player->lives; @@ -85,7 +85,7 @@ static inline void P_ArchivePlayer(savebuffer_t *save) // // P_UnArchivePlayer // -static inline void P_UnArchivePlayer(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_UnArchivePlayer(savebuffer_t *save) { savedata.skincolor = READUINT8(save->p); savedata.skin = READUINT8(save->p); @@ -1043,25 +1043,25 @@ typedef enum tc_end } specials_e; -static inline UINT32 SaveMobjnum(const mobj_t *mobj) +FUNCINLINE static ATTRINLINE UINT32 SaveMobjnum(const mobj_t *mobj) { if (mobj) return mobj->mobjnum; return 0; } -static inline UINT32 SaveSector(const sector_t *sector) +FUNCINLINE static ATTRINLINE UINT32 SaveSector(const sector_t *sector) { if (sector) return (UINT32)(sector - sectors); return 0xFFFFFFFF; } -static inline UINT32 SaveLine(const line_t *line) +FUNCINLINE static ATTRINLINE UINT32 SaveLine(const line_t *line) { if (line) return (UINT32)(line - lines); return 0xFFFFFFFF; } -static inline UINT32 SavePlayer(const player_t *player) +FUNCINLINE static ATTRINLINE UINT32 SavePlayer(const player_t *player) { if (player) return (UINT32)(player - players); return 0xFFFFFFFF; @@ -1476,7 +1476,7 @@ static void SaveElevatorThinker(savebuffer_t *save, const thinker_t *th, const U // // Saves a scroll_t thinker // -static inline void SaveScrollThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) +FUNCINLINE static ATTRINLINE void SaveScrollThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) { const scroll_t *ht = (const void *)th; WRITEUINT8(save->p, type); @@ -1497,7 +1497,7 @@ static inline void SaveScrollThinker(savebuffer_t *save, const thinker_t *th, co // // Saves a friction_t thinker // -static inline void SaveFrictionThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) +FUNCINLINE static ATTRINLINE void SaveFrictionThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) { const friction_t *ht = (const void *)th; WRITEUINT8(save->p, type); @@ -1513,7 +1513,7 @@ static inline void SaveFrictionThinker(savebuffer_t *save, const thinker_t *th, // // Saves a pusher_t thinker // -static inline void SavePusherThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) +FUNCINLINE static ATTRINLINE void SavePusherThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) { const pusher_t *ht = (const void *)th; WRITEUINT8(save->p, type); @@ -1598,7 +1598,7 @@ static void SaveDisappearThinker(savebuffer_t *save, const thinker_t *th, const // // Saves a polyrotate_t thinker // -static inline void SavePolyrotatetThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) +FUNCINLINE static ATTRINLINE void SavePolyrotatetThinker(savebuffer_t *save, const thinker_t *th, const UINT8 type) { const polyrotate_t *ht = (const void *)th; WRITEUINT8(save->p, type); @@ -1935,25 +1935,25 @@ mobj_t *P_FindNewPosition(UINT32 oldposition) return NULL; } -static inline mobj_t *LoadMobj(UINT32 mobjnum) +FUNCINLINE static ATTRINLINE mobj_t *LoadMobj(UINT32 mobjnum) { if (mobjnum == 0) return NULL; return (mobj_t *)(size_t)mobjnum; } -static inline sector_t *LoadSector(UINT32 sector) +FUNCINLINE static ATTRINLINE sector_t *LoadSector(UINT32 sector) { if (sector >= numsectors) return NULL; return §ors[sector]; } -static inline line_t *LoadLine(UINT32 line) +FUNCINLINE static ATTRINLINE line_t *LoadLine(UINT32 line) { if (line >= numlines) return NULL; return &lines[line]; } -static inline player_t *LoadPlayer(UINT32 player) +FUNCINLINE static ATTRINLINE player_t *LoadPlayer(UINT32 player) { if (player >= MAXPLAYERS) return NULL; return &players[player]; @@ -2529,7 +2529,7 @@ static void LoadScrollThinker(savebuffer_t *save, actionf_p1 thinker) // // Loads a friction_t from a save game // -static inline void LoadFrictionThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadFrictionThinker(savebuffer_t *save, actionf_p1 thinker) { friction_t *ht = (friction_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2576,7 +2576,7 @@ static void LoadPusherThinker(savebuffer_t *save, actionf_p1 thinker) // // Loads a laserthink_t from a save game // -static inline void LoadLaserThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadLaserThinker(savebuffer_t *save, actionf_p1 thinker) { laserthink_t *ht = (laserthink_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2621,7 +2621,7 @@ FUNCINLINE static ATTRINLINE void LoadLightlevelThinker(savebuffer_t *save, acti // // Loads a executor_t from a save game // -static inline void LoadExecutorThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadExecutorThinker(savebuffer_t *save, actionf_p1 thinker) { executor_t *ht = (executor_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2639,7 +2639,7 @@ static inline void LoadExecutorThinker(savebuffer_t *save, actionf_p1 thinker) // // Loads a disappear_t thinker // -static inline void LoadDisappearThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadDisappearThinker(savebuffer_t *save, actionf_p1 thinker) { disappear_t *ht = (disappear_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2660,7 +2660,7 @@ static inline void LoadDisappearThinker(savebuffer_t *save, actionf_p1 thinker) // // Loads a polyrotate_t thinker // -static inline void LoadPolyrotatetThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadPolyrotatetThinker(savebuffer_t *save, actionf_p1 thinker) { polyrotate_t *ht = (polyrotate_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2720,7 +2720,7 @@ static void LoadPolymoveThinker(savebuffer_t *save, actionf_p1 thinker) // // Loads a polywaypoint_t thinker // -static inline void LoadPolywaypointThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadPolywaypointThinker(savebuffer_t *save, actionf_p1 thinker) { polywaypoint_t *ht = (polywaypoint_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2776,7 +2776,7 @@ static inline void LoadPolywaypointThinker(savebuffer_t *save, actionf_p1 thinke // // loads a polyslidedoor_t thinker // -static inline void LoadPolyslidedoorThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadPolyslidedoorThinker(savebuffer_t *save, actionf_p1 thinker) { polyslidedoor_t *ht = (polyslidedoor_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2814,7 +2814,7 @@ static inline void LoadPolyslidedoorThinker(savebuffer_t *save, actionf_p1 think // // Loads a polyswingdoor_t thinker // -static inline void LoadPolyswingdoorThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadPolyswingdoorThinker(savebuffer_t *save, actionf_p1 thinker) { polyswingdoor_t *ht = (polyswingdoor_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -2847,7 +2847,7 @@ static inline void LoadPolyswingdoorThinker(savebuffer_t *save, actionf_p1 think // // Loads a polydisplace_t thinker // -static inline void LoadPolydisplaceThinker(savebuffer_t *save, actionf_p1 thinker) +FUNCINLINE static ATTRINLINE void LoadPolydisplaceThinker(savebuffer_t *save, actionf_p1 thinker) { polydisplace_t *ht = (polydisplace_t*)Z_LevelPoolMalloc(sizeof (*ht)); ht->thinker.alloctype = TAT_LEVELPOOL; @@ -3115,7 +3115,7 @@ static void P_NetUnArchiveThinkers(savebuffer_t *save) #define PD_FLAGS 0x01 #define PD_TRANS 0x02 -static inline void P_ArchivePolyObj(savebuffer_t *save, polyobj_t *po) +FUNCINLINE static ATTRINLINE void P_ArchivePolyObj(savebuffer_t *save, polyobj_t *po) { UINT8 diff = 0; WRITEINT32(save->p, po->id); @@ -3137,7 +3137,7 @@ static inline void P_ArchivePolyObj(savebuffer_t *save, polyobj_t *po) WRITEINT32(save->p, po->translucency); } -static inline void P_UnArchivePolyObj(savebuffer_t *save, polyobj_t *po) +FUNCINLINE static ATTRINLINE void P_UnArchivePolyObj(savebuffer_t *save, polyobj_t *po) { INT32 id; UINT32 angle; @@ -3172,7 +3172,7 @@ static inline void P_UnArchivePolyObj(savebuffer_t *save, polyobj_t *po) Polyobj_MoveOnLoad(po, angle, x, y); } -static inline void P_ArchivePolyObjects(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_ArchivePolyObjects(savebuffer_t *save) { INT32 i; @@ -3185,7 +3185,7 @@ static inline void P_ArchivePolyObjects(savebuffer_t *save) P_ArchivePolyObj(save, &PolyObjects[i]); } -static inline void P_UnArchivePolyObjects(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_UnArchivePolyObjects(savebuffer_t *save) { INT32 i, numSavedPolys; @@ -3203,7 +3203,7 @@ static inline void P_UnArchivePolyObjects(savebuffer_t *save) // // P_FinishMobjs // -static inline void P_FinishMobjs(void) +FUNCINLINE static ATTRINLINE void P_FinishMobjs(void) { thinker_t *currentthinker; mobj_t *mobj; @@ -3220,7 +3220,7 @@ static inline void P_FinishMobjs(void) } } -static inline mobj_t *RelinkMobj(mobj_t **ptr) +FUNCINLINE static ATTRINLINE mobj_t *RelinkMobj(mobj_t **ptr) { UINT32 temp = (UINT32)(size_t)*ptr; *ptr = NULL; @@ -3269,7 +3269,7 @@ static void P_RelinkPointers(void) // // P_NetArchiveSpecials // -static inline void P_NetArchiveSpecials(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_NetArchiveSpecials(savebuffer_t *save) { size_t i, z; @@ -3347,7 +3347,7 @@ static void P_NetUnArchiveSpecials(savebuffer_t *save) // ======================================================================= // Misc // ======================================================================= -static inline void P_ArchiveMisc(savebuffer_t *save) +FUNCINLINE static ATTRINLINE void P_ArchiveMisc(savebuffer_t *save) { if (gamecomplete) WRITEINT16(save->p, gamemap | 8192); @@ -3360,7 +3360,7 @@ static inline void P_ArchiveMisc(savebuffer_t *save) WRITESTRINGN(save->p, timeattackfolder, sizeof(timeattackfolder)); } -static inline void P_UnArchiveSPGame(savebuffer_t *save, INT16 mapoverride) +FUNCINLINE static ATTRINLINE void P_UnArchiveSPGame(savebuffer_t *save, INT16 mapoverride) { char testname[sizeof(timeattackfolder)]; @@ -3531,7 +3531,8 @@ static void P_ReloadSaveLevelData(void) ss->floorpic_angle = spawnss->floorpic_angle; ss->ceilingpic_angle = spawnss->ceilingpic_angle; ss->tag = spawnss->tag; - ss->firsttag = ss->nexttag = -1; + ss->firsttag = spawnss->firsttag; + ss->nexttag = spawnss->nexttag; if (ss->ffloors) { @@ -3556,7 +3557,8 @@ static void P_ReloadSaveLevelData(void) li->callcount = 0; li->tag = spawnli->tag; - li->firsttag = li->nexttag = -1; + li->firsttag = spawnli->firsttag; + li->nexttag = spawnli->nexttag; if (li->sidenum[0] != 0xffff) { @@ -3580,8 +3582,6 @@ static void P_ReloadSaveLevelData(void) si->midtexture = spawnsi->midtexture; } } - - P_InitTagLists(); } FUNCINLINE static ATTRINLINE boolean P_NetUnArchiveMisc(savebuffer_t *save, boolean reloading) diff --git a/src/p_setup.c b/src/p_setup.c index 2ccbd1821..73445b6b3 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -1983,11 +1983,12 @@ static void P_LoadMapData(const virtres_t* virt) P_LoadLinedefs(virtlinedefs->data); P_LoadSidedefs(virtsidedefs->data); P_LoadThings(virtthings->data); + P_InitTagLists(); // Create xref tables for tags // Copy relevant map data for NetArchive purposes. - spawnsectors = Z_Calloc(numsectors * sizeof(*sectors), PU_LEVEL, NULL); - spawnlines = Z_Calloc(numlines * sizeof(*lines), PU_LEVEL, NULL); - spawnsides = Z_Calloc(numsides * sizeof(*sides), PU_LEVEL, NULL); + spawnsectors = Z_Malloc(numsectors * sizeof(*sectors), PU_LEVEL, NULL); + spawnlines = Z_Malloc(numlines * sizeof(*lines), PU_LEVEL, NULL); + spawnsides = Z_Malloc(numsides * sizeof(*sides), PU_LEVEL, NULL); memcpy(spawnsectors, sectors, numsectors * sizeof(*sectors)); memcpy(spawnlines, lines, numlines * sizeof(*lines)); diff --git a/src/p_spec.c b/src/p_spec.c index 7b4b45358..e7b032131 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -2091,8 +2091,7 @@ static void P_ProcessLineSpecial(line_t *line, mobj_t *mo, sector_t *callsec) // Change the music and apply position/fade operations else { - strncpy(mapmusic.name, sides[line->sidenum[0]].text, 7); - mapmusic.name[6] = 0; + strlcpy(mapmusic.name, sides[line->sidenum[0]].text, sizeof(mapmusic.name)); mapmusic.flags = tracknum & MUSIC_TRACKMASK; if (!(line->flags & ML_BLOCKMONSTERS)) @@ -5387,7 +5386,6 @@ void P_SpawnSpecials(INT32 fromnetsave, boolean reloadinggamestate) // set current weather curWeather = mapheaderinfo[gamemap-1]->weather; - P_InitTagLists(); // Create xref tables for tags P_SearchForDisableLinedefs(); // Disable linedefs are now allowed to disable *any* line P_SpawnScrollers(); // Add generalized scrollers diff --git a/src/p_user.c b/src/p_user.c index a5c01152a..b99998844 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -3315,7 +3315,7 @@ static ticcmd_t *P_CameraCmd(camera_t *cam, UINT8 num) cmd->sidemove = (SINT8)(cmd->sidemove + side); } - lang += (cmd->angleturn<<16); + lang += (cmd->angleturn << 16); cam->localangle = lang; if (!cam->reset_aiming) @@ -3821,7 +3821,13 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall if (demo.playback) { - focusangle = mo->angle; + // Hack-adjacent. + // Sometimes stale ticcmds send a weird angle at the start of the race. + // P_UpdatePlayerAngle knows to ignore cmd angle when you literally can't turn, so we do the same here. + if (leveltime > starttime) + focusangle = player->cmd.angleturn << 16; + else + focusangle = mo->angle; // Just use something known sane. focusaiming = 0; } else if (P_IsLocalPlayer(player)) diff --git a/src/r_bsp.cpp b/src/r_bsp.cpp index 6ef63739f..87d775c87 100644 --- a/src/r_bsp.cpp +++ b/src/r_bsp.cpp @@ -77,7 +77,7 @@ void R_ClearDrawSegs(void) // CPhipps - // Instead of clipsegs, let's try using an array with one entry for each column, // indicating whether it's blocked by a solid wall yet or not. -UINT8 *solidcol; +UINT8 *solidcol = NULL; void R_AllocClipSegMemory(void) { diff --git a/src/r_data.c b/src/r_data.c index 6c999d1ae..93ad621fa 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -90,21 +90,21 @@ INT32 numtextures = 0; // total number of textures found, // size of following tables texture_t **textures = NULL; -static UINT32 **texturecolumnofs; // column offset lookup table for each texture -UINT8 **texturecache; // graphics data for each generated full-size texture +static UINT32 **texturecolumnofs = NULL; // column offset lookup table for each texture +UINT8 **texturecache = NULL; // graphics data for each generated full-size texture // texture width is a power of 2, so it can easily repeat along sidedefs using a simple mask -static INT32 *texturewidth; +static INT32 *texturewidth = NULL; -fixed_t *textureheight; // needed for texture pegging +fixed_t *textureheight = NULL; // needed for texture pegging -INT32 *texturetranslation; +INT32 *texturetranslation = NULL; // needed for pre rendering -sprcache_t *spritecachedinfo; +sprcache_t *spritecachedinfo = NULL; -lighttable_t *colormaps; -UINT8 *encoremap; +lighttable_t *colormaps = NULL; +UINT8 *encoremap = NULL; #ifdef HASINVERT UINT8 invertmap[256]; #endif @@ -1391,6 +1391,7 @@ void R_ReInitColormaps(UINT16 num, lumpnum_t newencoremap) // Load in the light tables, now 64k aligned for smokie... lump = W_GetNumForName(colormap); + if (lump == LUMPERROR) lump = basecolormaplump; else diff --git a/src/r_draw.cpp b/src/r_draw.cpp index c8a09745a..39f8918bb 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -41,8 +41,7 @@ /** \brief view info */ -INT32 linesize, viewwidth, viewheight, viewwindowx, viewwindowy; -UINT8 *renderscreen; // haleyjd +INT32 viewwidth, viewheight, viewwindowx, viewwindowy; // ========================================================================= // COLUMN DRAWING CODE STUFF @@ -489,6 +488,92 @@ void R_FlushTranslationColormapCache(void) // in reality, the few routines that can work for either mode, are // put here +enum columncontext_e columncontext = COLUMNCONTEXT_DIRECT; + +enum ColumnFlushType +{ + FLUSH_NONE = 0x0000, + FLUSH_OPAQUE = 0x0001, + FLUSH_TRANS = 0x0002, + FLUSH_COLORMAP = 0x0004, + FLUSH_COLORMAP_TRANS = 0x0008, +}; + +typedef struct drawcolumndata_temp_s +{ + INT32 x; + INT32 yl[8], yh[8]; + + // e6y: resolution limitation is removed + UINT8 *buf; + + INT32 startx; + ColumnFlushType type; + INT32 commontop, commonbot; + UINT8 *transmap; + // SoM 7-28-04: Fix the fuzz problem. + UINT8 *translation; +} drawcolumndata_temp_t; + +drawcolumndata_temp_t temp_dc = {}; + +// +// Error functions that will abort if R_FlushColumns tries to flush +// columns without a column type. +// +FUNCNORETURN static ATTRNORETURN void R_FlushWholeError(void) +{ + I_Error("R_FlushWholeColumns called without being initialized.\n"); +} + +FUNCNORETURN static ATTRNORETURN void R_FlushHTError(void) +{ + I_Error("R_FlushHTColumns called without being initialized.\n"); +} + +FUNCNORETURN static ATTRNORETURN void R_QuadFlushError(void) +{ + I_Error("R_FlushQuadColumn called without being initialized.\n"); +} + +static void (*R_FlushWholeColumns)(void) = R_FlushWholeError; +static void (*R_FlushHTColumns)(void) = R_FlushHTError; +static void (*R_FlushQuadColumn)(void) = R_QuadFlushError; + +static void R_FlushColumns(void) +{ + if (temp_dc.x != 8 || temp_dc.commontop >= temp_dc.commonbot) + R_FlushWholeColumns(); + else + { + R_FlushHTColumns(); + R_FlushQuadColumn(); + } + + temp_dc.x = 0; +} + +// +// R_ResetColumnBuffer +// +// haleyjd 09/13/04: new function to call from main rendering loop +// which gets rid of the unnecessary reset of various variables during +// column drawing. +// +void R_ResetColumnBuffer(void) +{ + // haleyjd 10/06/05: this must not be done if x == 0! + if (temp_dc.x) + { + R_FlushColumns(); + } + + temp_dc.type = FLUSH_NONE; + R_FlushWholeColumns = R_FlushWholeError; + R_FlushHTColumns = R_FlushHTError; + R_FlushQuadColumn = R_QuadFlushError; +} + /** \brief The R_InitViewBuffer function Creates lookup tables for getting the framebuffer address @@ -521,40 +606,35 @@ static void R_AllocViewMemory(void) R_AllocVisSpriteMemory(); } - -void R_InitViewBuffer(INT32 width, INT32 height) +void R_InitViewBuffer(void) { - if (width > MAXVIDWIDTH) - width = MAXVIDWIDTH; - if (height > MAXVIDHEIGHT) - height = MAXVIDHEIGHT; - R_AllocViewMemory(); viewwindowx = 0; viewwindowy = 0; - linesize = vid.width; // killough 11/98 - renderscreen = vid.screens[0]; // haleyjd 07/02/14 -} + INT32 bufsize = (vid.width * 8) * sizeof(*temp_dc.buf); -/** \brief viewborder patches lump numbers -*/ -lumpnum_t viewborderlump[8]; + if (temp_dc.buf) + { +#if defined(__SSE__) + aligned_free(temp_dc.buf); +#else + Z_Free(temp_dc.buf); +#endif + } -/** \brief Store the lumpnumber of the viewborder patches -*/ + memset(&temp_dc, 0, sizeof(temp_dc)); -void R_InitViewBorder(void) -{ - viewborderlump[BRDR_T] = W_GetNumForName("brdr_t"); - viewborderlump[BRDR_B] = W_GetNumForName("brdr_b"); - viewborderlump[BRDR_L] = W_GetNumForName("brdr_l"); - viewborderlump[BRDR_R] = W_GetNumForName("brdr_r"); - viewborderlump[BRDR_TL] = W_GetNumForName("brdr_tl"); - viewborderlump[BRDR_BL] = W_GetNumForName("brdr_bl"); - viewborderlump[BRDR_TR] = W_GetNumForName("brdr_tr"); - viewborderlump[BRDR_BR] = W_GetNumForName("brdr_br"); +#if defined(__SSE__) + while (bufsize & 15) + bufsize++; + temp_dc.buf = static_cast(aligned_alloc(16, bufsize)); +#else + temp_dc.buf = static_cast(Z_Malloc(bufsize, PU_STATIC, NULL)); +#endif + + memset(temp_dc.buf, 0, bufsize); } /** \brief The R_VideoErase function @@ -578,129 +658,6 @@ void R_VideoErase(size_t ofs, INT32 count) M_Memcpy(vid.screens[0] + ofs, vid.screens[1] + ofs, count); } - -#if 0 -/** \brief R_FillBackScreen - - Fills the back screen with a pattern for variable screen sizes - Also draws a beveled edge. -*/ -void R_FillBackScreen(void) -{ - UINT8 *src, *dest; - patch_t *patch; - INT32 x, y, step, boff; - - // quickfix, don't cache lumps in both modes - if (rendermode != render_soft) - return; - - // draw pattern around the status bar too (when hires), - // so return only when in full-screen without status bar. - if (scaledviewwidth == vid.width && viewheight == vid.height) - return; - - src = scr_borderpatch; - dest = vid.screens[1]; - - for (y = 0; y < vid.height; y++) - { - for (x = 0; x < vid.width/128; x++) - { - M_Memcpy (dest, src+((y&127)<<7), 128); - dest += 128; - } - - if (vid.width&127) - { - M_Memcpy(dest, src+((y&127)<<7), vid.width&127); - dest += (vid.width&127); - } - } - - // don't draw the borders when viewwidth is full vid.width. - if (scaledviewwidth == vid.width) - return; - - step = 8; - boff = 8; - - patch = W_CacheLumpNum(viewborderlump[BRDR_T], PU_CACHE); - for (x = 0; x < scaledviewwidth; x += step) - V_DrawPatch(viewwindowx + x, viewwindowy - boff, 1, patch); - - patch = W_CacheLumpNum(viewborderlump[BRDR_B], PU_CACHE); - for (x = 0; x < scaledviewwidth; x += step) - V_DrawPatch(viewwindowx + x, viewwindowy + viewheight, 1, patch); - - patch = W_CacheLumpNum(viewborderlump[BRDR_L], PU_CACHE); - for (y = 0; y < viewheight; y += step) - V_DrawPatch(viewwindowx - boff, viewwindowy + y, 1, patch); - - patch = W_CacheLumpNum(viewborderlump[BRDR_R],PU_CACHE); - for (y = 0; y < viewheight; y += step) - V_DrawPatch(viewwindowx + scaledviewwidth, viewwindowy + y, 1, - patch); - - // Draw beveled corners. - V_DrawPatch(viewwindowx - boff, viewwindowy - boff, 1, - W_CacheLumpNum(viewborderlump[BRDR_TL], PU_CACHE)); - V_DrawPatch(viewwindowx + scaledviewwidth, viewwindowy - boff, 1, - W_CacheLumpNum(viewborderlump[BRDR_TR], PU_CACHE)); - V_DrawPatch(viewwindowx - boff, viewwindowy + viewheight, 1, - W_CacheLumpNum(viewborderlump[BRDR_BL], PU_CACHE)); - V_DrawPatch(viewwindowx + scaledviewwidth, viewwindowy + viewheight, 1, - W_CacheLumpNum(viewborderlump[BRDR_BR], PU_CACHE)); -} - -/** \brief The R_DrawViewBorder - - Draws the border around the view - for different size windows? -*/ -void R_DrawViewBorder(void) -{ - INT32 top, side, ofs; - - if (rendermode == render_none) - return; -#ifdef HWRENDER - if (rendermode != render_soft) - { - HWR_DrawViewBorder(0); - return; - } - else -#endif - -#ifdef DEBUG - fprintf(stderr,"RDVB: vidwidth %d vidheight %d scaledviewwidth %d viewheight %d\n", - vid.width, vid.height, scaledviewwidth, viewheight); -#endif - - if (scaledviewwidth == vid.width) - return; - - top = (vid.height - viewheight)>>1; - side = (vid.width - scaledviewwidth)>>1; - - // copy top and one line of left side - R_VideoErase(0, top*vid.width+side); - - // copy one line of right side and bottom - ofs = (viewheight+top)*vid.width - side; - R_VideoErase(ofs, top*vid.width + side); - - // copy sides using wraparound - ofs = top*vid.width + vid.width-side; - side <<= 1; - - // simpler using our VID_Blit routine - VID_BlitLinearScreen(vid.screens[1] + ofs, vid.screens[0] + ofs, side, viewheight - 1, - vid.width, vid.width); -} -#endif - // ========================================================================== // INCLUDE DRAWING CODE HERE // ========================================================================== diff --git a/src/r_draw.h b/src/r_draw.h index bcd734e50..a472b5537 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -25,15 +25,12 @@ extern "C" { // ------------------------------- // COMMON STUFF FOR 8bpp AND 16bpp // ------------------------------- -extern UINT8 *renderscreen; -extern INT32 linesize; FUNCINLINE static ATTRINLINE UINT8 *R_Address(INT32 px, INT32 py) { - return renderscreen + (py + viewwindowy) * linesize + (viewwindowx + px); + return vid.screens[0] + (py + viewwindowy) * vid.width + (viewwindowx + px); } - typedef struct { float x, y, z; } floatv3_t; @@ -102,6 +99,16 @@ extern floatv3_t *ds_su, *ds_sv, *ds_sz; extern float focallengthf; +enum columncontext_e +{ + COLUMNCONTEXT_DIRECT = 0, + COLUMNCONTEXT_FLUSH, +}; + +extern enum columncontext_e columncontext; +void R_SetColumnContext(enum columncontext_e _columncontext); + +void R_ResetColumnBuffer(void); typedef void (coldrawfunc_t)(drawcolumndata_t*); typedef void (spandrawfunc_t)(drawspandata_t*); @@ -152,29 +159,12 @@ extern spandrawfunc_t *spanfuncs[SPANDRAWFUNC_MAX]; void R_DrawMaskedColumn(drawcolumndata_t* dc, column_t *column); -/// \brief Top border -#define BRDR_T 0 -/// \brief Bottom border -#define BRDR_B 1 -/// \brief Left border -#define BRDR_L 2 -/// \brief Right border -#define BRDR_R 3 -/// \brief Topleft border -#define BRDR_TL 4 -/// \brief Topright border -#define BRDR_TR 5 -/// \brief Bottomleft border -#define BRDR_BL 6 -/// \brief Bottomright border -#define BRDR_BR 7 - -extern lumpnum_t viewborderlump[8]; - // ------------------------------------------------ -// r_draw.c COMMON ROUTINES FOR BOTH 8bpp and 16bpp +// r_draw.c // ------------------------------------------------ +// Custom player skin translation + #define GTC_CACHE 1 #define GTC_MENUCACHE GTC_CACHE //@TODO Add a separate caching mechanism for menu colormaps distinct from in-level GTC_CACHE. For now this is still preferable to memory leaks... @@ -219,19 +209,9 @@ UINT8 *R_GetBlendTable(int style, INT32 alphalevel); boolean R_BlendLevelVisible(INT32 blendmode, INT32 alphalevel); -// Custom player skin translation -void R_InitViewBuffer(INT32 width, INT32 height); -void R_InitViewBorder(void); +void R_InitViewBuffer(void); void R_VideoErase(size_t ofs, INT32 count); -// Rendering function. -#if 0 -void R_FillBackScreen(void); - -// If the view size is not full screen, draws a border around it. -void R_DrawViewBorder(void); -#endif - #define TRANSPARENTPIXEL 247 // ----------------- @@ -250,6 +230,15 @@ void R_DrawTranslatedTranslucentColumn(drawcolumndata_t* dc); void R_Draw2sMultiPatchColumn(drawcolumndata_t* dc); void R_Draw2sMultiPatchTranslucentColumn(drawcolumndata_t* dc); +// column drawers which use buffered drawing with flush +void R_DrawColumn_Flush(drawcolumndata_t* dc); +void R_DrawTranslucentColumn_Flush(drawcolumndata_t* dc); +void R_DrawTranslatedColumn_Flush(drawcolumndata_t* dc); +void R_DrawColumnShadowed_Flush(drawcolumndata_t* dc); +void R_DrawTranslatedTranslucentColumn_Flush(drawcolumndata_t* dc); +void R_Draw2sMultiPatchColumn_Flush(drawcolumndata_t* dc); +void R_Draw2sMultiPatchTranslucentColumn_Flush(drawcolumndata_t* dc); + void R_DrawFogColumn(drawcolumndata_t* dc); // span drawers diff --git a/src/r_draw_column.cpp b/src/r_draw_column.cpp index bae220e6d..51690fbb0 100644 --- a/src/r_draw_column.cpp +++ b/src/r_draw_column.cpp @@ -21,6 +21,8 @@ // a has a constant z depth from top to bottom. // +#include "r_draw_flush.cpp" + enum DrawColumnType { DC_BASIC = 0x0000, @@ -28,10 +30,12 @@ enum DrawColumnType DC_TRANSMAP = 0x0002, DC_HOLES = 0x0004, DC_LIGHTLIST = 0x0008, + DC_DIRECT = 0x0010, // draw our columns directly to screen! }; template -static constexpr UINT8 R_GetColumnTranslated(drawcolumndata_t* dc, UINT8 col, const UINT8 * restrict colormap) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetColumnTranslated(const drawcolumndata_t* dc, UINT8 col, const UINT8 * restrict colormap) { if constexpr (Type & DrawColumnType::DC_COLORMAP) { @@ -41,8 +45,10 @@ static constexpr UINT8 R_GetColumnTranslated(drawcolumndata_t* dc, UINT8 col, co return colormap[col]; } +// translucency is handled on flush side now! template -static constexpr UINT8 R_GetColumnTranslucent(drawcolumndata_t* dc, UINT8 * restrict dest, UINT8 col, const UINT8 * restrict colormap) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetColumnTranslucent(const drawcolumndata_t* dc, UINT8 * restrict dest, UINT8 col, const UINT8 * restrict colormap) { col = R_GetColumnTranslated(dc, col, colormap); @@ -57,7 +63,8 @@ static constexpr UINT8 R_GetColumnTranslucent(drawcolumndata_t* dc, UINT8 * rest } template -static constexpr UINT8 R_DrawColumnPixel(drawcolumndata_t* dc, UINT8 * restrict dest, UINT32 bit, const UINT8 * restrict source, const UINT8 * restrict colormap) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_DrawColumnPixel(const drawcolumndata_t* dc, UINT8 * restrict dest, UINT32 bit, const UINT8 * restrict source, const UINT8 * restrict colormap) { UINT8 col = source[bit]; @@ -69,6 +76,7 @@ static constexpr UINT8 R_DrawColumnPixel(drawcolumndata_t* dc, UINT8 * restrict } } + // if we dont buffer our columns, we need to handle translucency again return R_GetColumnTranslucent(dc, dest, col, colormap); } @@ -80,8 +88,18 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) { INT32 count; + // leban 1/17/99: + // removed the + 1 here, adjusted the if test, and added an increment + // later. this helps a compiler pipeline a bit better. the x86 + // assembler also does this. count = dc->yh - dc->yl; + // leban 1/17/99: + // this case isn't executed too often. depending on how many instructions + // there are between here and the second if test below, this case could + // be moved down and might save instructions overall. since there are + // probably different wads that favor one way or the other, i'll leave + // this alone for now. if (count < 0) // Zero length, column does not exceed a pixel. { return; @@ -150,6 +168,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) } R_DrawColumnTemplate(&dc_copy); + if (solid) { dc_copy.yl = bheight; @@ -183,19 +202,37 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) // killough 2/1/98: more performance tuning intptr_t frac; + // Looks familiar. const intptr_t fracstep = dc->iscale; - const intptr_t heightmask = dc->sourcelength-1; + const intptr_t heightmask = dc->sourcelength-1; // CPhipps - specify type constexpr INT32 npow2min = -1; const INT32 npow2max = dc->sourcelength; - const INT32 stride = vid.width; const UINT8 * restrict source = dc->source; const lighttable_t * restrict colormap = dc->colormap; // Framebuffer destination address. - UINT8 * restrict dest = R_Address(dc->x, dc->yl); + // SoM: MAGIC + UINT8 * restrict dest; - count++; + if constexpr (Type & DrawColumnType::DC_DIRECT) + dest = R_Address(dc->x, dc->yl); + else if constexpr ((Type & (DrawColumnType::DC_COLORMAP | DrawColumnType::DC_TRANSMAP)) + == (DrawColumnType::DC_COLORMAP | DrawColumnType::DC_TRANSMAP)) + dest = R_GetBufferColormapTrans(dc); + else if constexpr (Type & DrawColumnType::DC_TRANSMAP) + dest = R_GetBufferTrans(dc); + else if constexpr (Type & DrawColumnType::DC_COLORMAP) + dest = R_GetBufferColormap(dc); + else + dest = R_GetBufferOpaque(dc); + + INT32 stride = 8; //SoM: Oh, Oh it's MAGIC! You know... + + if constexpr (Type & DrawColumnType::DC_DIRECT) + stride = vid.width; + + count++; // killough 1/99: minor tuning // Determine scaling, which is the only mapping to be done. frac = (dc->texturemid + FixedMul((dc->yl << FRACBITS) - centeryfrac, fracstep)); @@ -205,15 +242,16 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) case 255: case 127: { - while(count--) + while (count--) { *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); + dest += stride; frac += fracstep; } } break; - case -1: + case npow2min: { if (frac < 0) // adjust in case we underread @@ -223,6 +261,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) while (--count >= 0) { *dest = R_DrawColumnPixel(dc, dest, frac>>FRACBITS, source, colormap); + dest += stride; frac += fracstep; } @@ -235,10 +274,12 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) while ((count -= 2) >= 0) // texture height is a power of 2 -- killough { *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); + dest += stride; frac += fracstep; *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS) & heightmask, source, colormap); + dest += stride; frac += fracstep; } @@ -271,7 +312,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) { // Re-map color indices from wall texture column // using a lighting/special effects LUT. - // heightmask is the Tutti-Frutti fix + // heightmask is the Tutti-Frutti fix -- killough // -1 is the lower clamp bound because column posts have a "safe" byte before the real data // and a few bytes after as well @@ -311,13 +352,18 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) R_DrawColumnTemplate(dc); \ } -DEFINE_COLUMN_FUNC(R_DrawColumn, DC_BASIC) -DEFINE_COLUMN_FUNC(R_DrawTranslucentColumn, DC_TRANSMAP) -DEFINE_COLUMN_FUNC(R_DrawTranslatedColumn, DC_COLORMAP) -DEFINE_COLUMN_FUNC(R_DrawColumnShadowed, DC_LIGHTLIST) -DEFINE_COLUMN_FUNC(R_DrawTranslatedTranslucentColumn, DC_COLORMAP|DC_TRANSMAP) -DEFINE_COLUMN_FUNC(R_Draw2sMultiPatchColumn, DC_HOLES) -DEFINE_COLUMN_FUNC(R_Draw2sMultiPatchTranslucentColumn, DC_HOLES|DC_TRANSMAP) +#define DEFINE_COLUMN_COMBO(name, flags) \ + DEFINE_COLUMN_FUNC(name, flags|DC_DIRECT) \ + DEFINE_COLUMN_FUNC(name ## _Flush, flags) + +DEFINE_COLUMN_COMBO(R_DrawColumn, DC_BASIC) +DEFINE_COLUMN_COMBO(R_DrawTranslucentColumn, DC_TRANSMAP) +DEFINE_COLUMN_COMBO(R_DrawTranslatedColumn, DC_COLORMAP) +DEFINE_COLUMN_COMBO(R_DrawColumnShadowed, DC_LIGHTLIST) +DEFINE_COLUMN_COMBO(R_DrawTranslatedTranslucentColumn, DC_COLORMAP|DC_TRANSMAP) +DEFINE_COLUMN_COMBO(R_Draw2sMultiPatchColumn, DC_HOLES) +DEFINE_COLUMN_COMBO(R_Draw2sMultiPatchTranslucentColumn, DC_HOLES|DC_TRANSMAP) + /** \brief The R_DrawFogColumn function Fog wall. diff --git a/src/r_draw_flush.cpp b/src/r_draw_flush.cpp new file mode 100644 index 000000000..b135c6125 --- /dev/null +++ b/src/r_draw_flush.cpp @@ -0,0 +1,269 @@ +// SONIC ROBO BLAST 2 KART +//----------------------------------------------------------------------------- +// Copyright (C) 2025 by Kart Krew. +// Copyright (C) 2020 by Sonic Team Junior. +// Copyright (C) 2000 by DooM Legacy Team. +// Copyright (C) 1996 by id Software, Inc. +// Copyright (C) 1999 by Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman +// Copyright (C) 1999-2000 by Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze +// Copyright (C) Copyright 2005, 2006 by Florian Schulze, Colin Phipps, Neil Stevens, Andrey Budko +// Copyright (C) 2013 by James Haley, Stephen McGranahan, et al. +// +// 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 r_draw_flush.cpp +/// \brief Optimized quad column buffer code. By SoM. +/// \note no includes because this is included as part of r_draw.cpp + +template +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetFlushPixelTranslated(const drawcolumndata_temp_t *t_dc, UINT8 col) +{ + if constexpr (Type & (ColumnFlushType::FLUSH_COLORMAP | ColumnFlushType::FLUSH_COLORMAP_TRANS)) + { + col = t_dc->translation[col]; + } + + return col; +} + +template +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetFlushPixelTranslucent(const drawcolumndata_temp_t *t_dc, UINT8 * restrict dest, UINT8 col) +{ + col = R_GetFlushPixelTranslated(t_dc, col); + + if constexpr (Type & (ColumnFlushType::FLUSH_TRANS | ColumnFlushType::FLUSH_COLORMAP_TRANS)) + { + // haleyjd 09/11/04: use temptranmap here + return *(t_dc->transmap + (col << 8) + (*dest)); + } + else + { + return col; + } +} + +template +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_DrawFlushPixel(const drawcolumndata_temp_t *t_dc, UINT8 * restrict dest, const UINT8 * restrict source) +{ + UINT8 col = *source; + return R_GetFlushPixelTranslucent(t_dc, dest, col); +} + +// +// R_FlushWhole +// +// Flushes the entire columns in the buffer, one at a time. +// This is used when a quad flush isn't possible. +// +template +static void R_FlushWhole(void) +{ + UINT8 * restrict source; + UINT8 * restrict dest; + INT32 count, yl; + const INT32 stride = vid.width; + drawcolumndata_temp_t *t_dc = &temp_dc; + UINT8 *restrict buf = t_dc->buf; + + while (--t_dc->x >= 0) + { + yl = t_dc->yl[t_dc->x]; + source = &buf[t_dc->x + (yl << 3)]; + dest = R_Address(t_dc->startx + t_dc->x, yl); + count = t_dc->yh[t_dc->x] - yl + 1; + + while (--count >= 0) + { + *dest = R_DrawFlushPixel(t_dc, dest, source); + source += 8; + dest += stride; + } + } +} + +// +// R_FlushHT +// +// Flushes the head and tail of columns in the buffer in +// preparation for a quad flush. +// +template +static void R_FlushHT(void) +{ + UINT8 * restrict source; + UINT8 * restrict dest; + INT32 count, colnum = 0; + INT32 yl, yh; + const INT32 stride = vid.width; + const drawcolumndata_temp_t *t_dc = &temp_dc; + UINT8 *restrict buf = t_dc->buf; + + while (colnum < 8) + { + yl = t_dc->yl[colnum]; + yh = t_dc->yh[colnum]; + + // flush column head + if (yl < t_dc->commontop) + { + source = &buf[colnum + (yl << 3)]; + dest = R_Address(t_dc->startx + colnum, yl); + count = t_dc->commontop - yl; + + while (--count >= 0) + { + *dest = R_DrawFlushPixel(t_dc, dest, source); + source += 8; + dest += stride; + } + } + + // flush column tail + if (yh > t_dc->commonbot) + { + source = &buf[colnum + ((t_dc->commonbot + 1) << 3)]; + dest = R_Address(t_dc->startx + colnum, t_dc->commonbot + 1); + count = yh - t_dc->commonbot; + + while (--count >= 0) + { + *dest = R_DrawFlushPixel(t_dc, dest, source); + source += 8; + dest += stride; + } + } + + ++colnum; + } +} + +// Begin: Quad column flushing functions. +template +static void R_FlushQuad(void) +{ + const INT32 stride = vid.width; + const drawcolumndata_temp_t *t_dc = &temp_dc; + INT32 count = t_dc->commonbot - t_dc->commontop + 1; + const UINT8 *restrict buf = t_dc->buf; + + const UINT8 * restrict source = buf + (t_dc->commontop << 3); + UINT8 * restrict dest = R_Address(t_dc->startx, t_dc->commontop); + + if constexpr (Type & ColumnFlushType::FLUSH_OPAQUE) + { +#if __SIZEOF_POINTER__ >= 8 // does not make much sense on 32bit targets + // 8 byte aligned copy -- make sure our dest ptr, source ptr AND stride are a multiple of 8! + if ((((uintptr_t)dest | (uintptr_t)source | stride) & 7) == 0) + { + const INT64 *source64 = reinterpret_cast(source); + INT64 *dest64 = reinterpret_cast(dest); + const INT32 deststep = stride / 8; + + while (--count >= 0) + { + *dest64 = *source64++; + dest64 += deststep; + } + } + else +#endif + { + while (--count >= 0) + { + dest[0] = source[0]; + dest[1] = source[1]; + dest[2] = source[2]; + dest[3] = source[3]; + dest[4] = source[4]; + dest[5] = source[5]; + dest[6] = source[6]; + dest[7] = source[7]; + source += 8; + dest += stride; + } + } + } + else + { + while (--count >= 0) + { + dest[0] = R_DrawFlushPixel(t_dc, &dest[0], &source[0]); + dest[1] = R_DrawFlushPixel(t_dc, &dest[1], &source[1]); + dest[2] = R_DrawFlushPixel(t_dc, &dest[2], &source[2]); + dest[3] = R_DrawFlushPixel(t_dc, &dest[3], &source[3]); + dest[4] = R_DrawFlushPixel(t_dc, &dest[4], &source[4]); + dest[5] = R_DrawFlushPixel(t_dc, &dest[5], &source[5]); + dest[6] = R_DrawFlushPixel(t_dc, &dest[6], &source[6]); + dest[7] = R_DrawFlushPixel(t_dc, &dest[7], &source[7]); + source += 8; + dest += stride; + } + } +} + +// haleyjd 09/12/04: split up R_GetBuffer into various different +// functions to minimize the number of branches and take advantage +// of as much precalculated information as possible. +template +static UINT8 *R_GetBuffer(drawcolumndata_t *dc) +{ + drawcolumndata_temp_t *t_dc = &temp_dc; + + // haleyjd: reordered predicates + if (t_dc->x == 8 || + (t_dc->x && (t_dc->type != Type || t_dc->x + t_dc->startx != dc->x))) + R_FlushColumns(); + + if (!t_dc->x) + { + ++t_dc->x; + t_dc->startx = dc->x; + t_dc->yl[0] = t_dc->commontop = dc->yl; + t_dc->yh[0] = t_dc->commonbot = dc->yh; + t_dc->type = Type; + + if constexpr (Type & (ColumnFlushType::FLUSH_TRANS | ColumnFlushType::FLUSH_COLORMAP_TRANS)) + { + t_dc->transmap = dc->transmap; + } + + if constexpr (Type & (ColumnFlushType::FLUSH_COLORMAP | ColumnFlushType::FLUSH_COLORMAP_TRANS)) + { + t_dc->translation = dc->translation; + } + + R_FlushWholeColumns = R_FlushWhole; + R_FlushHTColumns = R_FlushHT; + R_FlushQuadColumn = R_FlushQuad; + + return &t_dc->buf[dc->yl << 3]; + } + + t_dc->yl[t_dc->x] = dc->yl; + t_dc->yh[t_dc->x] = dc->yh; + + if (dc->yl > t_dc->commontop) + t_dc->commontop = dc->yl; + if (dc->yh < t_dc->commonbot) + t_dc->commonbot = dc->yh; + + return &t_dc->buf[(dc->yl << 3) + t_dc->x++]; +} + +#define DEFINE_GETBUF_FUNC(name, flags) \ + FUNCINLINE static ATTRINLINE UINT8 *name(drawcolumndata_t *dc) \ + { \ + constexpr ColumnFlushType opt = static_cast(flags); \ + return R_GetBuffer(dc); \ + } + +DEFINE_GETBUF_FUNC(R_GetBufferOpaque, FLUSH_OPAQUE) +DEFINE_GETBUF_FUNC(R_GetBufferTrans, FLUSH_TRANS) +DEFINE_GETBUF_FUNC(R_GetBufferColormap, FLUSH_COLORMAP) +DEFINE_GETBUF_FUNC(R_GetBufferColormapTrans, FLUSH_COLORMAP_TRANS) + diff --git a/src/r_draw_span.cpp b/src/r_draw_span.cpp index cfa053382..b1870685c 100644 --- a/src/r_draw_span.cpp +++ b/src/r_draw_span.cpp @@ -50,7 +50,8 @@ enum DrawSpanType }; template -static constexpr UINT8 R_GetSpanTranslated(drawspandata_t* ds, UINT8 col) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetSpanTranslated(const drawspandata_t* ds, UINT8 col) { if constexpr (Type & DrawSpanType::DS_COLORMAP) { @@ -63,7 +64,8 @@ static constexpr UINT8 R_GetSpanTranslated(drawspandata_t* ds, UINT8 col) } template -static constexpr UINT8 R_GetSpanTranslucent(drawspandata_t* ds, UINT8 *dsrc, const UINT8 *colormap, UINT8 col) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_GetSpanTranslucent(const drawspandata_t* ds, UINT8 *dsrc, const UINT8 *colormap, UINT8 col) { col = colormap[R_GetSpanTranslated(ds, col)]; @@ -78,7 +80,8 @@ static constexpr UINT8 R_GetSpanTranslucent(drawspandata_t* ds, UINT8 *dsrc, con } template -static constexpr UINT8 R_DrawSpanPixel(drawspandata_t* ds, UINT8 *dsrc, const UINT8 *colormap, UINT32 bit, const UINT8 *source) +FUNCINLINE static ATTRINLINE constexpr UINT8 +R_DrawSpanPixel(const drawspandata_t* ds, UINT8 *dsrc, const UINT8 *colormap, UINT32 bit, const UINT8 *source) { UINT8 col = source[bit]; @@ -157,14 +160,18 @@ static void R_DrawSpanTemplate(drawspandata_t* ds) { bit = ((yposition >> ds->nflatyshift) & ds->nflatmask) | (xposition >> ds->nflatxshift); - dest[i] = R_DrawSpanPixel(ds, &dsrc[i], colormap, bit, source); + if constexpr (Type & DS_RIPPLE) + dest[i] = R_DrawSpanPixel(ds, &dsrc[i], colormap, bit, source); + else + dest[i] = R_DrawSpanPixel(ds, &dest[i], colormap, bit, source); xposition += xstep; yposition += ystep; } dest += 8; - dsrc += 8; + if constexpr (Type & DS_RIPPLE) + dsrc += 8; count -= 8; } @@ -173,10 +180,14 @@ static void R_DrawSpanTemplate(drawspandata_t* ds) { bit = ((yposition >> ds->nflatyshift) & ds->nflatmask) | (xposition >> ds->nflatxshift); - *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + if constexpr (Type & DS_RIPPLE) + *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + else + *dest = R_DrawSpanPixel(ds, dest, colormap, bit, source); dest++; - dsrc++; + if constexpr (Type & DS_RIPPLE) + dsrc++; xposition += xstep; yposition += ystep; @@ -243,15 +254,14 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) local_for_thread std::vector tiltlighting; iz = ds->szp.z + ds->szp.y*(centery-ds->y) + ds->szp.x*(ds->x1-centerx); + uz = ds->sup.z + ds->sup.y*(centery-ds->y) + ds->sup.x*(ds->x1-centerx); + vz = ds->svp.z + ds->svp.y*(centery-ds->y) + ds->svp.x*(ds->x1-centerx); // Lighting is simple. It's just linear interpolation from start to end R_GetTiltedLighting(tiltlighting, ds, iz, width, stride); - uz = ds->sup.z + ds->sup.y*(centery-ds->y) + ds->sup.x*(ds->x1-centerx); - vz = ds->svp.z + ds->svp.y*(centery-ds->y) + ds->svp.x*(ds->x1-centerx); - - const UINT8 *source = ds->source; - const UINT8 *colormap = ds->colormap; + const UINT8 * restrict source = ds->source; + const UINT8 * restrict colormap = ds->colormap; if constexpr (Type & DS_RIPPLE) { @@ -313,12 +323,16 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) { bit = (((v + stepv * i) >> nflatyshift) & nflatmask) | ((u + stepu * i) >> nflatxshift); colormap = ds->planezlight[tiltlighting[x1 + i]] + (ds->colormap - colormaps); - dest[i] = R_DrawSpanPixel(ds, &dsrc[i], colormap, bit, source); + if constexpr (Type & DS_RIPPLE) + dest[i] = R_DrawSpanPixel(ds, &dsrc[i], colormap, bit, source); + else + dest[i] = R_DrawSpanPixel(ds, &dest[i], colormap, bit, source); } ds->x1 += SPANSIZE; dest += SPANSIZE; - dsrc += SPANSIZE; + if constexpr (Type & DS_RIPPLE) + dsrc += SPANSIZE; startu = endu; startv = endv; width -= SPANSIZE; @@ -332,7 +346,10 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) v = (INT64)(startv); bit = ((v >> nflatyshift) & nflatmask) | (u >> nflatxshift); colormap = ds->planezlight[tiltlighting[ds->x1]] + (ds->colormap - colormaps); - *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + if constexpr (Type & DS_RIPPLE) + *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + else + *dest = R_DrawSpanPixel(ds, dest, colormap, bit, source); ds->x1++; } else @@ -355,10 +372,14 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) { bit = ((v >> ds->nflatyshift) & ds->nflatmask) | (u >> ds->nflatxshift); colormap = ds->planezlight[tiltlighting[ds->x1]] + (ds->colormap - colormaps); - *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + if constexpr (Type & DS_RIPPLE) + *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); + else + *dest = R_DrawSpanPixel(ds, dest, colormap, bit, source); dest++; + if constexpr (Type & DS_RIPPLE) + dsrc++; ds->x1++; - dsrc++; u += stepu; v += stepv; } @@ -389,11 +410,11 @@ DEFINE_SPAN_COMBO(R_DrawTranslucentWaterSpan, DS_TRANSMAP|DS_RIPPLE) */ void R_DrawFogSpan(drawspandata_t* ds) { + INT32 count = ds->x2 - ds->x1 + 1; + const UINT8 * restrict colormap = ds->colormap; UINT8 * restrict dest = R_Address(ds->x1, ds->y); - intptr_t count = ds->x2 - ds->x1 + 1; - while (count >= 4) { dest[0] = colormap[dest[0]]; @@ -401,7 +422,7 @@ void R_DrawFogSpan(drawspandata_t* ds) dest[2] = colormap[dest[2]]; dest[3] = colormap[dest[3]]; - dest += 4; + dest += 4; count -= 4; } diff --git a/src/r_fps.cpp b/src/r_fps.cpp index ad8c97aed..98bfaf68b 100644 --- a/src/r_fps.cpp +++ b/src/r_fps.cpp @@ -172,7 +172,7 @@ static vector3_t *R_LerpVector3(const vector3_t *from, const vector3_t *to, fixe // recalc necessary stuff for mouseaiming // slopes are already calculated for the full possible view (which is 4*viewheight). // 18/08/18: (No it's actually 16*viewheight, thanks Lactozilla for finding this out) -static void R_SetupFreelook(void) +void R_SetupFreelook(void) { // clip it in the case we are looking a hardware 90 degrees full aiming // (lmps, network and use F12...) diff --git a/src/r_fps.h b/src/r_fps.h index 49ca669d3..7ad5e9f16 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -151,6 +151,7 @@ typedef struct levelinterpolator_s { }; } levelinterpolator_t; +void R_SetupFreelook(void); // Interpolates the current view variables (r_state.h) against the selected view context in R_SetViewContext void R_InterpolateView(fixed_t frac, boolean forceinvalid); // Special function just for software diff --git a/src/r_main.cpp b/src/r_main.cpp index 08f1e68a1..339e34548 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -63,7 +63,7 @@ size_t loopcount; fixed_t viewx, viewy, viewz; angle_t viewangle, aimingangle, viewroll; -UINT8 viewssnum; +UINT8 viewssnum = 0; fixed_t viewcos, viewsin; boolean skyVisible; boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS]; // saved values of skyVisible for each splitscreen player @@ -88,7 +88,7 @@ INT32 viewangletox[FINEANGLES/2]; // The xtoviewangleangle[] table maps a screen pixel // to the lowest viewangle that maps back to x ranges // from clipangle to -clipangle. -angle_t *xtoviewangle; +angle_t *xtoviewangle = NULL; lighttable_t *scalelight[LIGHTLEVELS][MAXLIGHTSCALE]; lighttable_t *scalelightfixed[MAXLIGHTSCALE]; @@ -253,6 +253,7 @@ void SplitScreen_OnChange(void) if (playeringame[i] && i != consoleplayer) { UINT8 j; + for (j = 1; j < MAXSPLITSCREENPLAYERS; j++) { if (displayplayers[j] == consoleplayer) @@ -268,6 +269,7 @@ void SplitScreen_OnChange(void) } } } + static void Fov_OnChange(void) { R_SetViewSize(); @@ -943,9 +945,10 @@ void R_ExecuteSetViewSize(void) memset(scalelight, 0xFF, sizeof(scalelight)); // Calculate the light levels to use for each level/scale combination. - for (i = 0; i< LIGHTLEVELS; i++) + for (i = 0; i < LIGHTLEVELS; i++) { startmapl = ((LIGHTLEVELS - 1 - i)*2)*NUMCOLORMAPS/LIGHTLEVELS; + for (j = 0; j < MAXLIGHTSCALE; j++) { level = startmapl - j*vid.width/(viewwidth)/DISTMAP; @@ -960,6 +963,8 @@ void R_ExecuteSetViewSize(void) } } + R_SetupFreelook(); + am_recalc = true; } @@ -1003,7 +1008,7 @@ static void R_InitViewMapping(void) static void R_SetupViewBuffers(void) { R_CalcFov(cv_fov.value); - R_InitViewBuffer(viewwidth, viewheight); + R_InitViewBuffer(); R_InitViewMapping(); } @@ -1023,8 +1028,6 @@ void R_Init(void) //I_OutputMsg("\nR_InitData"); R_InitData(); - //I_OutputMsg("\nR_InitViewBorder"); - R_InitViewBorder(); R_SetViewSize(); // setsizeneeded is set true // this is now done by SCR_Recalc() at the first mode set @@ -1404,9 +1407,12 @@ void R_RenderPlayerView(player_t *player) R_ClearPlanes(); R_ClearSprites(); + R_SetColumnContext(COLUMNCONTEXT_FLUSH); R_RenderViewpoint(&masks[nummasks - 1], false); R_ClipSprites(drawsegs, NULL); + R_ResetColumnBuffer(); + R_SetColumnContext(COLUMNCONTEXT_DIRECT); R_DrawSkyPlanes(); // draw the fucker again to prevent some artifacts R_DrawPlanes(); R_DrawMasked(masks, nummasks); @@ -1441,6 +1447,7 @@ void R_RenderPlayerView(player_t *player) // check for new console commands. NetUpdate(); + R_SetColumnContext(COLUMNCONTEXT_FLUSH); ps_numbspcalls.value.i = ps_numpolyobjects.value.i = ps_numdrawnodes.value.i = 0; PS_START_TIMING(ps_bsptime); R_RenderViewpoint(&masks[nummasks - 1], true); @@ -1448,6 +1455,7 @@ void R_RenderPlayerView(player_t *player) PS_START_TIMING(ps_sw_spritecliptime); R_ClipSprites(drawsegs, NULL); PS_STOP_TIMING(ps_sw_spritecliptime); + R_ResetColumnBuffer(); ps_numsprites.value.i = numvisiblesprites; @@ -1484,12 +1492,14 @@ void R_RenderPlayerView(player_t *player) R_RenderViewpoint(&masks[nummasks - 1], true); R_ClipSprites(ds_p - (masks[nummasks - 1].drawsegs[1] - masks[nummasks - 1].drawsegs[0]), portal); + R_ResetColumnBuffer(); Portal_Remove(portal); } } PS_STOP_TIMING(ps_sw_portaltime); + R_SetColumnContext(COLUMNCONTEXT_DIRECT); PS_START_TIMING(ps_sw_planetime); if (!skybox) R_DrawSkyPlanes(); @@ -1500,7 +1510,6 @@ void R_RenderPlayerView(player_t *player) PS_START_TIMING(ps_sw_maskedtime); R_DrawMasked(masks, nummasks); PS_STOP_TIMING(ps_sw_maskedtime); - free(masks); // Check for new console commands. diff --git a/src/r_main.h b/src/r_main.h index 4ec43a2f3..850101e64 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -97,7 +97,7 @@ FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSide(fixed_t x, fixed_t y, // Try to quickly decide by looking at sign bits. // also use a mask to avoid branch prediction - INT32 mask = (node->dy ^ node->dx ^ x ^ y) >> 31; + INT32 mask = (((node->dy ^ node->dx ^ x ^ y) < 0) ? -1 : 0); return (mask & ((node->dy ^ x) < 0)) | // (left is negative) (~mask & (FixedMul(y, node->dx>>FRACBITS) >= FixedMul(node->dy>>FRACBITS, x))); } diff --git a/src/r_patch.c b/src/r_patch.cpp similarity index 87% rename from src/r_patch.c rename to src/r_patch.cpp index e774c1c2e..09aca078a 100644 --- a/src/r_patch.c +++ b/src/r_patch.cpp @@ -19,6 +19,7 @@ #include "r_skins.h" #include "z_zone.h" #include "w_wad.h" +#include #ifdef HWRENDER #include "hardware/hw_glob.h" @@ -37,7 +38,7 @@ static void R_ParseSpriteInfoFrame(spriteinfo_t *info) UINT8 frameFrame = 0xFF; INT16 frameXPivot = 0; INT16 frameYPivot = 0; - rotaxis_t frameRotAxis = 0; + rotaxis_t frameRotAxis = ROTAXIS_X; // Sprite identifier sprinfoToken = M_GetToken(NULL); @@ -158,14 +159,14 @@ static void R_ParseSpriteInfo(boolean spr2) I_Error("Error parsing SPRTINFO lump: Unknown sprite name \"%s\"", newSpriteName); if (!memcmp(newSpriteName,sprnames[i],4)) { - sprnum = i; + sprnum = static_cast(i); break; } } } // allocate a spriteinfo - info = Z_Calloc(sizeof(spriteinfo_t), PU_STATIC, NULL); + info = static_cast(Z_Calloc(sizeof(spriteinfo_t), PU_STATIC, NULL)); info->available = true; // Left Curly Brace @@ -329,7 +330,7 @@ void R_LoadSpriteInfoLumps(UINT16 wadnum, UINT16 numlumps) patch_t *Patch_Create(softwarepatch_t *source, size_t srcsize, void *dest) { - patch_t *patch = (dest == NULL) ? Z_Calloc(sizeof(patch_t), PU_PATCH, NULL) : (patch_t *)(dest); + patch_t *patch = static_cast((dest == NULL) ? Z_Calloc(sizeof(patch_t), PU_PATCH, NULL) : dest); if (source) { @@ -341,7 +342,7 @@ patch_t *Patch_Create(softwarepatch_t *source, size_t srcsize, void *dest) patch->height = SHORT(source->height); patch->leftoffset = SHORT(source->leftoffset); patch->topoffset = SHORT(source->topoffset); - patch->columnofs = Z_Calloc(size, PU_PATCH_DATA, NULL); + patch->columnofs = static_cast(Z_Calloc(size, PU_PATCH_DATA, NULL)); for (col = 0; col < source->width; col++) { @@ -357,7 +358,7 @@ patch_t *Patch_Create(softwarepatch_t *source, size_t srcsize, void *dest) if (colsize <= 0) I_Error("Patch_Create: no column data!"); - patch->columns = Z_Calloc(colsize, PU_PATCH_DATA, NULL); + patch->columns = static_cast(Z_Calloc(colsize, PU_PATCH_DATA, NULL)); M_Memcpy(patch->columns, ((UINT8 *)source + LONG(source->columnofs[0])), colsize); } @@ -429,8 +430,8 @@ void *Patch_AllocateHardwarePatch(patch_t *patch) { if (!patch->hardware) { - GLPatch_t *glPatch = Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, &patch->hardware); - glPatch->mipmap = Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, &glPatch->mipmap); + GLPatch_t *glPatch = static_cast(Z_Calloc(sizeof(GLPatch_t), PU_HWRPATCHINFO, &patch->hardware)); + glPatch->mipmap = static_cast(Z_Calloc(sizeof(GLMipmap_t), PU_HWRPATCHINFO, &glPatch->mipmap)); } return (void *)(patch->hardware); } @@ -448,7 +449,8 @@ void *Patch_CreateGL(patch_t *patch) } #endif // HWRENDER -static UINT8 *imgbuf = NULL; +// 1 MB should be enough for most cases +static std::vector imgbuf(1024 * 1024); // // R_MaskedFlatToPatch @@ -458,17 +460,27 @@ static UINT8 *imgbuf = NULL; void *R_PixelsToPatch(UINT8 *raw, INT16 width, INT16 height, INT16 leftoffset, INT16 topoffset, size_t *destsize) { INT16 x, y; - UINT8 *img; + UINT8 *img, *imgptr; UINT8 *colpointers, *startofspan; size_t size = 0; if (!raw) return NULL; - if (!imgbuf) - imgbuf = Z_Malloc(1<<26, PU_STATIC, NULL); + // Allocate a staging buffer with the maximum size needed for a patch of the same size as the input. - UINT8 *imgptr = imgbuf; + // round up to nearest multiple of 254-pixel posts, plus 1 more 254-pixel post for paranoia reasons + size_t maxcolumnsize = (2 + (height - 1) / 256) * 256; + // the patch header, and width columns of the max column size + size_t maxoutsize = maxcolumnsize * width + (8 + 4 * width); + // so, a 512x512 flat should maximally need 393,760 (384.53 KiB) bytes. + // quite a bit smaller than 64 megabytes, and much less annoying to the windows debug allocator! + while (imgbuf.size() < maxoutsize) + { + imgbuf.resize(imgbuf.size() * 2); + } + + imgptr = imgbuf.data(); // Write image size and offset WRITEINT16(imgptr, width); @@ -488,7 +500,7 @@ void *R_PixelsToPatch(UINT8 *raw, INT16 width, INT16 height, INT16 leftoffset, I startofspan = NULL; // Write column pointer - WRITEINT32(colpointers, imgptr - imgbuf); + WRITEINT32(colpointers, imgptr - imgbuf.data()); // Write pixels for (y = 0; y < height; y++) @@ -557,9 +569,9 @@ void *R_PixelsToPatch(UINT8 *raw, INT16 width, INT16 height, INT16 leftoffset, I WRITEUINT8(imgptr, 0xFF); } - size = imgptr-imgbuf; - img = Z_Malloc(size, PU_STATIC, NULL); - memcpy(img, imgbuf, size); + size = imgptr-imgbuf.data(); + img = static_cast(Z_Malloc(size, PU_STATIC, NULL)); + memcpy(img, imgbuf.data(), size); if (destsize != NULL) *destsize = size; @@ -582,17 +594,27 @@ void *R_PixelsToPatch(UINT8 *raw, INT16 width, INT16 height, INT16 leftoffset, I void *R_MaskedFlatToPatch(UINT16 *raw, INT16 width, INT16 height, INT16 leftoffset, INT16 topoffset, size_t *destsize) { INT16 x, y; - UINT8 *img; + UINT8 *img, *imgptr; UINT8 *colpointers, *startofspan; size_t size = 0; if (!raw) return NULL; - if (!imgbuf) - imgbuf = Z_Malloc(1<<26, PU_STATIC, NULL); + // Allocate a staging buffer with the maximum size needed for a patch of the same size as the input. - UINT8 *imgptr = imgbuf; + // round up to nearest multiple of 254-pixel posts, plus 1 more 254-pixel post for paranoia reasons + size_t maxcolumnsize = (2 + (height - 1) / 256) * 256; + // the patch header, and width columns of the max column size + size_t maxoutsize = maxcolumnsize * width + (8 + 4 * width); + // so, a 512x512 flat should maximally need 393,760 (384.53 KiB) bytes. + // quite a bit smaller than 64 megabytes, and much less annoying to the windows debug allocator! + while (imgbuf.size() < maxoutsize) + { + imgbuf.resize(imgbuf.size() * 2); + } + + imgptr = imgbuf.data(); // Write image size and offset WRITEINT16(imgptr, width); @@ -612,7 +634,7 @@ void *R_MaskedFlatToPatch(UINT16 *raw, INT16 width, INT16 height, INT16 leftoffs startofspan = NULL; // Write column pointer - WRITEINT32(colpointers, imgptr - imgbuf); + WRITEINT32(colpointers, imgptr - imgbuf.data()); // Write pixels for (y = 0; y < height; y++) @@ -682,9 +704,9 @@ void *R_MaskedFlatToPatch(UINT16 *raw, INT16 width, INT16 height, INT16 leftoffs WRITEUINT8(imgptr, 0xFF); } - size = imgptr-imgbuf; - img = Z_Malloc(size, PU_STATIC, NULL); - memcpy(img, imgbuf, size); + size = imgptr-imgbuf.data(); + img = static_cast(Z_Malloc(size, PU_STATIC, NULL)); + memcpy(img, imgbuf.data(), size); if (destsize != NULL) *destsize = size; diff --git a/src/r_patch.h b/src/r_patch.h index 4d44b5416..266e4a563 100644 --- a/src/r_patch.h +++ b/src/r_patch.h @@ -14,6 +14,10 @@ #ifndef __R_PATCH__ #define __R_PATCH__ +#ifdef __cplusplus +extern "C" { +#endif + #include "r_defs.h" // Structs @@ -63,4 +67,8 @@ void *R_PixelsToPatch(UINT8 *raw, INT16 width, INT16 height, INT16 leftoffset, I UINT16 R_GetPatchPixel(patch_t *patch, INT32 x, INT32 y, boolean flip); void R_PatchToPixels(patch_t *patch, UINT8 *dst); // Important: dst must have enough space for patch->width*patch->height pixels! +#ifdef __cplusplus +} // extern "C" +#endif + #endif // __R_PATCH__ diff --git a/src/r_patchrotation.c b/src/r_patchrotation.cpp similarity index 83% rename from src/r_patchrotation.c rename to src/r_patchrotation.cpp index 862febf2f..ebf8960e6 100644 --- a/src/r_patchrotation.c +++ b/src/r_patchrotation.cpp @@ -15,6 +15,7 @@ #include "r_patchrotation.h" #include "z_zone.h" #include "w_wad.h" +#include #ifdef ROTSPRITE // @@ -89,14 +90,14 @@ patch_t *Patch_GetRotatedSprite(spriteframe_t *sprite, size_t frame, size_t spri RotatedPatch_DoRotation(rotsprite, patch, rotationangle, xpivot, ypivot, flip); } - return rotsprite->patches[idx]; + return static_cast(rotsprite->patches[idx]); } rotsprite_t *RotatedPatch_Create(INT32 numangles) { - rotsprite_t *rotsprite = Z_Calloc(sizeof(rotsprite_t), PU_STATIC, NULL); + rotsprite_t *rotsprite = static_cast(Z_Calloc(sizeof(rotsprite_t), PU_STATIC, NULL)); rotsprite->angles = numangles; - rotsprite->patches = Z_Calloc(rotsprite->angles * 2 * sizeof(void *), PU_STATIC, NULL); + rotsprite->patches = static_cast(Z_Calloc(rotsprite->angles * 2 * sizeof(void *), PU_STATIC, NULL)); return rotsprite; } @@ -118,30 +119,8 @@ static void RotatedPatch_CalculateDimensions( h1 = FixedInt(FixedCeil(h1 + (FRACUNIT/2))); h2 = FixedInt(FixedCeil(h2 + (FRACUNIT/2))); - *newwidth = max(width, max(w1, w2)); - *newheight = max(height, max(h1, h2)); -} - -static void RotatedPatch_AllocImgBuf(UINT16 **buf, size_t size, size_t *capacity) -{ - if (!*buf) - { - *buf = Z_Malloc(*capacity, PU_STATIC, NULL); - } - - size_t allocsize = size * sizeof(UINT16); - - // make sure our buffer always fits with what we need - if (allocsize > *capacity) - { - while (*capacity < allocsize) - *capacity *= 2; - - Z_Free(*buf); - *buf = Z_Malloc(*capacity, PU_STATIC, NULL); - } - - //CONS_Printf("RotatedPatch_AllocBuf: Allocated %.2f KB\n", *capacity / 1024.0); + *newwidth = std::max(width, std::max(w1, w2)); + *newheight = std::max(height, std::max(h1, h2)); } void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle, INT32 xpivot, INT32 ypivot, boolean flip) @@ -149,10 +128,10 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle UINT32 i; patch_t *rotated; - static UINT16 *rawdst = NULL, *rawconv = NULL; + static std::vector rawdst(1024 * 1024), rawconv(1024 * 1024); // 1 MB should be enough for most cases + UINT16 *rawout; size_t size; - static size_t dst_capacity = (1024 * 1024), conv_capacity = (1024 * 1024); // 1 MB should be enough for most cases INT32 bflip = (flip != 0x00); INT32 width = patch->width; @@ -206,7 +185,10 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle if (!size) size = (width * height); - RotatedPatch_AllocImgBuf(&rawdst, size, &dst_capacity); + while (rawdst.size() < size) + { + rawdst.resize(rawdst.size() * 2); + } for (i = 0; i < size; i++) rawdst[i] = 0xFF00; @@ -250,11 +232,11 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle size = (width * height); - RotatedPatch_AllocImgBuf(&rawconv, size, &conv_capacity); - memset(rawconv, 0, conv_capacity * sizeof(UINT16)); + rawconv.resize(size); + memset(rawconv.data(), 0, size * sizeof(UINT16)); src = &rawdst[(miny * newwidth) + minx]; - dest = rawconv; + dest = rawconv.data(); dy = height; while (dy--) @@ -267,14 +249,14 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle ox -= minx; oy -= miny; - rawout = rawconv; + rawout = rawconv.data(); } else { width = newwidth; height = newheight; - rawout = rawdst; + rawout = rawdst.data(); } // make patch diff --git a/src/r_plane.cpp b/src/r_plane.cpp index 475e8a44d..8ef47f722 100644 --- a/src/r_plane.cpp +++ b/src/r_plane.cpp @@ -46,15 +46,15 @@ // good night sweet prince //#define SHITPLANESPARENCY -visplane_t *visplanes[MAXVISPLANES]; +visplane_t *visplanes[MAXVISPLANES] = {}; static visplane_t *freetail; static visplane_t **freehead = &freetail; -visplane_t *floorplane; -visplane_t *ceilingplane; +visplane_t *floorplane = NULL; +visplane_t *ceilingplane = NULL; -visffloor_t visffloor[MAXFFLOORS]; -INT32 numffloors; +visffloor_t visffloor[MAXFFLOORS] = {}; +INT32 numffloors = 0; //SoM: 3/23/2000: Boom visplane hashing routine. #define visplane_hash(picnum,lightlevel,height) \ @@ -65,8 +65,8 @@ INT32 numffloors; // floorclip starts out SCREENHEIGHT // ceilingclip starts out -1 // -INT16 *floorclip, *ceilingclip; -fixed_t *frontscale; +INT16 *floorclip = NULL, *ceilingclip = NULL; +fixed_t *frontscale = NULL; // // spanstart holds the start of a plane span @@ -81,13 +81,13 @@ static INT32 *spanstart; // (this is to calculate yslopes only when really needed) // (when mouselookin', yslope is moving into yslopetab) // Check R_SetupFrame, R_SetViewSize for more... -fixed_t *yslopetab; -fixed_t *yslope; +fixed_t *yslopetab = NULL; +fixed_t *yslope = NULL; -fixed_t basexscale, baseyscale; +fixed_t basexscale = 0, baseyscale = 0; -static INT16 *ffloor_f_clip; -static INT16 *ffloor_c_clip; +static INT16 *ffloor_f_clip = NULL; +static INT16 *ffloor_c_clip = NULL; static void R_SetTiltedSpan(drawspandata_t* ds, INT32 span); static void R_SetSlopePlaneVectors(drawspandata_t* ds, visplane_t *pl, INT32 y, fixed_t xoff, fixed_t yoff); @@ -616,14 +616,12 @@ void R_ExpandPlane(visplane_t *pl, INT32 start, INT32 stop) // static void R_MakeSpans(void (*mapfunc)(drawspandata_t* ds, void(*spanfunc)(drawspandata_t*), INT32, INT32, INT32, boolean), spandrawfunc_t* localspanfunc, drawspandata_t* ds, INT32 x, INT32 t1, INT32 b1, INT32 t2, INT32 b2, boolean allow_parallel) { - const INT32 vidheight = vid.height; - // Alam: from r_splats's R_RenderFloorSplat - if (t1 >= vidheight) t1 = vidheight-1; - if (b1 >= vidheight) b1 = vidheight-1; - if (t2 >= vidheight) t2 = vidheight-1; - if (b2 >= vidheight) b2 = vidheight-1; - if (x-1 >= vid.width) x = vid.width; + if (t1 >= viewheight) t1 = viewheight-1; + if (b1 >= viewheight) b1 = viewheight-1; + if (t2 >= viewheight) t2 = viewheight-1; + if (b2 >= viewheight) b2 = viewheight-1; + if (x-1 >= viewwidth) x = viewwidth; #ifdef HAVE_THREADS // We want to draw N spans per subtask to ensure the work is @@ -716,13 +714,10 @@ void R_DrawPlanes(void) visplane_t *pl; INT32 i; drawspandata_t ds = {}; -#ifdef HAVE_THREADS - srb2::ThreadPool::Sema tp_sema; -#endif - R_UpdatePlaneRipple(&ds); #ifdef HAVE_THREADS + srb2::ThreadPool::Sema tp_sema; srb2::g_main_threadpool->begin_sema(); #endif for (i = 0; i < MAXVISPLANES; i++, pl++) @@ -742,13 +737,20 @@ void R_DrawPlanes(void) #endif } -static void R_DrawSkyPlane(visplane_t *pl, void(*colfunc2)(drawcolumndata_t*), boolean allow_parallel); +static void R_DrawSkyPlane(visplane_t *pl, void(*skycolfunc)(drawcolumndata_t*), boolean allow_parallel); void R_DrawSkyPlanes(void) { visplane_t *pl; INT32 i; + // If we're not supposed to draw the sky (e.g. for skyboxes), don't do anything! + // This probably utterly ruins sky rendering for FOFs and polyobjects, unfortunately + if (!newview->sky) + { + return; + } + #ifdef HAVE_THREADS srb2::ThreadPool::Sema tp_sema; srb2::g_main_threadpool->begin_sema(); @@ -770,24 +772,17 @@ void R_DrawSkyPlanes(void) #endif } -static void R_DrawSkyPlane(visplane_t *pl, void(*colfunc2)(drawcolumndata_t*), boolean allow_parallel) +static void R_DrawSkyPlane(visplane_t *pl, void(*skycolfunc)(drawcolumndata_t*), boolean allow_parallel) { INT32 x; if (!(pl->minx <= pl->maxx)) return; - // If we're not supposed to draw the sky (e.g. for skyboxes), don't do anything! - // This probably utterly ruins sky rendering for FOFs and polyobjects, unfortunately - if (!newview->sky) - { - return; - } - drawcolumndata_t dc = {}; const INT32 texture = texturetranslation[skytexture]; - // Reset column drawer function (note: couldn't we just call walldrawerfunc directly?) + // Reset column drawer function (note: couldn't we just call colfuncs[BASEDRAWFUNC] directly?) // (that is, unless we'll need to switch drawers in future for some reason) R_SetColumnFunc(BASEDRAWFUNC); @@ -837,7 +832,7 @@ static void R_DrawSkyPlane(visplane_t *pl, void(*colfunc2)(drawcolumndata_t*), b dc.x = x + i; dc.source = R_GetColumn(texture, -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 - colfunc2(&dc); + skycolfunc(&dc); } }; @@ -871,10 +866,9 @@ static void R_DrawSkyPlane(visplane_t *pl, void(*colfunc2)(drawcolumndata_t*), b dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x]>>ANGLETOFINESHIFT)); dc.x = x; dc.source = - R_GetColumn(texturetranslation[skytexture], - -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 + R_GetColumn(texturetranslation[skytexture], -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 - colfunc2(&dc); + skycolfunc(&dc); } #endif } @@ -1159,7 +1153,7 @@ void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl, boolean allow_paralle offset = (scry*vid.width) + scrx; // No idea if this works - VID_BlitLinearScreen(renderscreen + offset, + VID_BlitLinearScreen(vid.screens[0] + offset, vid.screens[1] + (top*vid.width), // intentionally not +offset viewwidth, bottom-top, vid.width, vid.width); diff --git a/src/r_segs.cpp b/src/r_segs.cpp index c83b45593..d1cbbf9c2 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -26,7 +26,6 @@ #include "p_local.h" // Camera... #include "p_setup.h" #include "p_slopes.h" -#include "console.h" // con_clipviewtop #include "screen.h" #include "core/memory.h" @@ -628,8 +627,6 @@ void R_RenderThickSideRange(drawseg_t *drawseg, INT32 x1, INT32 x2, ffloor_t *pf sector_t tempsec; INT32 templight; INT32 i, p; - fixed_t bottombounds = viewheight << FRACBITS; - fixed_t topbounds = (con_clipviewtop - 1) << FRACBITS; fixed_t offsetvalue = 0; lightlist_t *light; r_lightlist_t *rlight; @@ -936,7 +933,7 @@ void R_RenderThickSideRange(drawseg_t *drawseg, INT32 x1, INT32 x2, ffloor_t *pf bottom_frac += bottom_step; // SoM: If column is out of range, why bother with it?? - if (windowbottom < topbounds || windowtop > bottombounds) + if (windowbottom < 0 || windowtop > (viewheight << FRACBITS)) { if (dc->numlights) { @@ -2239,7 +2236,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) lowcutslope = std::max(worldbottomslope, worldlowslope) + viewz; highcutslope = std::min(worldtopslope, worldhighslope) + viewz; - auto check_fof_offscreen = [&](INT32 bottom, INT32 bottomslope, INT32 top, INT32 topslope) + auto check_fof_offscreen = [&](ffloor_t* rover, INT32 bottom, INT32 bottomslope, INT32 top, INT32 topslope) { return ((P_GetFFloorTopZAt (rover, segleft .x, segleft .y) <= bottom + viewz && P_GetFFloorTopZAt (rover, segright.x, segright.y) <= bottomslope + viewz) @@ -2379,7 +2376,7 @@ void R_StoreWallRange(INT32 start, INT32 stop) continue; // Oy vey. - if (check_fof_offscreen(worldbottom, worldbottomslope, worldtop, worldtopslope)) + if (check_fof_offscreen(rover, worldbottom, worldbottomslope, worldtop, worldtopslope)) continue; ds_p->thicksides[i] = rover; @@ -2397,10 +2394,10 @@ void R_StoreWallRange(INT32 start, INT32 stop) continue; // Oy vey. - if (check_fof_offscreen(worldbottom, worldbottomslope, worldtop, worldtopslope)) + if (check_fof_offscreen(rover, worldbottom, worldbottomslope, worldtop, worldtopslope)) continue; - if (check_fof_offscreen(worldlow, worldlowslope, worldhigh, worldhighslope)) + if (check_fof_offscreen(rover, worldlow, worldlowslope, worldhigh, worldhighslope)) continue; ds_p->thicksides[i] = rover; diff --git a/src/r_skins.c b/src/r_skins.c index f0fbfcfd1..9d289f936 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -35,6 +35,8 @@ CV_PossibleValue_t Forceskin_cons_t[MAXSKINS+2]; +#include "discord.h" + INT32 numskins = 0; INT32 numallskins = 0; INT32 numlocalskins = 0; @@ -328,8 +330,14 @@ void SetPlayerSkinByNum(INT32 playernum, INT32 skinnum) if (player->mo) P_SetScale(player->mo, player->mo->scale); + // for replays: We have changed our skin mid-game; let the game know so it can do the same in the replay! demo_extradata[playernum] |= DXD_SKIN; +#ifdef HAVE_DISCORDRPC + if (player - players == consoleplayer) + DRPC_UpdatePresence(); +#endif + return; } diff --git a/src/r_things.cpp b/src/r_things.cpp index 4713bc50e..75c333cd4 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -43,13 +43,6 @@ #define MINZ (FRACUNIT*16) #define BASEYCENTER (BASEVIDHEIGHT/2) -typedef struct -{ - INT32 x1, x2; - INT32 column; - INT32 topclip, bottomclip; -} maskdraw_t; - // // Sprite rotation 0 is facing the viewer, // rotation 1 is one angle turn CLOCKWISE around the axis. @@ -60,8 +53,8 @@ typedef struct static lighttable_t **spritelights; // constant arrays used for psprite clipping and initializing clipping -INT16 *negonearray; -INT16 *screenheightarray; +INT16 *negonearray = NULL; +INT16 *screenheightarray = NULL; // // INITIALIZATION FUNCTIONS @@ -94,13 +87,6 @@ static drawseg_xrange_item_t *drawsegs_xrange; static size_t drawsegs_xrange_size = 0; static INT32 drawsegs_xrange_count = 0; -INT32 R_ThingLightLevel(mobj_t* thing) -{ - INT32 lightlevel = thing->lightlevel; - - return lightlevel; -} - // // Sprite rotation 0 is facing the viewer, // rotation 1 is one angle turn CLOCKWISE around the axis. @@ -546,8 +532,8 @@ void R_ClearSprites(void) visspritecount = numvisiblesprites = clippedvissprites = 0; } -static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS]; -static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS]; +static INT16 *vissprite_clipbot[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; +static INT16 *vissprite_cliptop[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {0}; static void R_AllocVisSpriteChunkMemory(UINT32 chunk) { @@ -581,16 +567,16 @@ static vissprite_t overflowsprite; static vissprite_t *R_GetVisSprite(UINT32 num) { - UINT32 chunk = num >> VISSPRITECHUNKBITS; + UINT32 chunk = num >> VISSPRITECHUNKBITS; - // Allocate chunk if necessary - if (!visspritechunks[chunk]) - { - Z_Malloc(sizeof(vissprite_t) * VISSPRITESPERCHUNK, PU_LEVEL, &visspritechunks[chunk]); - R_AllocVisSpriteChunkMemory(chunk); - } + // Allocate chunk if necessary + if (!visspritechunks[chunk]) + { + Z_Malloc(sizeof(vissprite_t) * VISSPRITESPERCHUNK, PU_LEVEL, &visspritechunks[chunk]); + R_AllocVisSpriteChunkMemory(chunk); + } - return visspritechunks[chunk] + (num & VISSPRITEINDEXMASK); + return visspritechunks[chunk] + (num & VISSPRITEINDEXMASK); } static vissprite_t *R_NewVisSprite(void) @@ -607,8 +593,8 @@ static vissprite_t *R_NewVisSprite(void) // Masked means: partly transparent, i.e. stored // in posts/runs of opaque pixels. // -INT16 *mfloorclip; -INT16 *mceilingclip; +INT16 *mfloorclip = NULL; +INT16 *mceilingclip = NULL; fixed_t spryscale = 0, sprtopscreen = 0, sprbotscreen = 0; fixed_t windowtop = 0, windowbottom = 0; @@ -737,7 +723,6 @@ static void R_DrawFlippedMaskedColumn(drawcolumndata_t* dc, column_t *column) dc->texturemid = basetexturemid; } - // Based off of R_GetLinedefTransTable transnum_t R_GetThingTransTable(fixed_t alpha, transnum_t transmap) { @@ -2525,8 +2510,6 @@ void R_InitDrawNodes(void) // R_DrawSprite // //Fab : 26-04-98: -// NOTE : uses con_clipviewtop, so that when console is on, -// don't draw the part of sprites hidden under the console static void R_DrawSprite(vissprite_t *spr) { mfloorclip = spr->clipbot; @@ -2826,6 +2809,7 @@ void R_ClipSprites(drawseg_t* dsstart, portal_t* portal) if (drawsegs_xrange_size < maxdrawsegs) { + // haleyjd: fix reallocation to track 2x size drawsegs_xrange_size = 2 * maxdrawsegs; for (i = 0; i < DS_RANGES_COUNT; i++) @@ -2865,6 +2849,9 @@ void R_ClipSprites(drawseg_t* dsstart, portal_t* portal) } } + // haleyjd: terminate with a nullptr user for faster loop - adds ~3 FPS + drawsegs_xranges[0].items[drawsegs_xranges[0].count].user = nullptr; + for (; clippedvissprites < visspritecount; clippedvissprites++) { vissprite_t *spr = R_GetVisSprite(clippedvissprites); @@ -3069,6 +3056,9 @@ void R_DrawMasked(maskcount_t* masks, INT32 nummasks) heads = static_cast(calloc(nummasks, sizeof(drawnode_t))); + if (!heads) + I_Error("R_DrawMasked: No more free memory\n"); + for (i = 0; i < nummasks; i++) { heads[i].next = heads[i].prev = &heads[i]; diff --git a/src/r_things.h b/src/r_things.h index 9cba7340d..fd03a6611 100644 --- a/src/r_things.h +++ b/src/r_things.h @@ -23,10 +23,10 @@ extern "C" { // number of sprite lumps for spritewidth,offset,topoffset lookup tables // Fab: this is a hack : should allocate the lookup tables per sprite -#if defined(__x86_64__) || defined(__amd64__) || defined(__aarch64__) || defined(__arm64__) // only for 64bit (idk how else to proper check lmao) -#define MAXVISSPRITES 4096 -#else +#if __SIZEOF_POINTER__ < 8 #define MAXVISSPRITES 2048 // added 2-2-98 was 128 +#else +#define MAXVISSPRITES 4096 // only for 64bit #endif #define VISSPRITECHUNKBITS 6 // 2^6 = 64 sprites per chunk @@ -63,7 +63,10 @@ extern fixed_t windowtop; extern fixed_t windowbottom; extern INT32 lengthcol; -INT32 R_ThingLightLevel(mobj_t *thing); +FUNCINLINE static ATTRINLINE INT32 R_ThingLightLevel(mobj_t* thing) +{ + return (INT32)thing->lightlevel; +} fixed_t R_GetSpriteDirectionalLighting(angle_t angle); fixed_t R_GetShadowZ(mobj_t *thing, pslope_t **shadowslope); @@ -83,7 +86,7 @@ typedef struct { size_t drawsegs[2]; size_t vissprites[2]; - fixed_t viewx, viewy, viewz; /**< View z stored at the time of the BSP traversal for the view/portal. Masked sorting/drawing needs it. */ + fixed_t viewx, viewy, viewz; /**< View z stored at the time of the BSP traversal for the view/portal. Masked sorting/drawing needs it. */ sector_t* viewsector; } maskcount_t; diff --git a/src/screen.c b/src/screen.c index 21ec0ed52..4a38ef97d 100644 --- a/src/screen.c +++ b/src/screen.c @@ -80,11 +80,7 @@ consvar_t cv_accuratefps = {"fpssampling", "1", CV_SAVE, accuratefps_cons_t, NUL // SCREEN VARIABLES // ========================================================================= -UINT8 *scr_borderpatch; // flat used to fill the reduced view borders set at ST_Init() - -// ========================================================================= - -static void SCR_SetDrawFuncs(void) +static void SCR_SetDrawFuncs(enum columncontext_e _columncontext) { // // setup the right draw routines @@ -103,13 +99,27 @@ static void SCR_SetDrawFuncs(void) spanfuncs[SPANDRAWFUNC_FOG] = R_DrawFogSpan; spanfuncs[SPANDRAWFUNC_TILTEDFOG] = R_DrawFogSpan_Tilted; - colfuncs[BASEDRAWFUNC] = R_DrawColumn; - colfuncs[COLDRAWFUNC_FUZZY] = R_DrawTranslucentColumn; - colfuncs[COLDRAWFUNC_TRANS] = R_DrawTranslatedColumn; - colfuncs[COLDRAWFUNC_SHADOWED] = R_DrawColumnShadowed; - colfuncs[COLDRAWFUNC_TRANSTRANS] = R_DrawTranslatedTranslucentColumn; - colfuncs[COLDRAWFUNC_TWOSMULTIPATCH] = R_Draw2sMultiPatchColumn; - colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS] = R_Draw2sMultiPatchTranslucentColumn; + if (_columncontext == COLUMNCONTEXT_FLUSH) + { + colfuncs[BASEDRAWFUNC] = R_DrawColumn_Flush; + colfuncs[COLDRAWFUNC_FUZZY] = R_DrawTranslucentColumn_Flush; + colfuncs[COLDRAWFUNC_TRANS] = R_DrawTranslatedColumn_Flush; + colfuncs[COLDRAWFUNC_SHADOWED] = R_DrawColumnShadowed_Flush; + colfuncs[COLDRAWFUNC_TRANSTRANS] = R_DrawTranslatedTranslucentColumn_Flush; + colfuncs[COLDRAWFUNC_TWOSMULTIPATCH] = R_Draw2sMultiPatchColumn_Flush; + colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS] = R_Draw2sMultiPatchTranslucentColumn_Flush; + } + else + { + colfuncs[BASEDRAWFUNC] = R_DrawColumn; + colfuncs[COLDRAWFUNC_FUZZY] = R_DrawTranslucentColumn; + colfuncs[COLDRAWFUNC_TRANS] = R_DrawTranslatedColumn; + colfuncs[COLDRAWFUNC_SHADOWED] = R_DrawColumnShadowed; + colfuncs[COLDRAWFUNC_TRANSTRANS] = R_DrawTranslatedTranslucentColumn; + colfuncs[COLDRAWFUNC_TWOSMULTIPATCH] = R_Draw2sMultiPatchColumn; + colfuncs[COLDRAWFUNC_TWOSMULTIPATCHTRANS] = R_Draw2sMultiPatchTranslucentColumn; + } + colfuncs[COLDRAWFUNC_FOG] = R_DrawFogColumn; R_SetColumnFunc(BASEDRAWFUNC); @@ -131,12 +141,23 @@ void SCR_SetMode(void) V_SetPalette(0); - SCR_SetDrawFuncs(); + SCR_SetDrawFuncs(COLUMNCONTEXT_DIRECT); // set the apprpriate drawer for the sky (tall or INT16) setmodeneeded = 0; } +// used to switch between column buffering and drawing them directly to screen +// our sky "plane" drawer cannot handle the buffer system due to multithreading +// (that would require alot of extra complexity for smth with massive diminishing results) +// Our masked drawing step draws things in a very particular order, which results in alot of flushing to screen +// effectively adding massive overhead due to excessive flushing, so we draw our masked thing directly to screen instead +void R_SetColumnContext(enum columncontext_e _columncontext) +{ + columncontext = _columncontext; + SCR_SetDrawFuncs(_columncontext); // set our column drawers +} + void R_SetColumnFunc(size_t id) { I_Assert(id < COLDRAWFUNC_MAX); @@ -298,7 +319,6 @@ void SCR_SetDefaultMode(void) // Change fullscreen on/off according to cv_fullscreen void SCR_ChangeFullscreen(void) { -#ifdef DIRECTFULLSCREEN I_SetBorderlessWindow(); // Running this here so we can have borderless window at startup // allow_fullscreen is set by VID_PrepareModeList @@ -311,8 +331,8 @@ void SCR_ChangeFullscreen(void) VID_PrepareModeList(); setmodeneeded = VID_GetModeForSize(vid.width, vid.height) + 1; } + return; -#endif } boolean SCR_IsAspectCorrect(INT32 width, INT32 height) @@ -400,74 +420,97 @@ void SCR_CalculateFPS(void) #endif } +static void SCR_DrawOldTicRate(UINT32 cap, UINT32 benchmark, double fps, INT32 fpsflags) +{ + const char *fps_string; + INT32 ticcntcolor = 0; + + if (fps > (benchmark - 5)) + ticcntcolor = V_GREENMAP; + else if (fps < 20) + ticcntcolor = V_REDMAP; + + if (cap != 0) + fps_string = va("%d/%d\x82", (INT32)fps, cap); + else + fps_string = va("%d\x82", (INT32)fps); + + // draw "FPS" + if (cv_ticrate.value == 3) + V_DrawRightAlignedString(319, 181, V_YELLOWMAP|fpsflags, "FPS"); + + V_DrawRightAlignedString(319, 190, ticcntcolor|fpsflags, fps_string); +} + +static void SCR_DrawKartTicRate(UINT32 cap, UINT32 benchmark, double fps, INT32 fpsflags) +{ + UINT8 *ticcntcolor = NULL; + INT32 x = 318; + + // draw "FPS" + if (cv_ticrate.value == 1) + { + ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_YELLOW, GTC_CACHE); + V_DrawFixedPatch(306< (benchmark - 5)) + ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_MINT, GTC_CACHE); + else if (fps < 20) + ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); + else + ticcntcolor = NULL; + + if (cap != 0) + { + UINT32 digits = 1; + UINT32 c2 = cap; + + while (c2 > 0) + { + c2 = c2 / 10; + digits++; + } + + // draw total frame: + V_DrawPingNum(x, 190, fpsflags, cap, ticcntcolor); + + x -= digits * 4; + + // draw "/" + V_DrawFixedPatch(x< (benchmark - 5)) - ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_MINT, GTC_CACHE); - else if (fps < 20) - ticcntcolor = R_GetTranslationColormap(TC_RAINBOW, SKINCOLOR_RASPBERRY, GTC_CACHE); - - if (cap != 0) - { - UINT32 digits = 1; - UINT32 c2 = cap; - - while (c2 > 0) - { - c2 = c2 / 10; - digits++; - } - - // draw total frame: - V_DrawPingNum(x, 190, fpsflags, cap, ticcntcolor); - - x -= digits * 4; - - // draw "/" - V_DrawFixedPatch(x< (benchmark - 5)) - ticcntcolor2 = V_GREENMAP; - else if (fps < 20) - ticcntcolor2 = V_REDMAP; - - if (cap != 0) - fps_string = va("%d/%d\x82", (INT32)fps, cap); - else - fps_string = va("%d\x82", (INT32)fps); - - // draw "FPS" - if (cv_ticrate.value == 3) - V_DrawRightAlignedString(319, 181, V_YELLOWMAP|fpsflags, "FPS"); - - V_DrawRightAlignedString(319, 190, ticcntcolor2|fpsflags, fps_string); + case 1: // new kart counter + case 2: + SCR_DrawKartTicRate(cap, benchmark, fps, fpsflags); + break; + case 3: // kart v1.0/srb2 counter + case 4: + SCR_DrawOldTicRate(cap, benchmark, fps, fpsflags); + break; + default: + break; } } @@ -482,7 +525,6 @@ void SCR_DisplayLocalPing(void) if (cv_showping.value == 1 || (cv_showping.value == 2 && ping > servermaxping)) // only show 2 (warning) if our ping is at a bad level { INT32 dispy = (cv_ticrate.value == 1) ? 165 : ((cv_ticrate.value == 2 || cv_ticrate.value == 4) ? 172 : ((cv_ticrate.value == 3) ? 163 : 181)); // absolute buttpain - HU_drawPlayerPing(308, dispy, consoleplayer, pingflags); // consoleplayer's ping is everyone's ping in a splitnetgame :P } } diff --git a/src/screen.h b/src/screen.h index ecad24a64..0a912e97a 100644 --- a/src/screen.h +++ b/src/screen.h @@ -84,8 +84,6 @@ enum extern viddef_t vid; extern INT32 setmodeneeded; // mode number to set if needed, or 0 -extern UINT8 *scr_borderpatch; // patch used to fill the view borders - extern consvar_t cv_scr_width, cv_scr_height, cv_renderview, cv_frameskip, cv_fullscreen, cv_vhseffect, cv_shittyscreen; extern consvar_t cv_parallelsoftware; extern consvar_t cv_paralleldrawmasked; @@ -96,6 +94,7 @@ extern consvar_t cv_vidwait; extern consvar_t cv_votebgscaling; +//void R_SetColumnContext(enum columncontext_e _columncontext); // declared in r_draw! void R_SetColumnFunc(size_t id); void R_SetSpanFunc(size_t id); boolean R_CheckColumnFunc(size_t id); diff --git a/src/sdl/Srb2SDL.dsp b/src/sdl/Srb2SDL.dsp index 47ede4126..96d3e8418 100644 --- a/src/sdl/Srb2SDL.dsp +++ b/src/sdl/Srb2SDL.dsp @@ -45,7 +45,7 @@ MTL=midl.exe # ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32 # ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /G5 /W3 /GX /Zi /Ot /Og /Oi /Op /Oy /Ob1 /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "NDEBUG" /D "SDLMAIN" /D "NO_STDIO_REDIRECT" /D "USE_WGL_SWAP" /D "DIRECTFULLSCREEN" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GF /c +# ADD CPP /nologo /G5 /W3 /GX /Zi /Ot /Og /Oi /Op /Oy /Ob1 /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "NDEBUG" /D "SDLMAIN" /D "NO_STDIO_REDIRECT" /D "USE_WGL_SWAP" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GF /c # ADD BASE RSC /l 0x409 /d "NDEBUG" # ADD RSC /l 0x409 /d "NDEBUG" # SUBTRACT RSC /x @@ -72,7 +72,7 @@ LINK32=link.exe # PROP Target_Dir "" MTL=midl.exe # ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /G6 /W4 /WX /Gm /GX /ZI /Od /Op /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "_DEBUG" /D "USE_WGL_SWAP" /D "DIRECTFULLSCREEN" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GZ /c +# ADD CPP /nologo /G6 /W4 /WX /Gm /GX /ZI /Od /Op /I "..\..\libs\libpng-src" /I "..\..\libs\zlib" /D "_DEBUG" /D "USE_WGL_SWAP" /D "HAVE_SDL" /D "HWRENDER" /D "HAVE_FILTER" /D "HAVE_MIXER" /D "USEASM" /D "HAVE_PNG" /FR /FD /GZ /c # SUBTRACT CPP /YX # ADD BASE RSC /l 0x409 /d "_DEBUG" # ADD RSC /l 0x409 /d "_DEBUG" diff --git a/src/sdl/Srb2SDL.props b/src/sdl/Srb2SDL.props index f02b9b35e..8c4799f20 100644 --- a/src/sdl/Srb2SDL.props +++ b/src/sdl/Srb2SDL.props @@ -6,9 +6,9 @@ - HAVE_ZLIB;HAVE_LIBGME;USE_WGL_SWAP;DIRECTFULLSCREEN;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) + HAVE_ZLIB;HAVE_LIBGME;USE_WGL_SWAP;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) - USE_WGL_SWAP;DIRECTFULLSCREEN;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) + USE_WGL_SWAP;HAVE_SDL;HWRENDER;HAVE_FILTER;HAVE_MIXER;SDLMAIN;%(PreprocessorDefinitions) diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 7314995e8..4e9e54d72 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -545,7 +545,7 @@ static inline void I_ShutdownConsole(void){} // -//I_OutputMsg +// I_OutputMsg // void I_OutputMsg(const char *fmt, ...) { @@ -553,6 +553,9 @@ void I_OutputMsg(const char *fmt, ...) char *txt; va_list argptr; + if (!fmt) + return; + va_start(argptr,fmt); len = vsnprintf(NULL, 0, fmt, argptr); va_end(argptr); @@ -560,6 +563,10 @@ void I_OutputMsg(const char *fmt, ...) return; txt = static_cast(malloc(len+1)); + + if (!txt) + I_Error("I_OutputMsg: Out of memory!\n"); + va_start(argptr,fmt); vsprintf(txt, fmt, argptr); va_end(argptr); @@ -2021,7 +2028,7 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) if (errorcount > 20) { va_start(argptr, error); - vsprintf(buffer, error, argptr); + vsnprintf(buffer, 8192, error, argptr); va_end(argptr); // Implement message box with SDL_ShowSimpleMessageBox, // which should fail gracefully if it can't put a message box up @@ -2039,7 +2046,7 @@ FUNCIERROR void ATTRNORETURN I_Error(const char *error, ...) // Display error message in the console before we start shutting it down va_start(argptr, error); - vsprintf(buffer, error, argptr); + vsnprintf(buffer, 8192, error, argptr); va_end(argptr); I_OutputMsg("\nI_Error(): %s\n", buffer); diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 9ce860cb4..7393d8e4b 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -156,9 +156,9 @@ static SDL_bool usesdl2soft = SDL_FALSE; static SDL_bool borderlesswindow = SDL_FALSE; // SDL2 vars -SDL_Window *window; -SDL_Renderer *renderer; -static SDL_Texture *texture; +SDL_Window *window = NULL; +SDL_Renderer *renderer = NULL; +static SDL_Texture *texture = NULL; static SDL_bool havefocus = SDL_TRUE; static const char *fallback_resolution_name = "Fallback"; @@ -412,6 +412,10 @@ static INT32 GetTypedChar(SDL_Keysym keysym) break; } + // Special case for console key + if (scancode == SDL_SCANCODE_GRAVE) + return '`'; + if (SDL_PeepEvents(&next_event, 1, SDL_PEEKEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT) == 1 && next_event.type == SDL_TEXTINPUT) { if (next_event.text.text[1] == '\0') // limit to ASCII @@ -905,6 +909,7 @@ static void Impl_HandleControllerAddedEvent(SDL_Event evt) cv_usejoystick[i].value = 0; else if (atoi(cv_usejoystick[i].string) <= I_NumJoys() // don't mess if we intentionally set higher than NumJoys && cv_usejoystick[i].value) // update the cvar ONLY if a device exists + CV_SetValue(&cv_usejoystick[i], cv_usejoystick[i].value); } @@ -1107,9 +1112,11 @@ void I_OsPolling(void) I_GetEvent(); mod = SDL_GetModState(); + /* Handle here so that our state is always synched with the system. */ shiftdown = ctrldown = altdown = 0; capslock = false; + if (mod & KMOD_LSHIFT) shiftdown |= 1; if (mod & KMOD_RSHIFT) shiftdown |= 2; if (mod & KMOD_LCTRL) ctrldown |= 1; @@ -1143,7 +1150,7 @@ static void VID_Command_Mode_f (void) { INT32 modenum; - if (COM_Argc()!= 2) + if (COM_Argc() != 2) { CONS_Printf("vid_mode : set video mode, current video mode %i\n", vid.modenum); return; @@ -1288,8 +1295,8 @@ static void SDLSetMode(INT32 width, INT32 height, SDL_bool fullscreen) #endif OglSdlSurface(vid.width, vid.height); } + else #endif - if (rendermode == render_soft) { SDL_RenderClear(renderer); @@ -1354,7 +1361,8 @@ void I_FinishUpdate(void) const boolean isserverplayer = consoleplayer == serverplayer; - if (cv_showping.value && ((netgame && !isserverplayer) || (simulated_lag != 0 && isserverplayer && Playing()))) + if (cv_showping.value && ((netgame && !isserverplayer) || + (simulated_lag != 0 && isserverplayer && Playing()))) SCR_DisplayLocalPing(); } @@ -1621,11 +1629,13 @@ static SDL_bool Impl_CreateContext(void) if (!renderer) renderer = SDL_CreateRenderer(window, -1, flags); + if (renderer == NULL) { CONS_Printf(M_GetText("Couldn't create rendering context: %s\n"), SDL_GetError()); return SDL_FALSE; } + SDL_RenderSetLogicalSize(renderer, BASEVIDWIDTH, BASEVIDHEIGHT); } @@ -1728,6 +1738,7 @@ void I_StartupGraphics(void) #endif { const char *vd = SDL_GetCurrentVideoDriver(); + //CONS_Printf(M_GetText("Starting up with video driver: %s\n"), vd); if (vd && (strncasecmp(vd, "fbcon", 6) == 0)) framebuffer = SDL_TRUE; @@ -1958,7 +1969,7 @@ static void Impl_SetVsync(void) #endif #ifdef HWRENDER if (!renderer && rendermode == render_opengl && - sdlglcontext != NULL && SDL_GL_GetCurrentContext() == sdlglcontext) + sdlglcontext != NULL && SDL_GL_GetCurrentContext() == sdlglcontext) { SDL_GL_SetSwapInterval(cv_vidwait.value ? 1 : 0); } diff --git a/src/sdl/mixer_sound.c b/src/sdl/mixer_sound.c index cbc3f5334..646d44135 100644 --- a/src/sdl/mixer_sound.c +++ b/src/sdl/mixer_sound.c @@ -123,13 +123,12 @@ static int result; static void var_cleanup(void) { song_length = loop_point = 0.0f; - music_bytes = fading_source = fading_target =\ - fading_timer = fading_duration = 0; + music_bytes = fading_source = fading_target = + fading_timer = fading_duration = 0; music_end_bytes = 0; music_stutter_bytes = 0; - songpaused = is_looping =\ - is_fading = false; + songpaused = is_looping = is_fading = false; fading_callback = NULL; fading_do_callback = false; @@ -229,6 +228,7 @@ void I_ShutdownSound(void) { if (!sound_started) return; // not an error condition + sound_started = false; Mix_CloseAudio(); @@ -254,6 +254,7 @@ void I_UpdateSound(void) { if (fading_callback) (*fading_callback)(); + fading_callback = NULL; fading_do_callback = false; } @@ -280,6 +281,7 @@ static Mix_Chunk *ds2chunk(void *stream) ver = READUINT16(stream); // sound version format? if (ver != 3) // It should be 3 if it's a doomsound... return NULL; // onos! it's not a doomsound! + freq = READUINT16(stream); samples = READUINT32(stream); @@ -287,91 +289,100 @@ static Mix_Chunk *ds2chunk(void *stream) return NULL; // division by zero // convert from signed 8bit ???hz to signed 16bit 44100hz. - switch(freq) + switch (freq) { - case 44100: - if (samples >= UINT32_MAX>>2) - return NULL; // would wrap, can't store. - newsamples = samples; - break; - case 22050: - if (samples >= UINT32_MAX>>3) - return NULL; // would wrap, can't store. - newsamples = samples<<1; - break; - case 11025: - if (samples >= UINT32_MAX>>4) - return NULL; // would wrap, can't store. - newsamples = samples<<2; - break; - default: - frac = (44100 << FRACBITS) / (UINT32)freq; - if (!(frac & 0xFFFF)) // other solid multiples (change if FRACBITS != 16) - newsamples = samples * (frac >> FRACBITS); - else // strange and unusual fractional frequency steps, plus anything higher than 44100hz. - newsamples = FixedMul(FixedDiv(samples, freq), 44100) + 1; // add 1 to counter truncation. - if (newsamples >= UINT32_MAX>>2) - return NULL; // would and/or did wrap, can't store. - break; + case 44100: + if (samples >= UINT32_MAX>>2) + return NULL; // would wrap, can't store. + + newsamples = samples; + break; + case 22050: + if (samples >= UINT32_MAX>>3) + return NULL; // would wrap, can't store. + + newsamples = samples<<1; + break; + case 11025: + if (samples >= UINT32_MAX>>4) + return NULL; // would wrap, can't store. + + newsamples = samples<<2; + break; + default: + frac = (44100 << FRACBITS) / (UINT32)freq; + + if (!(frac & 0xFFFF)) // other solid multiples (change if FRACBITS != 16) + newsamples = samples * (frac >> FRACBITS); + else // strange and unusual fractional frequency steps, plus anything higher than 44100hz. + newsamples = FixedMul(FixedDiv(samples, freq), 44100) + 1; // add 1 to counter truncation. + + if (newsamples >= UINT32_MAX>>2) + return NULL; // would and/or did wrap, can't store. + + break; } + sound = Z_Malloc(newsamples<<2, PU_SOUND, NULL); // samples * frequency shift * bytes per sample * channels s = (SINT8 *)stream; d = (INT16 *)sound; i = 0; + switch(freq) { - case 44100: // already at the same rate? well that makes it simple. - while(i++ < samples) - { - o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits - *d++ = o; // left channel - *d++ = o; // right channel - } - break; - case 22050: // unwrap 2x - while(i++ < samples) - { - o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits - *d++ = o; // left channel - *d++ = o; // right channel - *d++ = o; // left channel - *d++ = o; // right channel - } - break; - case 11025: // unwrap 4x - while(i++ < samples) - { - o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits - *d++ = o; // left channel - *d++ = o; // right channel - *d++ = o; // left channel - *d++ = o; // right channel - *d++ = o; // left channel - *d++ = o; // right channel - *d++ = o; // left channel - *d++ = o; // right channel - } - break; - default: // convert arbitrary hz to 44100. - step = 0; - frac = ((UINT32)freq << FRACBITS) / 44100 + 1; //Add 1 to counter truncation. - while (i < samples) - { - o = (INT16)(*s+0x80)<<8; // changed signedness and shift up to 16 bits - while (step < FRACUNIT) // this is as fast as I can make it. + case 44100: // already at the same rate? well that makes it simple. + while(i++ < samples) { + o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits *d++ = o; // left channel *d++ = o; // right channel - step += frac; } - do { - i++; s++; - step -= FRACUNIT; - } while (step >= FRACUNIT); - } - break; + break; + case 22050: // unwrap 2x + while(i++ < samples) + { + o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits + *d++ = o; // left channel + *d++ = o; // right channel + *d++ = o; // left channel + *d++ = o; // right channel + } + break; + case 11025: // unwrap 4x + while(i++ < samples) + { + o = ((INT16)(*s++)+0x80)<<8; // changed signedness and shift up to 16 bits + *d++ = o; // left channel + *d++ = o; // right channel + *d++ = o; // left channel + *d++ = o; // right channel + *d++ = o; // left channel + *d++ = o; // right channel + *d++ = o; // left channel + *d++ = o; // right channel + } + break; + default: // convert arbitrary hz to 44100. + step = 0; + frac = ((UINT32)freq << FRACBITS) / 44100 + 1; //Add 1 to counter truncation. + + while (i < samples) + { + o = (INT16)(*s+0x80)<<8; // changed signedness and shift up to 16 bits + while (step < FRACUNIT) // this is as fast as I can make it. + { + *d++ = o; // left channel + *d++ = o; // right channel + step += frac; + } + do { + i++; s++; + step -= FRACUNIT; + } while (step >= FRACUNIT); + } + break; } // return Mixer Chunk. @@ -390,12 +401,14 @@ void *I_GetSfx(sfxinfo_t *sfx) if (sfx->lumpnum == LUMPERROR) sfx->lumpnum = S_GetSfxLumpNum(sfx); + sfx->length = W_LumpLength(sfx->lumpnum); lump = W_CacheLumpNum(sfx->lumpnum, PU_SOUND); // convert from standard DoomSound format. chunk = ds2chunk(lump); + if (chunk) { Z_Free(lump); @@ -415,6 +428,7 @@ void *I_GetSfx(sfxinfo_t *sfx) int zErr; // Somewhere to handle any error messages zlib tosses out memset(&stream, 0x00, sizeof (z_stream)); // Init zlib stream + // Begin the inflation process inflatedLen = *(UINT32 *)lump + (sfx->length-4); // Last 4 bytes are the decompressed size, typically inflatedData = (UINT8 *)Z_Malloc(inflatedLen, PU_SOUND, NULL); // Make room for the decompressed data @@ -424,10 +438,13 @@ void *I_GetSfx(sfxinfo_t *sfx) stream.next_out = inflatedData; zErr = inflateInit2(&stream, 32 + MAX_WBITS); + if (zErr == Z_OK) // We're good to go { zErr = inflate(&stream, Z_FINISH); - if (zErr == Z_STREAM_END) { + + if (zErr == Z_STREAM_END) + { // Run GME on new data if (!gme_open_data(inflatedData, inflatedLen, &emu, SAMPLERATE)) { @@ -444,6 +461,7 @@ void *I_GetSfx(sfxinfo_t *sfx) len = (info->play_length * 441 / 10) << 2; mem = Z_Malloc(len, PU_SOUND, 0); + gme_play(emu, len >> 1, mem); gme_free_info(info); gme_delete(emu); @@ -453,10 +471,14 @@ void *I_GetSfx(sfxinfo_t *sfx) } else CONS_Alert(CONS_ERROR,"Encountered %s when running inflate: %s\n", get_zlib_error(zErr), stream.msg); + (void)inflateEnd(&stream); } else // Hold up, zlib's got a problem + { CONS_Alert(CONS_ERROR,"Encountered %s when running inflateInit: %s\n", get_zlib_error(zErr), stream.msg); + } + Z_Free(inflatedData); // GME didn't open jack, but don't let that stop us from freeing this up #else return NULL; // No zlib support @@ -477,6 +499,7 @@ void *I_GetSfx(sfxinfo_t *sfx) len = (info->play_length * 441 / 10) << 2; mem = Z_Malloc(len, PU_SOUND, 0); + gme_play(emu, len >> 1, mem); gme_free_info(info); gme_delete(emu); @@ -487,6 +510,7 @@ void *I_GetSfx(sfxinfo_t *sfx) // Try to load it as a WAVE or OGG using Mixer. rw = SDL_RWFromMem(lump, sfx->length); + if (rw != NULL) { chunk = Mix_LoadWAV_RW(rw, 1); @@ -502,19 +526,23 @@ void I_FreeSfx(sfxinfo_t *sfx) { Mix_Chunk *chunk = (Mix_Chunk*)sfx->data; UINT8 *abufdata = NULL; + if (chunk->allocated == 0) { // We allocated the data in this chunk, so get the abuf from mixer, then let it free the chunk, THEN we free the data // I believe this should ensure the sound is not playing when we free it abufdata = chunk->abuf; } + Mix_FreeChunk(sfx->data); + if (abufdata) { // I'm going to assume we used Z_Malloc to allocate this data. Z_Free(abufdata); } } + sfx->data = NULL; sfx->lumpnum = LUMPERROR; } @@ -572,9 +600,12 @@ static UINT32 get_adjusted_position(UINT32 position) { // all in milliseconds UINT32 length = I_GetSongLength(); - UINT32 looppoint = I_GetSongLoopPoint(); + if (length) + { + UINT32 looppoint = I_GetSongLoopPoint(); return position >= length ? (position % (length-looppoint)) : position; + } else return position; } @@ -589,8 +620,7 @@ static void do_fading_callback(void) /// Music Hooks /// ------------------------ -static void -Countstutter (int len) +static void Countstutter(int len) { UINT32 bytes; @@ -617,7 +647,7 @@ Countstutter (int len) else bytes = ( music_bytes - music_stutter_bytes ); - I_SetSongPosition((int)( (float)bytes/4/44100.0f*1000 )); + I_SetSongPosition((int)((float)bytes/4/44100.0f*1000)); } } } @@ -628,7 +658,9 @@ static void count_music_bytes(int chan, void *stream, int len, void *udata) (void)stream; (void)udata; - if (!music || I_SongType() == MU_GME || I_SongType() == MU_MOD || I_SongType() == MU_MID) + const musictype_t mustype = I_SongType(); + + if (!music || mustype == MU_GME || mustype == MU_MOD || mustype == MU_MID) return; music_bytes += len; @@ -662,7 +694,9 @@ static UINT32 music_fade(UINT32 interval, void *param) return 0; } else if (songpaused) // don't decrement timer + { return interval; + } else if ((fading_timer -= 10) <= 0) { internal_volume = fading_target; @@ -675,11 +709,14 @@ static UINT32 music_fade(UINT32 interval, void *param) { UINT8 delta = abs(fading_target - fading_source); fixed_t factor = FixedDiv(fading_duration - fading_timer, fading_duration); + if (fading_target < fading_source) internal_volume = max(min(internal_volume, fading_source - FixedMul(delta, factor)), fading_target); else if (fading_target > fading_source) internal_volume = min(max(internal_volume, fading_source + FixedMul(delta, factor)), fading_target); + Mix_VolumeMusic(get_real_volume(music_volume)); + return interval; } } @@ -763,14 +800,22 @@ musictype_t I_SongType(void) #endif if (!music) return MU_NONE; - else if (Mix_GetMusicType(music) == MUS_MID) - return MU_MID; - else if (Mix_GetMusicType(music) == MUS_MOD || Mix_GetMusicType(music) == MUS_MODPLUG) - return MU_MOD; - else if (Mix_GetMusicType(music) == MUS_MP3 || Mix_GetMusicType(music) == MUS_MP3_MAD) - return MU_MP3; - else - return (musictype_t)Mix_GetMusicType(music); + + const Mix_MusicType mustype = Mix_GetMusicType(music); + + switch (mustype) + { + case MUS_MID: + return MU_MID; + case MUS_MOD: + case MUS_MODPLUG: + return MU_MOD; + case MUS_MP3: + case MUS_MP3_MAD: + return MU_MP3; + default: + return (musictype_t)mustype; + } } boolean I_SongPlaying(void) @@ -799,6 +844,7 @@ boolean I_SetSongSpeed(float speed) { if (speed > 250.0f) speed = 250.0f; //limit speed up to 250x + #ifdef HAVE_LIBGME if (gme) { @@ -857,51 +903,63 @@ UINT32 I_GetSongLength(void) // reconstruct info->play_length, from GME source // we only want intro + 1 loop, not 2 length = info->length; + if (length <= 0) { length = info->intro_length + info->loop_length; // intro + 1 loop + if (length <= 0) length = 150 * 1000; // 2.5 minutes } } gme_free_info(info); + return max(length, 0); } else #endif #ifdef HAVE_OPENMPT if (openmpt_mhandle) + { return (UINT32)(openmpt_module_get_duration_seconds(openmpt_mhandle) * 1000.); + } else #endif if (!music || I_SongType() == MU_MOD || I_SongType() == MU_MID) + { return 0; + } else { // VERY IMPORTANT to set your LENGTHMS= in your song files, folks! // SDL mixer can't read music length itself. length = (UINT32)(song_length*1000); + if (!length) CONS_Debug(DBG_DETAILED, "Getting music length: music is missing LENGTHMS= tag. Needed for seeking.\n"); + return length; } } boolean I_SetSongLoopPoint(UINT32 looppoint) { - if (!music || I_SongType() == MU_GME || I_SongType() == MU_MOD || I_SongType() == MU_MID || !is_looping) + if (!music|| !is_looping) return false; - else - { - UINT32 length = I_GetSongLength(); - if (length > 0) - looppoint %= length; + const musictype_t mustype = I_SongType(); - loop_point = max((float)(looppoint / 1000.0L), 0); - return true; - } + if (mustype == MU_GME || mustype == MU_MOD || mustype == MU_MID) + return false; + + UINT32 length = I_GetSongLength(); + + if (length > 0) + looppoint %= length; + + loop_point = max((float)(looppoint / 1000.0L), 0); + return true; } UINT32 I_GetSongLoopPoint(void) @@ -927,14 +985,19 @@ UINT32 I_GetSongLoopPoint(void) else #endif if (!music || I_SongType() == MU_MOD || I_SongType() == MU_MID) + { return 0; + } else + { return (UINT32)(loop_point * 1000); + } } boolean I_SetSongPosition(UINT32 position) { UINT32 length; + #ifdef HAVE_LIBGME if (gme) { @@ -971,9 +1034,13 @@ boolean I_SetSongPosition(UINT32 position) else #endif if (!music || I_SongType() == MU_MID) + { return false; + } else if (I_SongType() == MU_MOD) + { return Mix_SetMusicPosition(position); // Goes by channels + } else { // Because SDL mixer can't identify song length, if you have @@ -981,11 +1048,13 @@ boolean I_SetSongPosition(UINT32 position) // music_bytes becomes inaccurate. length = I_GetSongLength(); // get it in MS + if (length) position = get_adjusted_position(position); Mix_RewindMusic(); // needed for mp3 - if(Mix_SetMusicPosition((float)(position/1000.0L)) == 0) + + if (Mix_SetMusicPosition((float)(position/1000.0L)) == 0) music_bytes = (UINT32)(position/1000.0L*44100.0L*4); //assume 44.1khz, 4-byte length (see I_GetSongPosition) else // NOTE: This block fires on incorrect song format, @@ -1025,6 +1094,7 @@ UINT32 I_GetSongPosition(void) } gme_free_info(info); + return max(position, 0); } else @@ -1038,12 +1108,16 @@ UINT32 I_GetSongPosition(void) else #endif if (!music || I_SongType() == MU_MID) + { return 0; + } else + { return (UINT32)(music_bytes/44100.0L*1000.0L/4); //assume 44.1khz // 4 = byte length for 16-bit samples (AUDIO_S16SYS), stereo (2-channel) // This is hardcoded in I_StartupSound. Other formats for factor: // 8M: 1 | 8S: 2 | 16M: 2 | 16S: 4 + } } void I_UpdateSongLagThreshold(void) @@ -1057,12 +1131,16 @@ void I_UpdateSongLagThreshold(void) boolean I_LoadSong(char *data, size_t len) { - const char *key1 = "LOOP"; - const char *key2 = "POINT="; - const char *key3 = "MS="; - const size_t key1len = strlen(key1); - const size_t key2len = strlen(key2); - const size_t key3len = strlen(key3); + static const char *key1 = "LOOP"; + static const char *key2 = "POINT="; + static const char *key3 = "MS="; + static const size_t key1len = sizeof("LOOP")-1; + static const size_t key2len = sizeof("POINT=")-1; + static const size_t key3len = sizeof("MS=")-1; + //const size_t key1len = strlen(key1); + //const size_t key2len = strlen(key2); + //const size_t key3len = strlen(key3); + char *p = data; SDL_RWops *rw; @@ -1099,6 +1177,7 @@ boolean I_LoadSong(char *data, size_t len) stream.next_out = inflatedData; zErr = inflateInit2(&stream, 32 + MAX_WBITS); + if (zErr == Z_OK) // We're good to go { zErr = inflate(&stream, Z_FINISH); @@ -1114,10 +1193,12 @@ boolean I_LoadSong(char *data, size_t len) } else CONS_Alert(CONS_ERROR, "Encountered %s when running inflate: %s\n", get_zlib_error(zErr), stream.msg); + (void)inflateEnd(&stream); } else // Hold up, zlib's got a problem CONS_Alert(CONS_ERROR, "Encountered %s when running inflateInit: %s\n", get_zlib_error(zErr), stream.msg); + Z_Free(inflatedData); // GME didn't open jack, but don't let that stop us from freeing this up return false; #else @@ -1146,6 +1227,7 @@ boolean I_LoadSong(char *data, size_t len) if (result == OPENMPT_PROBE_FILE_HEADER_RESULT_SUCCESS) // We only cared if it succeeded, continue on if not. { openmpt_mhandle = openmpt_module_create_from_memory2(data, len, NULL, NULL, NULL, NULL, NULL, NULL, NULL); + if (!openmpt_mhandle) // Failed to create module handle? Show error and return! { mod_err = openmpt_module_error_get_last(openmpt_mhandle); @@ -1160,10 +1242,12 @@ boolean I_LoadSong(char *data, size_t len) // Let's see if Mixer is able to load this. rw = SDL_RWFromMem(data, len); + if (rw != NULL) { music = Mix_LoadMUS_RW(rw, 1); } + if (!music) { CONS_Alert(CONS_ERROR, "Mix_LoadMUS_RW: %s\n", Mix_GetError()); @@ -1191,7 +1275,7 @@ boolean I_LoadSong(char *data, size_t len) else if (!strncmp(p, key3, key3len)) // is it LOOPMS=? { p += key3len; // skip MS= - loop_point = (float)(atoi(p) / 1000.0L); // LOOPMS works by real time, as miliseconds. + loop_point = (float)(atof(p) / 1000.0); // LOOPMS works by real time, as miliseconds. // Everything that uses LOOPMS will work perfectly with SDL_Mixer. } } @@ -1201,6 +1285,7 @@ boolean I_LoadSong(char *data, size_t len) else // continue searching p++; } + return true; } @@ -1243,6 +1328,7 @@ boolean I_PlaySong(boolean looping) gme_start_track(gme, 0); current_track = 0; Mix_HookMusic(mix_gme, gme); + return true; } else @@ -1282,15 +1368,17 @@ boolean I_PlaySong(boolean looping) if (!music) return false; - if (fpclassify(song_length) == FP_ZERO && (I_SongType() == MU_OGG || I_SongType() == MU_MP3 || I_SongType() == MU_FLAC)) + const musictype_t mustype = I_SongType(); + + if (fpclassify(song_length) == FP_ZERO && (mustype == MU_OGG || mustype == MU_MP3 || mustype == MU_FLAC)) CONS_Debug(DBG_DETAILED, "This song is missing a LENGTHMS= tag! Required to make seeking work properly.\n"); - if (I_SongType() != MU_MOD && I_SongType() != MU_MID && Mix_PlayMusic(music, 0) == -1) + if (mustype != MU_MOD && mustype != MU_MID && Mix_PlayMusic(music, 0) == -1) { CONS_Alert(CONS_ERROR, "Mix_PlayMusic: %s\n", Mix_GetError()); return false; } - else if ((I_SongType() == MU_MOD || I_SongType() == MU_MID) && Mix_PlayMusic(music, looping ? -1 : 0) == -1) // if MOD, loop forever + else if ((mustype == MU_MOD || mustype == MU_MID) && Mix_PlayMusic(music, looping ? -1 : 0) == -1) // if MOD, loop forever { CONS_Alert(CONS_ERROR, "Mix_PlayMusic: %s\n", Mix_GetError()); return false; @@ -1300,10 +1388,10 @@ boolean I_PlaySong(boolean looping) I_SetMusicVolume(music_volume); - if (I_SongType() != MU_MOD && I_SongType() != MU_MID) + if (mustype != MU_MOD && mustype != MU_MID) Mix_HookMusicFinished(music_loop); // don't bother counting if MOD - if(I_SongType() != MU_MOD && I_SongType() != MU_MID && !Mix_RegisterEffect(MIX_CHANNEL_POST, count_music_bytes, NULL, NULL)) + if (mustype != MU_MOD && mustype != MU_MID && !Mix_RegisterEffect(MIX_CHANNEL_POST, count_music_bytes, NULL, NULL)) CONS_Alert(CONS_WARNING, "Error registering SDL music position counter: %s\n", Mix_GetError()); return true; @@ -1339,10 +1427,12 @@ void I_StopSong(void) void I_PauseSong(void) { - if(I_SongType() == MU_MID) // really, SDL Mixer? why can't you pause MIDI??? + const musictype_t mustype = I_SongType(); + + if (mustype == MU_MID) // really, SDL Mixer? why can't you pause MIDI??? return; - if(I_SongType() != MU_GME && I_SongType() != MU_MOD && I_SongType() != MU_MID) + if (mustype != MU_GME && mustype != MU_MOD && mustype != MU_MID) Mix_UnregisterEffect(MIX_CHANNEL_POST, count_music_bytes); Mix_PauseMusic(); @@ -1351,15 +1441,17 @@ void I_PauseSong(void) void I_ResumeSong(void) { - if (I_SongType() == MU_MID) + const musictype_t mustype = I_SongType(); + + if (mustype == MU_MID) return; - if (I_SongType() != MU_GME && I_SongType() != MU_MOD && I_SongType() != MU_MID) + if (mustype != MU_GME && mustype != MU_MOD && mustype != MU_MID) { - while(Mix_UnregisterEffect(MIX_CHANNEL_POST, count_music_bytes) != 0) { } + while (Mix_UnregisterEffect(MIX_CHANNEL_POST, count_music_bytes) != 0) { } // HACK: fixes issue of multiple effect callbacks being registered - if(music && I_SongType() != MU_MOD && I_SongType() != MU_MID && !Mix_RegisterEffect(MIX_CHANNEL_POST, count_music_bytes, NULL, NULL)) + if (music && mustype != MU_MOD && mustype != MU_MID && !Mix_RegisterEffect(MIX_CHANNEL_POST, count_music_bytes, NULL, NULL)) CONS_Alert(CONS_WARNING, "Error registering SDL music position counter: %s\n", Mix_GetError()); } @@ -1392,20 +1484,24 @@ boolean I_SetSongTrack(INT32 track) { if (current_track == track) return false; + SDL_LockAudio(); if (track >= 0 && track < gme_track_count(gme)-1) { gme_err_t gme_e = gme_start_track(gme, track); + if (gme_e != NULL) { CONS_Alert(CONS_ERROR, "GME error: %s\n", gme_e); return false; } + current_track = track; SDL_UnlockAudio(); return true; } SDL_UnlockAudio(); + return false; } else @@ -1415,6 +1511,7 @@ boolean I_SetSongTrack(INT32 track) { if (current_subsong == track) return false; + SDL_LockAudio(); if (track >= 0 && track < openmpt_module_get_num_subsongs(openmpt_mhandle)) { @@ -1428,8 +1525,10 @@ boolean I_SetSongTrack(INT32 track) return false; } #endif + if (I_SongType() == MU_MOD) return !Mix_SetMusicPosition(track); + (void)track; return false; } @@ -1441,8 +1540,10 @@ boolean I_SetSongTrack(INT32 track) void I_SetInternalMusicVolume(UINT8 volume) { internal_volume = volume; + if (!I_SongPlaying()) return; + Mix_VolumeMusic(get_real_volume(music_volume)); } @@ -1450,6 +1551,7 @@ void I_StopFadingSong(void) { if (fading_id) SDL_RemoveTimer(fading_id); + is_fading = false; fading_source = fading_target = fading_timer = fading_duration = fading_id = 0; } @@ -1466,8 +1568,10 @@ boolean I_FadeSongFromVolume(UINT8 target_volume, UINT8 source_volume, UINT32 ms if (!ms && volume_delta) { I_SetInternalMusicVolume(target_volume); + if (callback) (*callback)(); + return true; } @@ -1475,20 +1579,28 @@ boolean I_FadeSongFromVolume(UINT8 target_volume, UINT8 source_volume, UINT32 ms { if (callback) (*callback)(); + return true; } // Round MS to nearest 10 // If n - lower > higher - n, then round up - ms = (ms - ((ms / 10) * 10) > (((ms / 10) * 10) + 10) - ms) ? - (((ms / 10) * 10) + 10) // higher - : ((ms / 10) * 10); // lower + //ms = (ms - ((ms / 10) * 10) > (((ms / 10) * 10) + 10) - ms) ? + // (((ms / 10) * 10) + 10) // higher + // : ((ms / 10) * 10); // lower + + const int lower = (ms / 10) * 10; + const int upper = lower + 10; + ms = (ms - lower > upper - ms) ? upper : lower; if (!ms) + { I_SetInternalMusicVolume(target_volume); + } else if (source_volume != target_volume) { fading_id = SDL_AddTimer(10, music_fade, NULL); + if (fading_id) { is_fading = true; @@ -1519,7 +1631,7 @@ boolean I_FadeInPlaySong(UINT32 ms, boolean looping) { if (I_PlaySong(looping)) return I_FadeSongFromVolume(100, 0, ms, NULL); - else - return false; + + return false; } #endif diff --git a/src/st_stuff.c b/src/st_stuff.c index f5634423c..a4b3d0465 100644 --- a/src/st_stuff.c +++ b/src/st_stuff.c @@ -219,10 +219,6 @@ void ST_UnloadGraphics(void) void ST_LoadGraphics(void) { - // SRB2 border patch - //st_borderpatchnum = W_GetNumForName("GFZFLR01"); - //scr_borderpatch = W_CacheLumpNum(st_borderpatchnum, PU_HUDGFX); - // the original Doom uses 'STF' as base name for all face graphics // Graue 04-08-2004: face/name graphics are now indexed by skins // but load them in R_AddSkins, that gets called @@ -794,7 +790,7 @@ void ST_Drawer(void) LUA_HUD_DrawList(luahuddrawlist_game[i]); // draw Midnight Channel's overlay ontop - if (mapheaderinfo[gamemap-1]->typeoflevel & TOL_TV) // Very specific Midnight Channel stuff. + if (mapheaderinfo[gamemap-1]->typeoflevel & TOL_TV) // Very specific Midnight Channel stuff. ST_MayonakaStatic(); } @@ -802,7 +798,7 @@ void ST_Drawer(void) if (timeinmap < 15) { if (timeinmap <= 5) - V_DrawFill(0,0,BASEVIDWIDTH,BASEVIDHEIGHT,120); // Pure white on first few frames, to hide SRB2's awful level load artifacts + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 120); // Pure white on first few frames, to hide SRB2's awful level load artifacts else V_DrawFadeScreen(120, 15-timeinmap); // Then gradually fade out from there } diff --git a/src/v_video.c b/src/v_video.c index ab3d05b91..9805e910c 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -641,8 +641,8 @@ void VID_BlitLinearScreen(const UINT8 *restrict srcptr, UINT8 *restrict destptr, } } -static UINT8 hudplusalpha[11] = { 10, 8, 6, 4, 2, 0, 0, 0, 0, 0, 0}; -static UINT8 hudminusalpha[11] = { 10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5}; +static const UINT8 hudplusalpha[11] = { 10, 8, 6, 4, 2, 0, 0, 0, 0, 0, 0}; +static const UINT8 hudminusalpha[11] = { 10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5}; UINT8 hudtrans = 0; static const UINT8 *v_colormap = NULL; @@ -1739,59 +1739,69 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) void V_DrawVhsEffect(boolean rewind) { - static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; + static fixed_t upbary = 100, downbary = 150; + + UINT8 barsize, updistort, downdistort; - UINT8 *buf = vid.screens[0], *tmp = vid.screens[4]; UINT16 y; - UINT32 x, pos = 0; + UINT32 x, pos; - UINT8 *normalmapstart = ((UINT8 *)transtables + (8<>1; + barsize = vid.dup << 5; + updistort = vid.dup << (rewind ? 5 : 3); + downdistort = updistort >> 1; if (rewind) V_DrawVhsEffect(false); // experimentation - upbary -= renderdeltatics * (vid.dup * (rewind ? 3 : 1.8f)); - downbary += renderdeltatics * (vid.dup * (rewind ? 2 : 1)); + upbary -= FixedMul(vid.dup * (rewind ? 3 : 1.8f), renderdeltatics); + downbary += FixedMul(vid.dup * (rewind ? 2 : 1), renderdeltatics); - if (upbary < -barsize*FRACUNIT) - upbary = vid.height< vid.height<>FRACBITS, dby = downbary>>FRACBITS; + if (downbary > vid.height) + downbary = -barsize; #ifdef HWRENDER if (rendermode == render_opengl) { - HWR_RenderVhsEffect(uby, dby, updistort, downdistort, barsize); + HWR_RenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); return; } #endif + buf = vid.screens[0]; + tmp = vid.screens[4]; + + normalmapstart = ((UINT8 *)transtables + (8<= uby && y < uby+barsize) + if (y >= upbary && y < upbary+barsize) { thismapstart -= (2<= dby && y < dby+barsize) + if (y >= downbary && y < downbary+barsize) { thismapstart -= (2<> V_CHARCOLORSHIFT); + if (!colorflags || colorflags > 15) // INT32 is signed, but V_CHARCOLORMASK is a very restrictive mask. return NULL; + return (purplemap+((colorflags-1)<<8)); #endif } @@ -2000,6 +2012,7 @@ char *V_WordWrap(INT32 x, INT32 w, INT32 option, const char *string) for (i = 0; i < slen; ++i) { c = newstring[i]; + if ((UINT8)c >= 0x80 && (UINT8)c <= 0x8F) //color parsing! -Inuyasha 2.16.09 continue; @@ -3094,6 +3107,9 @@ INT32 V_SubStringWidth(const char *string, INT32 length, INT32 option) INT32 spacewidth = 4, charwidth = 0; ssize_t i; + if (!string) + return 0; + if (length < 0) length = strlen(string); @@ -3136,6 +3152,9 @@ INT32 V_SmallSubStringWidth(const char *string, INT32 length, INT32 option) INT32 spacewidth = 2, charwidth = 0; ssize_t i; + if (!string) + return 0; + if (length < 0) length = strlen(string); @@ -3176,9 +3195,14 @@ INT32 V_ThinSubStringWidth(const char *string, INT32 length, INT32 option) { INT32 c, w = 0; INT32 spacewidth = 2, charwidth = 0; - boolean lowercase = (option & V_ALLOWLOWERCASE); + boolean lowercase; ssize_t i; + if (!string) + return 0; + + lowercase = (option & V_ALLOWLOWERCASE); + if (length < 0) length = strlen(string); @@ -3233,6 +3257,9 @@ INT32 V_SubStringLengthToFit(const char *string, INT32 width, INT32 option) INT32 spacewidth = 4, charwidth = 0; INT32 i; + if (!string) + return 0; + switch (option & V_SPACINGMASK) { case V_MONOSPACE: @@ -3814,11 +3841,15 @@ void V_Init(void) for (i = 0; i < NUMSCREENS; i++) { + if (vid.screens[i]) + { #if defined(__SSE__) - aligned_free(vid.screens[i]); + aligned_free(vid.screens[i]); #else - free(vid.screens[i]); + free(vid.screens[i]); #endif + } + vid.screens[i] = NULL; } diff --git a/src/w_wad.c b/src/w_wad.c index 1cfb3f616..756dee4a6 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -259,9 +259,12 @@ static inline void W_LoadDehackedLumpsPK3(UINT16 wadnum) size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name char *name = malloc(length + 1); + if (!name) + I_Error("W_LoadDehackedLumpsPK3: Out of memory!\n"); + sprintf(name, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); name[length] = '\0'; - CONS_Printf(M_GetText("Loading SOC from %s\n"), name); + CONS_Printf("Loading SOC from %s\n", name); DEH_LoadDehackedLumpPwad(wadnum, posStart); free(name); } @@ -292,6 +295,9 @@ static inline void W_LoadDehackedLumps(UINT16 wadnum) size_t length = len + 1 + strlen(lump_p->fullname); // length of file name, '|', and lump name char *name = malloc(length + 1); + if (!name) + I_Error("W_LoadDehackedLumps: Out of memory!\n"); + sprintf(name, "%s|%s", wadfiles[wadnum]->filename, lump_p->fullname); name[length] = '\0'; diff --git a/src/win32/Sourcefile b/src/win32/Sourcefile new file mode 100644 index 000000000..0122059d8 --- /dev/null +++ b/src/win32/Sourcefile @@ -0,0 +1 @@ +win_dbg.c diff --git a/src/win32/win_dbg.c b/src/win32/win_dbg.c index 290227b09..a5d1adc3f 100644 --- a/src/win32/win_dbg.c +++ b/src/win32/win_dbg.c @@ -118,7 +118,7 @@ static VOID FPrintf(HANDLE fileHandle, LPCSTR lpFmt, ...) DWORD bytesWritten; va_start(arglist, lpFmt); - vsprintf(str, lpFmt, arglist); + vsnprintf(str, 1999, lpFmt, arglist); va_end(arglist); WriteFile(fileHandle, str, (DWORD)strlen(str), &bytesWritten, NULL); diff --git a/src/y_inter.c b/src/y_inter.c index c1bdafd32..9abbccbd8 100644 --- a/src/y_inter.c +++ b/src/y_inter.c @@ -552,18 +552,8 @@ void Y_Ticker(void) intertic++; - // multiplayer uses timer (based on cv_inttime) - if (timer) - { - if (!--timer) - { - Y_EndIntermission(); - Y_FollowIntermission(); - return; - } - } - // single player is hardcoded to go away after awhile - else if (intertic == endtic) + if ((timer && !--timer) + || (intertic == endtic)) { Y_EndIntermission(); Y_FollowIntermission();