From 524168b20b3a32d26cc9ca38f982940eda1a468e Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 2 Oct 2025 17:15:14 +0200 Subject: [PATCH 001/116] experiment: remove opengl adjusted segs in theory this should improve levelload times and reduce memory usage? gotta see if it really does, visually so far there seems to be no difference at all --- src/hardware/hw_bsp.c | 103 ---------------------------------- src/hardware/hw_main.cpp | 116 ++++++++------------------------------- src/p_setup.c | 11 ++++ src/r_defs.h | 12 ++-- 4 files changed, 43 insertions(+), 199 deletions(-) diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c index 8cad91168..5889dcb44 100644 --- a/src/hardware/hw_bsp.c +++ b/src/hardware/hw_bsp.c @@ -80,14 +80,6 @@ static poly_t *HWR_AllocPoly(INT32 numpts) return p; } -static polyvertex_t *HWR_AllocVertex(void) -{ - polyvertex_t *p; - size_t size = sizeof(polyvertex_t); - p = Z_Malloc(size, PU_HWRPLANE, NULL); - return p; -} - /// \todo polygons should be freed in reverse order for efficiency, /// for now don't free because it doesn't free in reverse order static void HWR_FreePoly(poly_t *poly) @@ -855,100 +847,6 @@ static INT32 SolveTProblem(void) return numsplitpoly; } -#define NEARDIST (0.75f) -#define MYMAX (10000000000000.0f) - -/* Adjust true segs (from the segs lump) to be exactely the same as - * plane polygone segs - * This also convert fixed_t point of segs in float (in moste case - * it share the same vertice - */ -static void AdjustSegs(void) -{ - size_t i, count; - INT32 j; - seg_t *lseg; - poly_t *p; - INT32 v1found = 0, v2found = 0; - float nearv1, nearv2; - - for (i = 0; i < numsubsectors; i++) - { - count = subsectors[i].numlines; - lseg = &segs[subsectors[i].firstline]; - p = extrasubsectors[i].planepoly; - - if (!p) - continue; - - for (; count--; lseg++) - { - float distv1,distv2,tmp; - nearv1 = nearv2 = MYMAX; - - // Don't touch polyobject segs. We'll compensate - // for this when we go about drawing them. - if (lseg->polyseg) - continue; - - for (j = 0; j < p->numpts; j++) - { - distv1 = p->pts[j].x - FIXED_TO_FLOAT(lseg->v1->x); - tmp = p->pts[j].y - FIXED_TO_FLOAT(lseg->v1->y); - distv1 = distv1*distv1+tmp*tmp; - - if (distv1 <= nearv1) - { - v1found = j; - nearv1 = distv1; - } - - // the same with v2 - distv2 = p->pts[j].x - FIXED_TO_FLOAT(lseg->v2->x); - tmp = p->pts[j].y - FIXED_TO_FLOAT(lseg->v2->y); - distv2 = distv2*distv2+tmp*tmp; - - if (distv2 <= nearv2) - { - v2found = j; - nearv2 = distv2; - } - } - - if (nearv1 <= NEARDIST*NEARDIST) - // share vertice with segs - lseg->pv1 = &(p->pts[v1found]); - else - { - // BP: here we can do better, using PointInSeg and compute - // the right point position also split a polygone side to - // solve a T-intersection, but too mush work - - // convert fixed vertex to float vertex - polyvertex_t *pv = HWR_AllocVertex(); - pv->x = FIXED_TO_FLOAT(lseg->v1->x); - pv->y = FIXED_TO_FLOAT(lseg->v1->y); - lseg->pv1 = pv; - } - - if (nearv2 <= NEARDIST*NEARDIST) - lseg->pv2 = &(p->pts[v2found]); - else - { - polyvertex_t *pv = HWR_AllocVertex(); - pv->x = FIXED_TO_FLOAT(lseg->v2->x); - pv->y = FIXED_TO_FLOAT(lseg->v2->y); - lseg->pv2 = pv; - } - - lseg->pv1->x2 = FloatToFixed(lseg->pv1->x); - lseg->pv1->y2 = FloatToFixed(lseg->pv1->y); - lseg->pv2->x2 = FloatToFixed(lseg->pv2->x); - lseg->pv2->y2 = FloatToFixed(lseg->pv2->y); - } - } -} - // call this routine after the BSP of a Doom wad file is loaded, // and it will generate all the convex polys for the hardware renderer @@ -1017,7 +915,6 @@ void HWR_CreatePlanePolygons(INT32 bspnum) #else SolveTProblem(); #endif - AdjustSegs(); #ifdef DEBUG_HWBSP //debug debug.. diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index c88b075a1..dc8cb55c0 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -741,27 +741,11 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool P_ClosestPointOnLine(viewx, viewy, ld, &v); dist = FixedToFloat(R_PointToDist(v.x, v.y)); - if (line->pv1) - { - x1 = line->pv1->x; - y1 = line->pv1->y; - } - else - { - x1 = FixedToFloat(line->v1->x); - y1 = FixedToFloat(line->v1->y); - } + x1 = (line->fv1.x); + y1 = (line->fv1.y); - if (line->pv2) - { - xd = line->pv2->x - x1; - yd = line->pv2->y - y1; - } - else - { - xd = FixedToFloat(line->v2->x) - x1; - yd = FixedToFloat(line->v2->y) - y1; - } + xd = (line->fv2.x) - x1; + yd = (line->fv2.y) - y1; // Based on the seg length and the distance from the line, split horizon into multiple poly sets to reduce distortion dist = sqrtf((xd*xd) + (yd*yd)) / dist / 16.0f; @@ -825,11 +809,11 @@ static void HWR_DrawSegsSplats(FSurfaceInfo * pSurf) M_ClearBox(segbbox); M_AddToBox(segbbox, - FloatToFixed(gl_curline->pv1->x), - FloatToFixed(gl_curline->pv1->y)); + FloatToFixed(gl_curline->fv1.x), + FloatToFixed(gl_curline->fv1.y)); M_AddToBox(segbbox, - FloatToFixed(gl_curline->pv2->x), - FloatToFixed(gl_curline->pv2->y)); + FloatToFixed(gl_curline->fv2.x), + FloatToFixed(gl_curline->fv2.y)); splat = (wallsplat_t *)gl_curline->linedef->splats; for (; splat; splat = splat->next) @@ -1324,35 +1308,15 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom const boolean noencore = (gl_linedef->flags & ML_TFERLINE); - if (LIKELY(gl_curline->pv1)) - { - vs.x = gl_curline->pv1->x; - vs.y = gl_curline->pv1->y; - v1x = gl_curline->pv1->x2; - v1y = gl_curline->pv1->y2; - } - else - { - vs.x = FixedToFloat(gl_curline->v1->x); - vs.y = FixedToFloat(gl_curline->v1->y); - v1x = gl_curline->v1->x; - v1y = gl_curline->v1->y; - } + vs.x = (gl_curline->fv1.x); + vs.y = (gl_curline->fv1.y); + v1x = gl_curline->v1->x; + v1y = gl_curline->v1->y; - if (LIKELY(gl_curline->pv2)) - { - ve.x = gl_curline->pv2->x; - ve.y = gl_curline->pv2->y; - v2x = gl_curline->pv2->x2; - v2y = gl_curline->pv2->y2; - } - else - { - ve.x = FixedToFloat(gl_curline->v2->x); - ve.y = FixedToFloat(gl_curline->v2->y); - v2x = gl_curline->v2->x; - v2y = gl_curline->v2->y; - } + ve.x = (gl_curline->fv2.x); + ve.y = (gl_curline->fv2.y); + v2x = gl_curline->v2->x; + v2y = gl_curline->v2->y; #define SLOPEPARAMS(slope, end1, end2, normalheight) \ end1 = P_GetZAt(slope, v1x, v1y, normalheight); \ @@ -2203,27 +2167,11 @@ static boolean CheckClip(sector_t * afrontsector, sector_t * abacksector) { fixed_t v1x, v1y, v2x, v2y; // the seg's vertexes as fixed_t - if (LIKELY(gl_curline->pv1)) - { - v1x = gl_curline->pv1->x2; - v1y = gl_curline->pv1->y2; - } - else - { - v1x = gl_curline->v1->x; - v1y = gl_curline->v1->y; - } + v1x = gl_curline->v1->x; + v1y = gl_curline->v1->y; - if (LIKELY(gl_curline->pv2)) - { - v2x = gl_curline->pv2->x2; - v2y = gl_curline->pv2->y2; - } - else - { - v2x = gl_curline->v2->x; - v2y = gl_curline->v2->y; - } + v2x = gl_curline->v2->x; + v2y = gl_curline->v2->y; #define SLOPEPARAMS(slope, end1, end2, normalheight) \ end1 = P_GetZAt(slope, v1x, v1y, normalheight); \ @@ -2428,27 +2376,11 @@ static void HWR_AddLine(seg_t *line) gl_curline = line; - if (LIKELY(gl_curline->pv1)) - { - v1x = gl_curline->pv1->x2; - v1y = gl_curline->pv1->y2; - } - else - { - v1x = gl_curline->v1->x; - v1y = gl_curline->v1->y; - } + v1x = gl_curline->v1->x; + v1y = gl_curline->v1->y; - if (LIKELY(gl_curline->pv2)) - { - v2x = gl_curline->pv2->x2; - v2y = gl_curline->pv2->y2; - } - else - { - v2x = gl_curline->v2->x; - v2y = gl_curline->v2->y; - } + v2x = gl_curline->v2->x; + v2y = gl_curline->v2->y; // OPTIMIZE: quickly reject orthogonal back sides. angle1 = R_PointToAngle64(v1x, v1y); diff --git a/src/p_setup.c b/src/p_setup.c index 2ccbd1821..afdda1ded 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -544,7 +544,18 @@ static void P_LoadSegs(UINT8 *data) { li->v1 = &vertexes[SHORT(ml->v1)]; li->v2 = &vertexes[SHORT(ml->v2)]; +#ifdef HWRENDER + if (rendermode == render_opengl) + { + li->fv1.x = FixedToFloat(li->v1->x); + li->fv1.y = FixedToFloat(li->v1->y); + //li->fv1.z = FixedToFloat(li->v1->z); // z is unused in gl + li->fv2.x = FixedToFloat(li->v2->x); + li->fv2.y = FixedToFloat(li->v2->y); + //li->fv2.z = FixedToFloat(li->v2->z); + } +#endif li->length = P_SegLength(li); li->angle = (SHORT(ml->angle))<offset = (SHORT(ml->offset))< Date: Thu, 2 Oct 2025 18:37:05 +0200 Subject: [PATCH 002/116] a thousand curses upon you polyobjects! --- src/hardware/hw_main.cpp | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index dc8cb55c0..1c7234d2c 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -729,6 +729,9 @@ static void HWR_RenderPlane(subsector_t *subsector, extrasubsector_t *xsub, bool for (i = 0; i < subsector->numlines; i++, line++) { + if (line->polyseg) + continue; + line_t* ld = line->linedef; // this check sucks and is a hotspot lel @@ -1308,16 +1311,26 @@ void HWR_ProcessSeg(void) // Sort of like GLWall::Process in GZDoom const boolean noencore = (gl_linedef->flags & ML_TFERLINE); - vs.x = (gl_curline->fv1.x); - vs.y = (gl_curline->fv1.y); v1x = gl_curline->v1->x; v1y = gl_curline->v1->y; - - ve.x = (gl_curline->fv2.x); - ve.y = (gl_curline->fv2.y); v2x = gl_curline->v2->x; v2y = gl_curline->v2->y; + if (gl_curline->polyseg) + { + vs.x = FixedToFloat(v1x); + vs.y = FixedToFloat(v1y); + ve.x = FixedToFloat(v2x); + ve.y = FixedToFloat(v2y); + } + else + { + vs.x = gl_curline->fv1.x; + vs.y = gl_curline->fv1.y; + ve.x = gl_curline->fv2.x; + ve.y = gl_curline->fv2.y; + } + #define SLOPEPARAMS(slope, end1, end2, normalheight) \ end1 = P_GetZAt(slope, v1x, v1y, normalheight); \ end2 = P_GetZAt(slope, v2x, v2y, normalheight); -- 2.54.0 From 93d0106c28bcb9d2becabd9fd677ca16f54f6a47 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 10:38:22 +0200 Subject: [PATCH 003/116] remove erronous ";" --- src/d_netcmd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 002195ec1..a99ece58a 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -4472,7 +4472,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. -- 2.54.0 From ab27090ecf985c461a933d68a40447fa2ab4900e Mon Sep 17 00:00:00 2001 From: toaster Date: Tue, 21 Oct 2025 20:48:22 +0100 Subject: [PATCH 004/116] Don't send a netxcmd when using addfile outside of netgame Was supposed to be happening already, but `multiplayer` is a useless variable... --- src/d_netcmd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index a99ece58a..65dd1d4cf 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -4429,7 +4429,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; -- 2.54.0 From a94740f5e9b9cb9cb4fd91ad668c4d04c8e5afa6 Mon Sep 17 00:00:00 2001 From: AJ Martinez Date: Sun, 26 Feb 2023 04:29:13 -0700 Subject: [PATCH 005/116] Fix unsteady camera movement in demos --- src/p_user.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) 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)) -- 2.54.0 From 77f4d4ef3bd55528043cfcc52b730bc023b03364 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 13:42:33 +0200 Subject: [PATCH 006/116] fix replays occasionally crashing when stopping due to R_ReInitColormaps our extra_colormaps pointer may be freed so ensure it only gets called after gamestate has been set to GS_NULL so we dont risk doing this mid renderframe fixes crashes in software and palette render mode --- src/g_demo.c | 11 ++++++----- src/r_main.cpp | 3 ++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/g_demo.c b/src/g_demo.c index 6b2c8f1c9..de8523ae9 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -3411,11 +3411,6 @@ 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) @@ -3427,6 +3422,12 @@ void G_StopDemo(void) wipegamestate = GS_NULL; SV_StopServer(); SV_ResetServer(); + + if (gamestate == GS_LEVEL && rendermode != render_none) + { + V_SetPaletteLump("PLAYPAL"); // Reset the palette + R_ReInitColormaps(0, LUMPERROR); + } } // Stops timing a demo. diff --git a/src/r_main.cpp b/src/r_main.cpp index a340ef29c..5313357d6 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -943,9 +943,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; -- 2.54.0 From 5289027272dce5cbd2179da4427a1feeb63476f1 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 15:32:38 +0200 Subject: [PATCH 007/116] uninline ctf resynch stuff this wont ever be used and just makes lto and others complain occasionally (maybe frenmod uses ctf? forgor) --- src/d_clisrv.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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; -- 2.54.0 From f74980027613ade10f50fa4c4dfa9ad81e9fde28 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 15:33:09 +0200 Subject: [PATCH 008/116] fix playersetup skin speen reading out of bounds reported by ubsan --- src/m_menu.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/m_menu.c b/src/m_menu.c index 6822dd499..e9915cb9c 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -8279,12 +8279,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); -- 2.54.0 From e5bae89d0f716de6f1e52bcafb2d855f26179818 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 15:34:24 +0200 Subject: [PATCH 009/116] fix namescrollbuf and mapmusic.name copies ensure those are properly null terminated as reported by ubsan --- src/m_menu.c | 8 ++++++-- src/p_spec.c | 3 +-- src/w_wad.c | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/m_menu.c b/src/m_menu.c index e9915cb9c..a7be33c42 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -7179,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... } diff --git a/src/p_spec.c b/src/p_spec.c index cf2ca3e3e..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)) diff --git a/src/w_wad.c b/src/w_wad.c index 1cfb3f616..95992fb42 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -261,7 +261,7 @@ static inline void W_LoadDehackedLumpsPK3(UINT16 wadnum) 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); } -- 2.54.0 From 5f394cd938a89685ad1dfa20404363b626a7b101 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 16:02:24 +0200 Subject: [PATCH 010/116] handle more memory allocation failure cases reported with -Wformat-overflow --- src/command.c | 2 ++ src/d_netcmd.c | 23 ++++++++++++++++++----- src/dedicated/i_system.c | 2 +- src/g_game.c | 4 ++++ src/lua_script.c | 4 ++++ src/sdl/i_system.cpp | 9 ++++++++- src/w_wad.c | 6 ++++++ 7 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/command.c b/src/command.c index 47bd521b0..463325e60 100644 --- a/src/command.c +++ b/src/command.c @@ -938,6 +938,8 @@ static void COM_Find_f(void) } help = COM_Argv(1); + if (!help) + return; helplen = strlen(help); CONS_Printf("\x82""Variables:\n"); matchesany = false; diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 65dd1d4cf..d62be9daa 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -2596,14 +2596,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)); @@ -4214,23 +4218,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); diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index 865ae4584..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]; diff --git a/src/g_game.c b/src/g_game.c index 5c984ad87..796c154d5 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -4061,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/lua_script.c b/src/lua_script.c index 723624ee2..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'; } diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 2663887d6..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); diff --git a/src/w_wad.c b/src/w_wad.c index 95992fb42..756dee4a6 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -259,6 +259,9 @@ 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("Loading SOC from %s\n", 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'; -- 2.54.0 From 41407538d4cbb4f3266db9edb6b3022a54724402 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 22 Oct 2025 22:52:06 +0200 Subject: [PATCH 011/116] cleanup + optimizations mixer_sound thx indev for the better ms rounding code <3 --- src/sdl/mixer_sound.c | 356 +++++++++++++++++++++++++++--------------- 1 file changed, 234 insertions(+), 122 deletions(-) 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 -- 2.54.0 From ed16c4fd9ffd3031547871d5709c7da53a69e2c8 Mon Sep 17 00:00:00 2001 From: toaster Date: Thu, 13 Oct 2022 13:12:07 +0100 Subject: [PATCH 012/116] Simplify intermission timer code - We had two ways of ending the intermission, but only one would actually be used, and it resulted in code duplication. - Combine the two ways. - Disable the reached-but-didn't-do-anything-before-now code path for setting endtic. --- src/y_inter.c | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) 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(); -- 2.54.0 From f751161693e3b067eae7b9adfb1ddbe5e9cbf6b2 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 23 Oct 2025 20:37:23 +0200 Subject: [PATCH 013/116] fix CECHO text being overwritten with nothing strlcat not strlcpy --- src/command.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/command.c b/src/command.c index 463325e60..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); } -- 2.54.0 From c07502bf5a26848fa520acda86fb538b7cd09b76 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 23 Oct 2025 20:51:11 +0200 Subject: [PATCH 014/116] use strl instead of strn stuff to copy cecho text ALOT safer than whatever this did before --- src/hu_stuff.c | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/hu_stuff.c b/src/hu_stuff.c index fa7060dff..3a01aedc0 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -2845,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) -- 2.54.0 From 54e7ad571e2687c01209d465a15e13694c7362b2 Mon Sep 17 00:00:00 2001 From: Indev Date: Thu, 23 Oct 2025 22:00:46 +0300 Subject: [PATCH 015/116] Check if mobj is spawned from local addon in most of lua_baselib functions related to mobjs --- src/lua_baselib.c | 54 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 47 insertions(+), 7 deletions(-) diff --git a/src/lua_baselib.c b/src/lua_baselib.c index c6b87193c..3715fefdb 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -365,6 +365,32 @@ static int lib_pLookForPlayers(lua_State *L) return 1; } +static boolean checkLocalAddon(lua_State *L) +{ + char buf[128]; + lua_Debug ar; + lua_getstack(L, 1, &ar); + lua_getinfo(L, "S", &ar); + + strncpy(buf, ar.source, sizeof(buf)-1); + buf[127] = 0; + + char *p; + + if ((p = strstr(buf, "|")) != NULL) + *p = '\0'; + + UINT16 i; + + for (i = 0; i < numwadfiles; ++i) + { + if (strcmp(wadfiles[i]->filename, buf+1) == 0) // buf+1 - skip "@" + break; + } + + return (i < numwadfiles) && !wadfiles[i]->important; +} + // P_MOBJ //////////// @@ -377,7 +403,9 @@ static int lib_pSpawnMobj(lua_State *L) NOHUD if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnMobj(x, y, z, type), META_MOBJ); + mobj_t *th = P_SpawnMobj(x, y, z, type); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -403,7 +431,9 @@ static int lib_pSpawnMissile(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnMissile(source, dest, type), META_MOBJ); + mobj_t *th = P_SpawnMissile(source, dest, type); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -420,7 +450,9 @@ static int lib_pSpawnXYZMissile(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnXYZMissile(source, dest, type, x, y, z), META_MOBJ); + mobj_t *th = P_SpawnXYZMissile(source, dest, type, x, y, z); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -439,7 +471,9 @@ static int lib_pSpawnPointMissile(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnPointMissile(source, xa, ya, za, type, x, y, z), META_MOBJ); + mobj_t *th = P_SpawnPointMissile(source, xa, ya, za, type, x, y, z); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -456,7 +490,9 @@ static int lib_pSpawnAlteredDirectionMissile(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnAlteredDirectionMissile(source, type, x, y, z, shiftingAngle), META_MOBJ); + mobj_t *th = P_SpawnAlteredDirectionMissile(source, type, x, y, z, shiftingAngle); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -485,7 +521,9 @@ static int lib_pSPMAngle(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SPMAngle(source, type, angle, allowaim, flags2), META_MOBJ); + mobj_t *th = P_SPMAngle(source, type, angle, allowaim, flags2); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -499,7 +537,9 @@ static int lib_pSpawnPlayerMissile(lua_State *L) return LUA_ErrInvalid(L, "mobj_t"); if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); - LUA_PushUserdata(L, P_SpawnPlayerMissile(source, type, flags2), META_MOBJ); + mobj_t *th = P_SpawnPlayerMissile(source, type, flags2); + th->islocal = checkLocalAddon(L); + LUA_PushUserdata(L, th, META_MOBJ); return 1; } -- 2.54.0 From aa06459c09550ac7fb9a92ef3ba11e35f26c809e Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 23 Oct 2025 11:23:13 +0200 Subject: [PATCH 016/116] set special case for console key when using native keyboard input ALWAYS make sure that remains in the same physical place otherwise things might get very annoying it already does so with my german layout --- src/sdl/i_video.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 9ce860cb4..df4b80e20 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -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 -- 2.54.0 From 852aa74d62dd7dae75f55a56b77a716cac17c792 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 23 Oct 2025 11:24:32 +0200 Subject: [PATCH 017/116] random style fixes and stuff --- src/hu_stuff.c | 22 +++++++++++----------- src/k_kart.c | 3 --- src/v_video.c | 4 ++-- 3 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 3a01aedc0..7f034f8ad 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<= 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/v_video.c b/src/v_video.c index 0104cf78c..9e7ece0d1 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; -- 2.54.0 From eb04271c83ee40c13d5180bfd5ff8658765c8d6d Mon Sep 17 00:00:00 2001 From: Indev Date: Thu, 23 Oct 2025 22:52:03 +0300 Subject: [PATCH 018/116] Actually try to do this with hooks --- src/lua_baselib.c | 40 +++++++--------------------------------- src/lua_hook.h | 1 + src/lua_hooklib.c | 30 ++++++++++++++++++++++++++---- 3 files changed, 34 insertions(+), 37 deletions(-) diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 3715fefdb..577549f5a 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -365,32 +365,6 @@ static int lib_pLookForPlayers(lua_State *L) return 1; } -static boolean checkLocalAddon(lua_State *L) -{ - char buf[128]; - lua_Debug ar; - lua_getstack(L, 1, &ar); - lua_getinfo(L, "S", &ar); - - strncpy(buf, ar.source, sizeof(buf)-1); - buf[127] = 0; - - char *p; - - if ((p = strstr(buf, "|")) != NULL) - *p = '\0'; - - UINT16 i; - - for (i = 0; i < numwadfiles; ++i) - { - if (strcmp(wadfiles[i]->filename, buf+1) == 0) // buf+1 - skip "@" - break; - } - - return (i < numwadfiles) && !wadfiles[i]->important; -} - // P_MOBJ //////////// @@ -404,7 +378,7 @@ static int lib_pSpawnMobj(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnMobj(x, y, z, type); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -432,7 +406,7 @@ static int lib_pSpawnMissile(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnMissile(source, dest, type); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -451,7 +425,7 @@ static int lib_pSpawnXYZMissile(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnXYZMissile(source, dest, type, x, y, z); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -472,7 +446,7 @@ static int lib_pSpawnPointMissile(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnPointMissile(source, xa, ya, za, type, x, y, z); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -491,7 +465,7 @@ static int lib_pSpawnAlteredDirectionMissile(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnAlteredDirectionMissile(source, type, x, y, z, shiftingAngle); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -522,7 +496,7 @@ static int lib_pSPMAngle(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SPMAngle(source, type, angle, allowaim, flags2); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } @@ -538,7 +512,7 @@ static int lib_pSpawnPlayerMissile(lua_State *L) if (type >= NUMMOBJTYPES) return luaL_error(L, "mobj type %d out of range (0 - %d)", type, NUMMOBJTYPES-1); mobj_t *th = P_SpawnPlayerMissile(source, type, flags2); - th->islocal = checkLocalAddon(L); + th->islocal = !hook_important; LUA_PushUserdata(L, th, META_MOBJ); return 1; } diff --git a/src/lua_hook.h b/src/lua_hook.h index 14437c26f..3072f2775 100644 --- a/src/lua_hook.h +++ b/src/lua_hook.h @@ -109,6 +109,7 @@ ENUM (STRING_HOOK); extern boolean hook_cmd_running; // This is used by PlayerCmd and lua_playerlib to prevent anything from being wirtten to player while we run PlayerCmd. extern int hook_defrosting; +extern bool hook_important; void LUA_HookVoid(int hook); void LUA_HookHUD(int hook, huddrawlist_h drawlist); diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index 6d04b6154..c2016b771 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -19,6 +19,7 @@ #include "b_bot.h" #include "z_zone.h" #include "m_perfstats.h" +#include "w_wad.h" #include "lua_script.h" #include "lua_libs.h" @@ -39,14 +40,20 @@ LIST (stringHookNames, STRING_HOOK_LIST); #undef LIST +typedef struct { + int id; + bool important; +} hookinfo_t; + typedef struct { int numHooks; - int *ids; + hookinfo_t *ids; } hook_t; typedef struct { int numGeneric; int ref; + bool important; } stringhook_t; static hook_t hookIds[HOOK(MAX)]; @@ -56,6 +63,8 @@ static hook_t mobjHookIds[NUMMOBJTYPES][MOBJ_HOOK(MAX)]; // Lua tables are used to lookup string hook ids. static stringhook_t stringHooks[STRING_HOOK(MAX)]; +bool hook_important = true; + // This will be indexed by hook id, the value of which fetches the registry. static int * hookRefs; static int nextid; @@ -109,7 +118,11 @@ static void get_table(lua_State *L) FUNCINLINE static ATTRINLINE void add_hook_to_table(lua_State *L, int n) { + lua_newtable(L); lua_pushnumber(L, nextid); + lua_rawseti(L, -2, 1); + lua_pushboolean(L, wadfiles[numwadfiles-1]->important); + lua_rawseti(L, -2, 2); lua_rawseti(L, -2, n); } @@ -180,7 +193,8 @@ FUNCINLINE static ATTRINLINE void add_hook(hook_t *map) { Z_Realloc(map->ids, (map->numHooks + 1) * sizeof *map->ids, PU_STATIC, &map->ids); - map->ids[map->numHooks++] = nextid; + map->ids[map->numHooks].important = wadfiles[numwadfiles-1]->important; + map->ids[map->numHooks++].id = nextid; } FUNCINLINE static ATTRINLINE void add_mobj_hook(lua_State *L, int hook_type) @@ -287,6 +301,7 @@ struct Hook_State { const char * string;/* used to fetch table, ran first if set */ int top;/* index of last argument passed to hook */ int id;/* id to fetch ref */ + boolean important;/* is this hook from local addon */ int values;/* num arguments passed to hook */ int results;/* num values returned by hook */ Hook_Callback results_handler;/* callback when hook successfully returns */ @@ -416,22 +431,29 @@ FUNCINLINE static ATTRINLINE void init_hook_call hook->results_handler = results_handler; } -FUNCINLINE static ATTRINLINE void get_hook(Hook_State *hook, const int *ids, int n) +FUNCINLINE static ATTRINLINE void get_hook(Hook_State *hook, const hookinfo_t *ids, int n) { - hook->id = ids[n]; + hook->id = ids[n].id; + hook->important = ids[n].important; lua_getref(gL, hookRefs[hook->id]); } FUNCINLINE static ATTRINLINE void get_hook_from_table(Hook_State *hook, int n) { lua_rawgeti(gL, -1, n); + lua_rawgeti(gL, -1, 1); hook->id = lua_tonumber(gL, -1); lua_pop(gL, 1); + lua_rawgeti(gL, -2, 2); + hook->important = lua_toboolean(gL, -1); + lua_pop(gL, 2); lua_getref(gL, hookRefs[hook->id]); } static int call_single_hook_no_copy(Hook_State *hook) { + hook_important = hook->important; + if (lua_pcall(gL, hook->values, hook->results, EINDEX) == 0) { if (hook->results > 0) -- 2.54.0 From b84d1013374bdcbfeb42ba5e0c94bb9d5659ea75 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 01:52:53 +0200 Subject: [PATCH 019/116] initialize sdl window,renderer and texture to something --- src/sdl/i_video.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index df4b80e20..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"; @@ -909,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); } @@ -1111,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; @@ -1147,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; @@ -1292,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); @@ -1358,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(); } @@ -1625,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); } @@ -1732,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; @@ -1962,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); } -- 2.54.0 From 0e2ffdeb1dedfd9954ddd4897d8d180ead70a014 Mon Sep 17 00:00:00 2001 From: "James R." Date: Sat, 30 Sep 2023 16:07:53 -0700 Subject: [PATCH 020/116] SDLSetMode: render immediately after resolution change to avoid 1-frame of texture presented at wrong size --- src/sdl/i_video.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 7393d8e4b..229008352 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -1313,6 +1313,11 @@ static void SDLSetMode(INT32 width, INT32 height, SDL_bool fullscreen) texture = SDL_CreateTexture(renderer, sw_texture_format, SDL_TEXTUREACCESS_STREAMING, width, height); } + + if (graphics_started) + { + I_UpdateNoVsync(); + } } // -- 2.54.0 From 383d55cac669d1e76ef170410fe9bd68fdbb8c89 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 03:37:45 +0200 Subject: [PATCH 021/116] smol cleanup V_DrawVhsEffect dont need to assign all the software stuff in gl mode --- src/hardware/hw_draw.c | 57 +++++++++++++++++++++--------------------- src/r_data.c | 1 + src/r_main.cpp | 2 ++ src/v_video.c | 43 +++++++++++++++++++++---------- 4 files changed, 62 insertions(+), 41 deletions(-) diff --git a/src/hardware/hw_draw.c b/src/hardware/hw_draw.c index cf8ab29e3..4797f21de 100644 --- a/src/hardware/hw_draw.c +++ b/src/hardware/hw_draw.c @@ -46,9 +46,9 @@ 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; @@ -87,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); @@ -269,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); @@ -506,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; @@ -518,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. { @@ -890,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; @@ -906,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; diff --git a/src/r_data.c b/src/r_data.c index a796de138..93ad621fa 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -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_main.cpp b/src/r_main.cpp index 5313357d6..339e34548 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -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(); diff --git a/src/v_video.c b/src/v_video.c index 9e7ece0d1..dd5091fa1 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -1739,22 +1739,24 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) void V_DrawVhsEffect(boolean rewind) { + fixed_t uby, dby; static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; - UINT8 *buf = vid.screens[0], *tmp = vid.screens[4]; - UINT16 y; - UINT32 x, pos = 0; + UINT8 barsize, updistort, downdistort; - 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 @@ -1763,11 +1765,12 @@ void V_DrawVhsEffect(boolean rewind) downbary += renderdeltatics * (vid.dup * (rewind ? 2 : 1)); if (upbary < -barsize*FRACUNIT) - upbary = vid.height< vid.height< vid.height << FRACBITS) downbary = -barsize*FRACUNIT; - fixed_t uby = upbary>>FRACBITS, dby = downbary>>FRACBITS; + uby = upbary >> FRACBITS; + dby = downbary >> FRACBITS; #ifdef HWRENDER if (rendermode == render_opengl) @@ -1777,6 +1780,16 @@ void V_DrawVhsEffect(boolean rewind) } #endif + buf = vid.screens[0]; + tmp = vid.screens[4]; + + normalmapstart = ((UINT8 *)transtables + (8<> 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 } @@ -1920,7 +1935,6 @@ UINT8 *V_GetStringColormap(INT32 colorflags) void V_DrawCharacter(INT32 x, INT32 y, INT32 c, boolean lowercaseallowed) { INT32 w, flags; - const UINT8 *colormap = V_GetStringColormap(c); flags = c & ~(V_CHARCOLORMASK | V_PARAMMASK); c &= 0x7f; @@ -1936,6 +1950,8 @@ void V_DrawCharacter(INT32 x, INT32 y, INT32 c, boolean lowercaseallowed) if (x + w > vid.width) return; + const UINT8 *colormap = V_GetStringColormap(c); + if (colormap != NULL) V_DrawMappedPatch(x, y, flags, hu_font[c], colormap); else @@ -2000,6 +2016,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; -- 2.54.0 From ca27dad6c117e364d5e3b13112662035092f0fc4 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 03:34:47 +0200 Subject: [PATCH 022/116] use D_ClearState in G_StopDemo actually fixes issues with crashes AND palette reset also resets a bunch of more stuff which def is good --- src/d_main.c | 27 ++++++++++++++++++++++++--- src/f_finale.c | 1 + src/g_demo.c | 13 +------------ 3 files changed, 26 insertions(+), 15 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 1bc346deb..992fc59db 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -954,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 // @@ -963,6 +981,7 @@ void D_ClearState(void) // okay, stop now // (otherwise the game still thinks we're playing!) + CURLAbortFile(); SV_StopServer(); SV_ResetServer(); serverlistultimatecount = 0; @@ -971,7 +990,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; @@ -990,7 +1010,6 @@ void D_ClearState(void) gameaction = ga_nothing; memset(displayplayers, 0, sizeof(displayplayers)); consoleplayer = 0; - //demosequence = -1; gametype = GT_RACE; // SRB2kart paused = false; @@ -1013,6 +1032,8 @@ void D_ClearState(void) G_SetGamestate(GS_NULL); wipegamestate = GS_NULL; + + M_ClearMenus(true); } // @@ -1022,8 +1043,8 @@ void D_StartTitle(void) { demo.title = false; D_ClearState(); + multiplayer = false; // reset manually netgame = false; // title menu shouldnt be a netgame lmao - M_ClearMenus(true); F_StartTitleScreen(); D_ResetDeviceLED(); } 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/g_demo.c b/src/g_demo.c index de8523ae9..f779c26d8 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -3416,18 +3416,7 @@ void G_StopDemo(void) if (gamestate == GS_VOTING) Y_EndVote(); - M_ClearMenus(true); - - G_SetGamestate(GS_NULL); - wipegamestate = GS_NULL; - SV_StopServer(); - SV_ResetServer(); - - if (gamestate == GS_LEVEL && rendermode != render_none) - { - V_SetPaletteLump("PLAYPAL"); // Reset the palette - R_ReInitColormaps(0, LUMPERROR); - } + D_ClearState(); } // Stops timing a demo. -- 2.54.0 From 7c507c7b3bd33980022d79f55c1f441f082d21b0 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 03:37:03 +0200 Subject: [PATCH 023/116] do some cleanup g_demo :shook: use the CLEANUP macro everywhere init some things that may not be initialized and make this more readable lets hope didnt break anything Zzz... TODO: if there are still issues with demo records and stuff crashing might consider porting some of the fixes from RR --- src/g_demo.c | 680 +++++++++++++++++++++++++++++---------------------- 1 file changed, 381 insertions(+), 299 deletions(-) diff --git a/src/g_demo.c b/src/g_demo.c index f779c26d8..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; @@ -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; @@ -3508,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; -- 2.54.0 From 8a305d3c797fe0b9af8fcde38f920095103a327a Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 03:47:50 +0200 Subject: [PATCH 024/116] move those to D_ClearState --- src/d_main.c | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 992fc59db..d4cef24c3 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -979,6 +979,8 @@ void D_ClearState(void) { INT32 i; + demo.title = false; + // okay, stop now // (otherwise the game still thinks we're playing!) CURLAbortFile(); @@ -1034,6 +1036,9 @@ void D_ClearState(void) wipegamestate = GS_NULL; M_ClearMenus(true); + + // map palettes affect this + D_ResetDeviceLED(); } // @@ -1041,12 +1046,9 @@ void D_ClearState(void) // void D_StartTitle(void) { - demo.title = false; D_ClearState(); - multiplayer = false; // reset manually - netgame = false; // title menu shouldnt be a netgame lmao + multiplayer = netgame = false; // title menu shouldnt be a netgame or multiplayer lmao F_StartTitleScreen(); - D_ResetDeviceLED(); } // -- 2.54.0 From 82c41915161650fa0a15fed5d05a2ff537a4ae97 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 04:09:43 +0200 Subject: [PATCH 025/116] Revert "SDLSetMode: render immediately after resolution change to avoid 1-frame of texture presented at wrong size" This reverts commit 0e2ffdeb1dedfd9954ddd4897d8d180ead70a014. --- src/sdl/i_video.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 229008352..7393d8e4b 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -1313,11 +1313,6 @@ static void SDLSetMode(INT32 width, INT32 height, SDL_bool fullscreen) texture = SDL_CreateTexture(renderer, sw_texture_format, SDL_TEXTUREACCESS_STREAMING, width, height); } - - if (graphics_started) - { - I_UpdateNoVsync(); - } } // -- 2.54.0 From 59470ddbd451a07074df3b5a87c612aff5cc382f Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 14:24:08 +0200 Subject: [PATCH 026/116] fix oob access in D_SetupVote check if luamaps was set before --- src/d_netcmd.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index d62be9daa..92d9fb935 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -2487,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)); -- 2.54.0 From ba5b79e48a5dff68fae9b93112d4aee79373f1e3 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 15:33:44 +0200 Subject: [PATCH 027/116] dont double print kitchen sink message to log we already handle this in HU_DoCEcho --- src/p_map.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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); } -- 2.54.0 From 16a531272fa839d99ff8946d6ec68aa91485291b Mon Sep 17 00:00:00 2001 From: Indev Date: Fri, 24 Oct 2025 16:36:07 +0300 Subject: [PATCH 028/116] Skip repeating backslashes in HU_DoCEcho when printing to console --- src/hu_stuff.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 7f034f8ad..0e29a5124 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -2855,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); -- 2.54.0 From bb3dd435f02c63d6f35eb6ab9a922ab20322061a Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 15:39:30 +0200 Subject: [PATCH 029/116] oop didnt mean to move this --- src/v_video.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/v_video.c b/src/v_video.c index dd5091fa1..031971326 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -1935,6 +1935,7 @@ UINT8 *V_GetStringColormap(INT32 colorflags) void V_DrawCharacter(INT32 x, INT32 y, INT32 c, boolean lowercaseallowed) { INT32 w, flags; + const UINT8 *colormap = V_GetStringColormap(c); flags = c & ~(V_CHARCOLORMASK | V_PARAMMASK); c &= 0x7f; @@ -1950,8 +1951,6 @@ void V_DrawCharacter(INT32 x, INT32 y, INT32 c, boolean lowercaseallowed) if (x + w > vid.width) return; - const UINT8 *colormap = V_GetStringColormap(c); - if (colormap != NULL) V_DrawMappedPatch(x, y, flags, hu_font[c], colormap); else -- 2.54.0 From 26fc417555c83ff4665768e208d817c98cf22ed8 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 16:09:43 +0200 Subject: [PATCH 030/116] forgor about localskin menu Zzz.... --- src/m_menu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/m_menu.c b/src/m_menu.c index a7be33c42..6eaccdce0 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -9643,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! } -- 2.54.0 From a69df8807dcb513d2324a2d5d42c20c89621b511 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 21:56:52 +0200 Subject: [PATCH 031/116] fix some messed up whitespaces lel --- src/m_argv.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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, '/'); -- 2.54.0 From 28685ea6582221db9faadd60b3ab22da0d20eaf7 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 25 Oct 2025 20:38:51 +0200 Subject: [PATCH 032/116] fix some tooltips issues, wording and inconsistencies fbo also now supports from gl 2.1 --- src/m_menudefs.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index e02113026..6bda9c733 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -968,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 @@ -1375,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 @@ -1763,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.", -- 2.54.0 From 8cc73bc482e2d0e73eeddf49b3303770af2c1c73 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 25 Oct 2025 22:01:22 +0200 Subject: [PATCH 033/116] =?UTF-8?q?Port=20RR=C2=B4s=20gamma=20correction?= =?UTF-8?q?=20+=20split=20gamma=20and=20brightness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit port of https://gitlab.com/kart-krew-dev/ring-racers/-/commit/e27506c660933e19dbcfe9ec776caf7819952e30 not cherry picked since it differs too much it would be hellish to untangle (sry!) Gamma is split from brightness since both do somewhat different things in the context here --- src/hardware/hw_main.cpp | 6 +- src/hardware/hw_md2.c | 2 +- src/m_menudefs.c | 50 +++++++------ src/r_draw.cpp | 23 ++++-- src/screen.c | 3 + src/v_video.c | 155 ++++++++++++++++++++------------------- src/v_video.h | 12 ++- 7 files changed, 141 insertions(+), 110 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 45f25c2a6..f4e95eb53 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -458,8 +458,8 @@ void HWR_Lighting(FSurfaceInfo *Surface, INT32 light_level, extracolormap_t *col // in palette rendering mode, this is not needed since it properly takes the changes to the palette itself if (!HWR_ShouldUsePaletteRendering()) { - V_CubeApply(&tint_color.s.red, &tint_color.s.green, &tint_color.s.blue); - V_CubeApply(&fade_color.s.red, &fade_color.s.green, &fade_color.s.blue); + V_CubeApply(&tint_color); + V_CubeApply(&fade_color); } Surface->PolyColor.rgba = poly_color.rgba; @@ -5962,7 +5962,7 @@ static void HWR_DoPostProcessor(player_t *player) Surf.PolyColor.s.alpha = 0xc0; // match software mode - V_CubeApply(&Surf.PolyColor.s.red, &Surf.PolyColor.s.green, &Surf.PolyColor.s.blue); + V_CubeApply(&Surf.PolyColor); GL_DrawPolygon(&Surf, v, 4, PF_Modulated|PF_Translucent|PF_NoTexture|PF_NoDepthTest); } diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index f3db532e9..7d4857dc3 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -417,7 +417,7 @@ static void md2_loadTexture(md2_t *model) size = w*h; while (size--) { - V_CubeApply(&image->s.red, &image->s.green, &image->s.blue); + V_CubeApply(image); image++; } } diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 6bda9c733..5f2d782f5 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -818,26 +818,31 @@ static menuitem_t OP_VideoOptionsMenu[] = #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) {IT_STRING|IT_CVAR, NULL, "Fullscreen", &cv_fullscreen, 20}, #endif +#ifdef BACKWARDSCOMPATCORRECTION {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Brightness", &cv_globalgamma, 30}, - - {IT_STRING | IT_CVAR | IT_CV_SLIDER, - NULL, "Saturation", &cv_globalsaturation , 40}, - - {IT_SUBMENU|IT_STRING, NULL, "Advanced Color Settings...", &OP_ColorOptionsDef, 50}, - - {IT_STRING | IT_CVAR, NULL, "Draw Distance", &cv_drawdist, 65}, - {IT_STRING | IT_CVAR, NULL, "Weather Draw Distance", &cv_drawdist_precip, 75}, - - {IT_STRING | IT_CVAR, NULL, "Show FPS", &cv_ticrate, 95}, - {IT_STRING | IT_CVAR, NULL, "Vertical Sync", &cv_vidwait, 105}, - {IT_STRING | IT_CVAR, NULL, "FPS Cap", &cv_fpscap, 115}, - {IT_STRING | IT_CVAR, NULL, "Drift spark pulse size", &cv_driftsparkpulse, 125}, - {IT_STRING | IT_CVAR, NULL, "VHS effect", &cv_vhseffect, 135}, -#ifdef HWRENDER - {IT_SUBMENU|IT_STRING, NULL, "OpenGL Options...", &OP_OpenGLOptionsDef, 145}, + NULL, "Gamma", &cv_globalgamma, 30}, #endif - {IT_SUBMENU|IT_STRING, NULL, "Advanced Video Options...", &OP_ExpOptionsDef, 155}, + + {IT_STRING | IT_CVAR | IT_CV_SLIDER, + NULL, "Brightness", &cv_globalbrightness, 40}, + + {IT_STRING | IT_CVAR | IT_CV_SLIDER, + NULL, "Saturation", &cv_globalsaturation , 50}, + + {IT_SUBMENU|IT_STRING, NULL, "Advanced Color Settings...", &OP_ColorOptionsDef, 60}, + + {IT_STRING | IT_CVAR, NULL, "Draw Distance", &cv_drawdist, 75}, + {IT_STRING | IT_CVAR, NULL, "Weather Draw Distance", &cv_drawdist_precip, 85}, + + {IT_STRING | IT_CVAR, NULL, "Show FPS", &cv_ticrate, 105}, + {IT_STRING | IT_CVAR, NULL, "Vertical Sync", &cv_vidwait, 115}, + {IT_STRING | IT_CVAR, NULL, "FPS Cap", &cv_fpscap, 125}, + {IT_STRING | IT_CVAR, NULL, "Drift spark pulse size", &cv_driftsparkpulse, 135}, + {IT_STRING | IT_CVAR, NULL, "VHS effect", &cv_vhseffect, 145}, +#ifdef HWRENDER + {IT_SUBMENU|IT_STRING, NULL, "OpenGL Options...", &OP_OpenGLOptionsDef, 155}, +#endif + {IT_SUBMENU|IT_STRING, NULL, "Advanced Video Options...", &OP_ExpOptionsDef, 165}, }; static const char* OP_VideoTooltips[] = @@ -846,11 +851,12 @@ static const char* OP_VideoTooltips[] = #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) "Enable fullscreen.", #endif - "Gamma (brightness) of the game.", - "Saturation of the game.", + "Increase the gamma of the displayed image.", + "Increase or decrease the brightness of the displayed image.", + "Reduce the saturation of the displayed image.", "Advanced color settings of the game.", - "How far away objects are drawn.", - "How far away weather is drawn.", + "How far objects can be drawn.", + "Affects how far weather visuals can be drawn.", "Show current game framerate and select the style.", "Sync game framerate to refresh rate of monitor.", "Set manual framerate cap.", diff --git a/src/r_draw.cpp b/src/r_draw.cpp index 39f8918bb..6dd1233a0 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -113,6 +113,7 @@ CV_PossibleValue_t Color_cons_t[MAXSKINCOLORS+1]; struct GenerateBlendTables_State { RGBA_t *LocalPalette; + RGBA_t *gammaCorrectedPalette; }; static void R_GenerateBlendTables_Core(struct GenerateBlendTables_State *state); @@ -126,6 +127,7 @@ static void R_GenerateBlendTables_Thread(void *userdata) R_GenerateBlendTables_Core(state); free(state->LocalPalette); + free(state->gammaCorrectedPalette); free(state); } #endif @@ -154,26 +156,33 @@ void R_InitTranslucencyTables(void) } static colorlookup_t transtab_lut; +static colorlookup_t transtab_lut_corrected; static void BlendTab_Translucent(UINT8 *table, int style, UINT8 blendamt) { INT16 bg, fg; + RGBA_t backrgba, frontrgba, result; if (table == NULL) I_Error("BlendTab_Translucent: input table was NULL!"); for (bg = 0; bg < 0x100; bg++) { + backrgba = pGammaCorrectedPalette[bg]; + for (fg = 0; fg < 0x100; fg++) { - RGBA_t backrgba = V_GetColor(bg); - RGBA_t frontrgba = V_GetColor(fg); - RGBA_t result; + frontrgba = pGammaCorrectedPalette[fg]; +#if 0 // perfect implementation result.rgba = ASTBlendPixel(backrgba, frontrgba, style, 0xFF); result.rgba = ASTBlendPixel(result, frontrgba, AST_TRANSLUCENT, blendamt); - table[((bg * 0x100) + fg)] = GetColorLUT(&transtab_lut, result.s.red, result.s.green, result.s.blue); +#else // performance scrabbler + result.rgba = ASTBlendPixel(backrgba, frontrgba, style, 0xFF); + result.rgba = ASTBlendPixel(result, frontrgba, AST_TRANSLUCENT, blendamt); + table[((bg * 0x100) + fg)] = GetColorLUT(&transtab_lut_corrected, result.s.red, result.s.green, result.s.blue); // pGammaCorrectedPalette +#endif } } } @@ -224,7 +233,7 @@ static void BlendTab_Modulative(UINT8 *table) RGBA_t frontrgba = V_GetColor(fg); RGBA_t result; result.rgba = ASTBlendPixel(backrgba, frontrgba, AST_MODULATE, 0); - table[((bg * 0x100) + fg)] = GetColorLUT(&transtab_lut, result.s.red, result.s.green, result.s.blue); + table[((bg * 0x100) + fg)] = GetColorLUT(&transtab_lut_corrected, result.s.red, result.s.green, result.s.blue); } } } @@ -278,11 +287,12 @@ void R_GenerateBlendTables(void) size_t palsize = 256 * sizeof(RGBA_t); state->LocalPalette = static_cast(memcpy(malloc(palsize), pLocalPalette, palsize)); + state->gammaCorrectedPalette = static_cast(memcpy(malloc(palsize), pGammaCorrectedPalette, palsize)); I_spawn_thread("blend-tables", R_GenerateBlendTables_Thread, state); #else - struct GenerateBlendTables_State state = {pLocalPalette}; + struct GenerateBlendTables_State state = {pLocalPalette, pGammaCorrectedPalette}; R_GenerateBlendTables_Core(&state); #endif } @@ -290,6 +300,7 @@ void R_GenerateBlendTables(void) static void R_GenerateBlendTables_Core(struct GenerateBlendTables_State *state) { InitColorLUT(&transtab_lut, state->LocalPalette, false); + InitColorLUT(&transtab_lut_corrected, state->gammaCorrectedPalette, false); // Additive BlendTab_GenerateMaps(blendtab_add, AST_ADD, BlendTab_Translucent); diff --git a/src/screen.c b/src/screen.c index 4a38ef97d..2ef8e664c 100644 --- a/src/screen.c +++ b/src/screen.c @@ -215,7 +215,10 @@ void SCR_Startup(void) CV_RegisterVar(&cv_menucaps); CV_RegisterVar(&cv_constextsize); +#ifdef BACKWARDSCOMPATCORRECTION CV_RegisterVar(&cv_globalgamma); +#endif + CV_RegisterVar(&cv_globalbrightness); CV_RegisterVar(&cv_globalsaturation); CV_RegisterVar(&cv_rhue); diff --git a/src/v_video.c b/src/v_video.c index 031971326..1045d2b57 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -43,8 +43,13 @@ static void CV_palette_OnChange(void); consvar_t cv_palette = {"palette", "", CV_CALL|CV_NOINIT, NULL, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_palettenum = {"palettenum", "0", CV_CALL|CV_NOINIT, CV_Unsigned, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -static CV_PossibleValue_t gamma_cons_t[] = {{-15, "MIN"}, {4, "MAX"}, {0, NULL}}; +#ifdef BACKWARDSCOMPATCORRECTION +static CV_PossibleValue_t gamma_cons_t[] = {{0, "MIN"}, {4, "MAX"}, {0, NULL}}; consvar_t cv_globalgamma = {"gamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +#endif + +static CV_PossibleValue_t brightness_cons_t[] = {{-15, "MIN"}, {5, "MAX"}, {0, NULL}}; +consvar_t cv_globalbrightness = {"brightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; static CV_PossibleValue_t saturation_cons_t[] = {{0, "MIN"}, {10, "MAX"}, {0, NULL}}; consvar_t cv_globalsaturation = {"saturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -85,6 +90,7 @@ consvar_t cv_menucaps = {"menucaps", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NUL // local copy of the palette for V_GetColor() RGBA_t *pLocalPalette = NULL; +RGBA_t *pGammaCorrectedPalette = NULL; static size_t currentPaletteSize; @@ -138,15 +144,11 @@ static boolean InitCube(void) #define diffconsgamma(cv) (cv.value != 0) #define diffconssat(cv) (cv.value != 10) -#ifdef BACKWARDSCOMPATCORRECTION - doinggamma = (cv_globalgamma.value < 0); //dont mess up gamma when raising brightness pls -#else - doinggamma = diffcons(cv_globalgamma); -#endif + doinggamma = diffcons(cv_globalbrightness); #define gammascale 8 - globalgammamul = (cv_globalgamma.value ? ((255.0f - (gammascale*abs(cv_globalgamma.value))) / 255.0f) : 1.0f); - globalgammaoffs = ((cv_globalgamma.value > 0) ? ((gammascale*cv_globalgamma.value) / 255.0f) : 0.0f); + globalgammamul = (cv_globalbrightness.value ? ((255.0f - (gammascale*abs(cv_globalbrightness.value))) / 255.0f) : 1.0f); + globalgammaoffs = ((cv_globalbrightness.value > 0) ? ((gammascale*cv_globalbrightness.value) / 255.0f) : 0.0f); desatur[0] = desatur[1] = desatur[2] = globalgammaoffs + (0.33f * globalgammamul); if (doinggamma @@ -302,24 +304,6 @@ same, I'm not gonna be the one to remove this base modification. toast 20/04/17 ... welp yes i am (27/07/19, see the ifdef around it) */ -const UINT8 correctiontable[256] = - {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, - 17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, - 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48, - 49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, - 65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80, - 81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96, - 97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112, - 113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128, - 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, - 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, - 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175, - 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, - 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, - 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, - 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239, - 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255}; - const UINT8 gammatable[5][256] = { {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, @@ -405,6 +389,26 @@ const UINT8 gammatable[5][256] = }; #endif +UINT32 V_GammaCorrect(UINT32 input, double power) +{ + RGBA_t result; + double linear; + + result.rgba = input; + + linear = ((double)result.s.red)/255.0f; + linear = pow(linear, power)*255.0f; + result.s.red = (UINT8)(linear); + linear = ((double)result.s.green)/255.0f; + linear = pow(linear, power)*255.0f; + result.s.green = (UINT8)(linear); + linear = ((double)result.s.blue)/255.0f; + linear = pow(linear, power)*255.0f; + result.s.blue = (UINT8)(linear); + + return result.rgba; +} + // keep a copy of the palette so that we can get the RGB value for a color index at any time. static void LoadPalette(const char *lumpname) { @@ -413,7 +417,7 @@ static void LoadPalette(const char *lumpname) lumpnum_t lumpnum; #ifdef BACKWARDSCOMPATCORRECTION - const UINT8 *usegamma = gammatable[min(max(cv_globalgamma.value, 0), 4)]; + const UINT8 *usegamma = gammatable[cv_globalgamma.value]; #endif Cubeapply = InitCube(); @@ -423,25 +427,18 @@ static void LoadPalette(const char *lumpname) palsize = currentPaletteSize / 3; Z_Free(pLocalPalette); + Z_Free(pGammaCorrectedPalette); pLocalPalette = Z_Malloc(sizeof (*pLocalPalette)*palsize, PU_STATIC, NULL); + pGammaCorrectedPalette = Z_Malloc(sizeof (*pGammaCorrectedPalette)*palsize, PU_STATIC, NULL); pal = W_CacheLumpNum(lumpnum, PU_CACHE); for (i = 0; i < palsize; i++) { #ifdef BACKWARDSCOMPATCORRECTION - if (cv_globalgamma.value >= 0 && cv_globalgamma.value <= 4) - { - pLocalPalette[i].s.red = usegamma[*pal++]; - pLocalPalette[i].s.green = usegamma[*pal++]; - pLocalPalette[i].s.blue = usegamma[*pal++]; - } - else - { - pLocalPalette[i].s.red = correctiontable[*pal++]; - pLocalPalette[i].s.green = correctiontable[*pal++]; - pLocalPalette[i].s.blue = correctiontable[*pal++]; - } + pLocalPalette[i].s.red = usegamma[*pal++]; + pLocalPalette[i].s.green = usegamma[*pal++]; + pLocalPalette[i].s.blue = usegamma[*pal++]; #else pLocalPalette[i].s.red = *pal++; pLocalPalette[i].s.green = *pal++; @@ -449,15 +446,17 @@ static void LoadPalette(const char *lumpname) #endif pLocalPalette[i].s.alpha = 0xFF; + pGammaCorrectedPalette[i].rgba = V_GammaDecode(pLocalPalette[i].rgba); + if (!Cubeapply) continue; - // lerp of colour cubing! if you want, make it smoother yourself - V_CubeApply(&pLocalPalette[i].s.red, &pLocalPalette[i].s.green, &pLocalPalette[i].s.blue); + V_CubeApply(&pGammaCorrectedPalette[i]); + pLocalPalette[i].rgba = V_GammaEncode(pGammaCorrectedPalette[i].rgba); } } -void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue) +void V_CubeApply(RGBA_t *input) { float working[4][3]; float linear; @@ -466,7 +465,7 @@ void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue) if (!Cubeapply) return; - linear = (*red/255.0f); + linear = ((*input).s.red/255.0); #define dolerp(e1, e2) ((1 - linear)*e1 + linear*e2) for (q = 0; q < 3; q++) { @@ -475,13 +474,15 @@ void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue) working[2][q] = dolerp(Cubepal[0][0][1][q], Cubepal[1][0][1][q]); working[3][q] = dolerp(Cubepal[0][1][1][q], Cubepal[1][1][1][q]); } - linear = (*green/255.0f); + + linear = ((*input).s.green/255.0); for (q = 0; q < 3; q++) { working[0][q] = dolerp(working[0][q], working[1][q]); working[1][q] = dolerp(working[2][q], working[3][q]); } - linear = (*blue/255.0f); + + linear = ((*input).s.blue/255.0); for (q = 0; q < 3; q++) { working[0][q] = 255*dolerp(working[0][q], working[1][q]); @@ -492,9 +493,9 @@ void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue) } #undef dolerp - *red = (UINT8)(working[0][0]); - *green = (UINT8)(working[0][1]); - *blue = (UINT8)(working[0][2]); + (*input).s.red = (UINT8)(working[0][0]); + (*input).s.green = (UINT8)(working[0][1]); + (*input).s.blue = (UINT8)(working[0][2]); } const char *R_GetPalname(UINT16 num) @@ -1329,37 +1330,37 @@ void V_DrawFill(INT32 x, INT32 y, INT32 w, INT32 h, INT32 c) // This is now a function since it's otherwise repeated 2 times and honestly looks retarded: static UINT32 V_GetHWConsBackColor(void) { - UINT8 r, g, b; + RGBA_t output; switch (cons_backcolor.value) { - case 0: r = 0xff; g = 0xff; b = 0xff; break; // White - case 1: r = 0x80; g = 0x80; b = 0x80; break; // Black - case 2: r = 0xde; g = 0xb8; b = 0x87; break; // Sepia - case 3: r = 0x40; g = 0x20; b = 0x10; break; // Brown - case 4: r = 0xfa; g = 0x80; b = 0x72; break; // Pink - case 5: r = 0xff; g = 0x69; b = 0xb4; break; // Raspberry - case 6: r = 0xff; g = 0x00; b = 0x00; break; // Red - case 7: r = 0xff; g = 0xd6; b = 0x83; break; // Creamsicle - case 8: r = 0xff; g = 0x80; b = 0x00; break; // Orange - case 9: r = 0xda; g = 0xa5; b = 0x20; break; // Gold - case 10: r = 0x80; g = 0x80; b = 0x00; break; // Yellow - case 11: r = 0x00; g = 0xff; b = 0x00; break; // Emerald - case 12: r = 0x00; g = 0x80; b = 0x00; break; // Green - case 13: r = 0x40; g = 0x80; b = 0xff; break; // Cyan - case 14: r = 0x46; g = 0x82; b = 0xb4; break; // Steel - case 15: r = 0x1e; g = 0x90; b = 0xff; break; // Periwinkle - case 16: r = 0x00; g = 0x00; b = 0xff; break; // Blue - case 17: r = 0xff; g = 0x00; b = 0xff; break; // Purple - case 18: r = 0xee; g = 0x82; b = 0xee; break; // Lavender + case 0: output.s.red = 0xff; output.s.green = 0xff; output.s.blue = 0xff; break; // White + case 1: output.s.red = 0x80; output.s.green = 0x80; output.s.blue = 0x80; break; // Black + case 2: output.s.red = 0xde; output.s.green = 0xb8; output.s.blue = 0x87; break; // Sepia + case 3: output.s.red = 0x40; output.s.green = 0x20; output.s.blue = 0x10; break; // Brown + case 4: output.s.red = 0xfa; output.s.green = 0x80; output.s.blue = 0x72; break; // Pink + case 5: output.s.red = 0xff; output.s.green = 0x69; output.s.blue = 0xb4; break; // Raspberry + case 6: output.s.red = 0xff; output.s.green = 0x00; output.s.blue = 0x00; break; // Red + case 7: output.s.red = 0xff; output.s.green = 0xd6; output.s.blue = 0x83; break; // Creamsicle + case 8: output.s.red = 0xff; output.s.green = 0x80; output.s.blue = 0x00; break; // Orange + case 9: output.s.red = 0xda; output.s.green = 0xa5; output.s.blue = 0x20; break; // Gold + case 10: output.s.red = 0x80; output.s.green = 0x80; output.s.blue = 0x00; break; // Yellow + case 11: output.s.red = 0x00; output.s.green = 0xff; output.s.blue = 0x00; break; // Emerald + case 12: output.s.red = 0x00; output.s.green = 0x80; output.s.blue = 0x00; break; // Green + case 13: output.s.red = 0x40; output.s.green = 0x80; output.s.blue = 0xff; break; // Cyan + case 14: output.s.red = 0x46; output.s.green = 0x82; output.s.blue = 0xb4; break; // Steel + case 15: output.s.red = 0x1e; output.s.green = 0x90; output.s.blue = 0xff; break; // Periwinkle + case 16: output.s.red = 0x00; output.s.green = 0x00; output.s.blue = 0xff; break; // Blue + case 17: output.s.red = 0xff; output.s.green = 0x00; output.s.blue = 0xff; break; // Purple + case 18: output.s.red = 0xee; output.s.green = 0x82; output.s.blue = 0xee; break; // Lavender // Default green - default: r = 0x00; g = 0x80; b = 0x00; break; + default: output.s.red = 0x00; output.s.green = 0x80; output.s.blue = 0x00; break; } if (!HWR_ShouldUsePaletteRendering()) - V_CubeApply(&r, &g, &b); + V_CubeApply(&output); - return (r << 24) | (g << 16) | (b << 8); + return (output.s.red << 24) | (output.s.green << 16) | (output.s.blue << 8); } #endif @@ -3808,12 +3809,14 @@ void InitColorLUT(colorlookup_t *lut, RGBA_t *palette, boolean makecolors) UINT8 r, g, b; for (r = 0; r < 0xFF; r++) - for (g = 0; g < 0xFF; g++) - for (b = 0; b < 0xFF; b++) { - i = CLUTINDEX(r, g, b); - if (lut->table[i] == 0xFFFF) - lut->table[i] = NearestPaletteColor(r, g, b, palette); + for (g = 0; g < 0xFF; g++) + { + for (b = 0; b < 0xFF; b++) + { + lut->table[i] = GetColorLUT(lut, r, g, b); + } + } } } } diff --git a/src/v_video.h b/src/v_video.h index 6213dc1bb..ce9337adc 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -40,7 +40,10 @@ extern "C" { // extern consvar_t cv_ticrate, cv_accuratefps, cv_allcaps, cv_constextsize, cv_menucaps, -cv_globalgamma, cv_globalsaturation, +#ifdef BACKWARDSCOMPATCORRECTION +cv_globalgamma, +#endif +cv_globalbrightness, cv_globalsaturation, cv_rhue, cv_yhue, cv_ghue, cv_chue, cv_bhue, cv_mhue, cv_rgamma, cv_ygamma, cv_ggamma, cv_cgamma, cv_bgamma, cv_mgamma, cv_rsaturation, cv_ysaturation, cv_gsaturation, cv_csaturation, cv_bsaturation, cv_msaturation, @@ -78,10 +81,15 @@ const char *R_GetPalname(UINT16 num); const char *GetPalette(void); extern RGBA_t *pLocalPalette; +extern RGBA_t *pGammaCorrectedPalette; extern UINT8 hudtrans; -void V_CubeApply(UINT8 *red, UINT8 *green, UINT8 *blue); +UINT32 V_GammaCorrect(UINT32 input, double power); +#define V_GammaDecode(input) V_GammaCorrect(input, 2.2f) +#define V_GammaEncode(input) V_GammaCorrect(input, (1/2.2f)) + +void V_CubeApply(RGBA_t *input); // Retrieve the ARGB value from a palette color index #define V_GetColor(color) (pLocalPalette[color&0xFF]) -- 2.54.0 From da67f6feb8e7b5c366a541c5444bba6e35e32cf9 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 25 Oct 2025 22:21:37 +0200 Subject: [PATCH 034/116] rename most "gamma" vars to "brightness" lots of confusion but it does more brightness adjustment than gamma adjustments, yes this does some gamma correction but not user changable global gamma adjustments like globalgamma uhhh --- src/m_menudefs.c | 12 ++--- src/screen.c | 12 ++--- src/v_video.c | 130 +++++++++++++++++++++++------------------------ src/v_video.h | 2 +- 4 files changed, 78 insertions(+), 78 deletions(-) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 5f2d782f5..f1106706a 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -904,37 +904,37 @@ static menuitem_t OP_ColorOptionsMenu[] = {IT_DISABLED, NULL, NULL, NULL, 35}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_rhue, 15}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_rsaturation, 20}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_rgamma, 25}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_rbrightness, 25}, {IT_HEADER, NULL, "Yellow", NULL, 34}, {IT_DISABLED, NULL, NULL, NULL, 73}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_yhue, 40}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_ysaturation, 45}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_ygamma, 50}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_ybrightness, 50}, {IT_HEADER, NULL, "Green", NULL, 59}, {IT_DISABLED, NULL, NULL, NULL, 112}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_ghue, 65}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_gsaturation, 70}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_ggamma, 75}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_gbrightness, 75}, {IT_HEADER, NULL, "Cyan", NULL, 84}, {IT_DISABLED, NULL, NULL, NULL, 255}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_chue, 90}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_csaturation, 95}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_cgamma, 100}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_cbrightness, 100}, {IT_HEADER, NULL, "Blue", NULL, 109}, {IT_DISABLED, NULL, NULL, NULL, 152}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_bhue, 115}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_bsaturation, 120}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_bgamma, 125}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_bbrightness, 125}, {IT_HEADER, NULL, "Magenta", NULL, 134}, {IT_DISABLED, NULL, NULL, NULL, 181}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Hue", &cv_mhue, 140}, {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Saturation", &cv_msaturation, 145}, - {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_mgamma, 150}, + {IT_STRING | IT_CVAR | IT_CV_SLIDER, NULL, "Brightness", &cv_mbrightness, 150}, }; static menuitem_t OP_ExpOptionsMenu[] = diff --git a/src/screen.c b/src/screen.c index 2ef8e664c..cae7d2479 100644 --- a/src/screen.c +++ b/src/screen.c @@ -228,12 +228,12 @@ void SCR_Startup(void) CV_RegisterVar(&cv_bhue); CV_RegisterVar(&cv_mhue); - CV_RegisterVar(&cv_rgamma); - CV_RegisterVar(&cv_ygamma); - CV_RegisterVar(&cv_ggamma); - CV_RegisterVar(&cv_cgamma); - CV_RegisterVar(&cv_bgamma); - CV_RegisterVar(&cv_mgamma); + CV_RegisterVar(&cv_rbrightness); + CV_RegisterVar(&cv_ybrightness); + CV_RegisterVar(&cv_gbrightness); + CV_RegisterVar(&cv_cbrightness); + CV_RegisterVar(&cv_bbrightness); + CV_RegisterVar(&cv_mbrightness); CV_RegisterVar(&cv_rsaturation); CV_RegisterVar(&cv_ysaturation); diff --git a/src/v_video.c b/src/v_video.c index 1045d2b57..90f4fd9f5 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -64,12 +64,12 @@ consvar_t cv_chue = {"chue", "12", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnCha consvar_t cv_bhue = {"bhue", "16", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_mhue = {"mhue", "20", CV_SAVE|CV_CALL, hue_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_rgamma = {"rgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ygamma = {"ygamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_ggamma = {"ggamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_cgamma = {"cgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_bgamma = {"bgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_mgamma = {"mgamma", "0", CV_SAVE|CV_CALL, gamma_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_rbrightness = {"rbrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_ybrightness = {"ybrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_gbrightness = {"gbrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_cbrightness = {"cbrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_bbrightness = {"bbrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_mbrightness = {"mbrightness", "0", CV_SAVE|CV_CALL, brightness_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_rsaturation = {"rsaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ysaturation = {"ysaturation", "10", CV_SAVE|CV_CALL, saturation_cons_t, CV_palette_OnChange, 0, NULL, NULL, 0, 0, NULL}; @@ -134,96 +134,96 @@ static boolean InitCube(void) }; float desatur[3]; // grey - float globalgammamul, globalgammaoffs; - boolean doinggamma; + float globalbrightnessmul, globalbrightnessoffs; + boolean doingbrightness; if (!loaded_config) return false; #define diffcons(cv) (strcmp(cv.string, cv.defaultvalue)) -#define diffconsgamma(cv) (cv.value != 0) +#define diffconsbrightness(cv) (cv.value != 0) #define diffconssat(cv) (cv.value != 10) - doinggamma = diffcons(cv_globalbrightness); + doingbrightness = diffcons(cv_globalbrightness); -#define gammascale 8 - globalgammamul = (cv_globalbrightness.value ? ((255.0f - (gammascale*abs(cv_globalbrightness.value))) / 255.0f) : 1.0f); - globalgammaoffs = ((cv_globalbrightness.value > 0) ? ((gammascale*cv_globalbrightness.value) / 255.0f) : 0.0f); - desatur[0] = desatur[1] = desatur[2] = globalgammaoffs + (0.33f * globalgammamul); +#define brightnessscale 8 + globalbrightnessmul = (cv_globalbrightness.value ? ((255.0f - (brightnessscale*abs(cv_globalbrightness.value))) / 255.0f) : 1.0f); + globalbrightnessoffs = ((cv_globalbrightness.value > 0) ? ((brightnessscale*cv_globalbrightness.value) / 255.0f) : 0.0f); + desatur[0] = desatur[1] = desatur[2] = globalbrightnessoffs + (0.33f * globalbrightnessmul); - if (doinggamma + if (doingbrightness || diffcons(cv_rhue) || diffcons(cv_yhue) || diffcons(cv_ghue) || diffcons(cv_chue) || diffcons(cv_bhue) || diffcons(cv_mhue) - || diffconsgamma(cv_rgamma) - || diffconsgamma(cv_ygamma) - || diffconsgamma(cv_ggamma) - || diffconsgamma(cv_cgamma) - || diffconsgamma(cv_bgamma) - || diffconsgamma(cv_mgamma)) // set the gamma'd/hued positions (saturation is done later) + || diffconsbrightness(cv_rbrightness) + || diffconsbrightness(cv_ybrightness) + || diffconsbrightness(cv_gbrightness) + || diffconsbrightness(cv_cbrightness) + || diffconsbrightness(cv_bbrightness) + || diffconsbrightness(cv_mbrightness)) // set the brightness'd/hued positions (saturation is done later) { - float mod, tempgammamul, tempgammaoffs; + float mod, tempbrightnessmul, tempbrightnessoffs; apply = true; - working[0][0][0][0] = working[0][0][0][1] = working[0][0][0][2] = globalgammaoffs; - working[1][1][1][0] = working[1][1][1][1] = working[1][1][1][2] = globalgammaoffs+globalgammamul; + working[0][0][0][0] = working[0][0][0][1] = working[0][0][0][2] = globalbrightnessoffs; + working[1][1][1][0] = working[1][1][1][1] = working[1][1][1][2] = globalbrightnessoffs+globalbrightnessmul; -#define dohue(hue, gamma, loc) \ - tempgammamul = (gamma ? ((255.0f - (gammascale*abs(gamma)))/255.0f)*globalgammamul : globalgammamul);\ - tempgammaoffs = ((gamma > 0) ? ((gammascale*gamma)/255.0f) + globalgammaoffs : globalgammaoffs);\ - mod = ((hue % huecoloursteps)*(tempgammamul)/huecoloursteps);\ +#define dohue(hue, brightness, loc) \ + tempbrightnessmul = (brightness ? ((255.0f - (brightnessscale*abs(brightness)))/255.0f)*globalbrightnessmul : globalbrightnessmul);\ + tempbrightnessoffs = ((brightness > 0) ? ((brightnessscale*brightness)/255.0f) + globalbrightnessoffs : globalbrightnessoffs);\ + mod = ((hue % huecoloursteps)*(tempbrightnessmul)/huecoloursteps);\ switch (hue/huecoloursteps)\ {\ case 0:\ default:\ - loc[0] = tempgammaoffs+tempgammamul;\ - loc[1] = tempgammaoffs+mod;\ - loc[2] = tempgammaoffs;\ + loc[0] = tempbrightnessoffs+tempbrightnessmul;\ + loc[1] = tempbrightnessoffs+mod;\ + loc[2] = tempbrightnessoffs;\ break;\ case 1:\ - loc[0] = tempgammaoffs+tempgammamul-mod;\ - loc[1] = tempgammaoffs+tempgammamul;\ - loc[2] = tempgammaoffs;\ + loc[0] = tempbrightnessoffs+tempbrightnessmul-mod;\ + loc[1] = tempbrightnessoffs+tempbrightnessmul;\ + loc[2] = tempbrightnessoffs;\ break;\ case 2:\ - loc[0] = tempgammaoffs;\ - loc[1] = tempgammaoffs+tempgammamul;\ - loc[2] = tempgammaoffs+mod;\ + loc[0] = tempbrightnessoffs;\ + loc[1] = tempbrightnessoffs+tempbrightnessmul;\ + loc[2] = tempbrightnessoffs+mod;\ break;\ case 3:\ - loc[0] = tempgammaoffs;\ - loc[1] = tempgammaoffs+tempgammamul-mod;\ - loc[2] = tempgammaoffs+tempgammamul;\ + loc[0] = tempbrightnessoffs;\ + loc[1] = tempbrightnessoffs+tempbrightnessmul-mod;\ + loc[2] = tempbrightnessoffs+tempbrightnessmul;\ break;\ case 4:\ - loc[0] = tempgammaoffs+mod;\ - loc[1] = tempgammaoffs;\ - loc[2] = tempgammaoffs+tempgammamul;\ + loc[0] = tempbrightnessoffs+mod;\ + loc[1] = tempbrightnessoffs;\ + loc[2] = tempbrightnessoffs+tempbrightnessmul;\ break;\ case 5:\ - loc[0] = tempgammaoffs+tempgammamul;\ - loc[1] = tempgammaoffs;\ - loc[2] = tempgammaoffs+tempgammamul-mod;\ + loc[0] = tempbrightnessoffs+tempbrightnessmul;\ + loc[1] = tempbrightnessoffs;\ + loc[2] = tempbrightnessoffs+tempbrightnessmul-mod;\ break;\ } - dohue(cv_rhue.value, cv_rgamma.value, working[1][0][0]); - dohue(cv_yhue.value, cv_ygamma.value, working[1][1][0]); - dohue(cv_ghue.value, cv_ggamma.value, working[0][1][0]); - dohue(cv_chue.value, cv_cgamma.value, working[0][1][1]); - dohue(cv_bhue.value, cv_bgamma.value, working[0][0][1]); - dohue(cv_mhue.value, cv_mgamma.value, working[1][0][1]); + dohue(cv_rhue.value, cv_rbrightness.value, working[1][0][0]); + dohue(cv_yhue.value, cv_ybrightness.value, working[1][1][0]); + dohue(cv_ghue.value, cv_gbrightness.value, working[0][1][0]); + dohue(cv_chue.value, cv_cbrightness.value, working[0][1][1]); + dohue(cv_bhue.value, cv_bbrightness.value, working[0][0][1]); + dohue(cv_mhue.value, cv_mbrightness.value, working[1][0][1]); #undef dohue } #define dosaturation(a, e) a = ((1 - work)*e + work*a) -#define docvsat(cv_sat, hue, gamma, r, g, b) \ +#define docvsat(cv_sat, hue, brightness, r, g, b) \ if diffconssat(cv_sat)\ {\ - float work, mod, tempgammamul, tempgammaoffs;\ + float work, mod, tempbrightnessmul, tempbrightnessoffs;\ apply = true;\ work = (cv_sat.value/10.0f);\ mod = ((hue % huecoloursteps)*(1.0f)/huecoloursteps);\ @@ -231,20 +231,20 @@ static boolean InitCube(void) mod = 2-mod;\ else\ mod += 1;\ - tempgammamul = (gamma ? ((255.0f - (gammascale*abs(gamma)))/255.0f)*globalgammamul : globalgammamul);\ - tempgammaoffs = ((gamma > 0) ? ((gammascale*gamma)/255.0f) + globalgammaoffs : globalgammaoffs);\ + tempbrightnessmul = (brightness ? ((255.0f - (brightnessscale*abs(brightness)))/255.0f)*globalbrightnessmul : globalbrightnessmul);\ + tempbrightnessoffs = ((brightness > 0) ? ((brightnessscale*brightness)/255.0f) + globalbrightnessoffs : globalbrightnessoffs);\ for (q = 0; q < 3; q++)\ - dosaturation(working[r][g][b][q], (tempgammaoffs+(desatur[q]*mod*tempgammamul)));\ + dosaturation(working[r][g][b][q], (tempbrightnessoffs+(desatur[q]*mod*tempbrightnessmul)));\ } - docvsat(cv_rsaturation, cv_rhue.value, cv_rgamma.value, 1, 0, 0); - docvsat(cv_ysaturation, cv_yhue.value, cv_ygamma.value, 1, 1, 0); - docvsat(cv_gsaturation, cv_ghue.value, cv_ggamma.value, 0, 1, 0); - docvsat(cv_csaturation, cv_chue.value, cv_cgamma.value, 0, 1, 1); - docvsat(cv_bsaturation, cv_bhue.value, cv_bgamma.value, 0, 0, 1); - docvsat(cv_msaturation, cv_mhue.value, cv_mgamma.value, 1, 0, 1); + docvsat(cv_rsaturation, cv_rhue.value, cv_rbrightness.value, 1, 0, 0); + docvsat(cv_ysaturation, cv_yhue.value, cv_ybrightness.value, 1, 1, 0); + docvsat(cv_gsaturation, cv_ghue.value, cv_gbrightness.value, 0, 1, 0); + docvsat(cv_csaturation, cv_chue.value, cv_cbrightness.value, 0, 1, 1); + docvsat(cv_bsaturation, cv_bhue.value, cv_bbrightness.value, 0, 0, 1); + docvsat(cv_msaturation, cv_mhue.value, cv_mbrightness.value, 1, 0, 1); -#undef gammascale +#undef brightnessscale if diffconssat(cv_globalsaturation) { @@ -267,7 +267,7 @@ static boolean InitCube(void) #undef dosaturation #undef diffcons -#undef diffconsgamma +#undef diffconsbrightness #undef diffconssat if (!apply) diff --git a/src/v_video.h b/src/v_video.h index ce9337adc..7eea1468c 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -45,7 +45,7 @@ cv_globalgamma, #endif cv_globalbrightness, cv_globalsaturation, cv_rhue, cv_yhue, cv_ghue, cv_chue, cv_bhue, cv_mhue, -cv_rgamma, cv_ygamma, cv_ggamma, cv_cgamma, cv_bgamma, cv_mgamma, +cv_rbrightness, cv_ybrightness, cv_gbrightness, cv_cbrightness, cv_bbrightness, cv_mbrightness, cv_rsaturation, cv_ysaturation, cv_gsaturation, cv_csaturation, cv_bsaturation, cv_msaturation, cv_palette, cv_palettenum; -- 2.54.0 From e26fb91350230a906e18d773d0ad4a91c75b81f1 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 25 Oct 2025 22:32:43 +0200 Subject: [PATCH 035/116] simplify vhs effect interpolation --- src/v_video.c | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/v_video.c b/src/v_video.c index 031971326..9805e910c 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -1739,8 +1739,7 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) void V_DrawVhsEffect(boolean rewind) { - fixed_t uby, dby; - static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; + static fixed_t upbary = 100, downbary = 150; UINT8 barsize, updistort, downdistort; @@ -1761,21 +1760,19 @@ void V_DrawVhsEffect(boolean rewind) 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 << FRACBITS; - if (downbary > vid.height << FRACBITS) - downbary = -barsize*FRACUNIT; + if (upbary < -barsize) + upbary = vid.height; - uby = upbary >> 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 @@ -1795,16 +1792,16 @@ void V_DrawVhsEffect(boolean rewind) thismapstart = normalmapstart; offs = 0; - if (y >= uby && y < uby+barsize) + if (y >= upbary && y < upbary+barsize) { thismapstart -= (2<= dby && y < dby+barsize) + if (y >= downbary && y < downbary+barsize) { thismapstart -= (2< Date: Sun, 26 Oct 2025 02:19:25 +0100 Subject: [PATCH 036/116] fix software hiding the wrong thing in video options --- src/m_menudefs.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index f1106706a..705b85912 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -875,7 +875,10 @@ enum #if defined (__unix__) || defined (UNIXCOMMON) || defined (HAVE_SDL) op_video_fullscreen, #endif +#ifdef BACKWARDSCOMPATCORRECTION op_video_gamma, +#endif + op_video_bright, op_video_sat, op_video_color, op_video_dd, -- 2.54.0 From 548cad76b289dd9a93319b7f0c44912894159d7f Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 26 Oct 2025 14:04:38 +0100 Subject: [PATCH 037/116] drawspan: some type fixes, mark const and reordering --- src/r_draw_column.cpp | 2 +- src/r_draw_span.cpp | 25 +++++++++++-------------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/r_draw_column.cpp b/src/r_draw_column.cpp index 51690fbb0..67dbf94e3 100644 --- a/src/r_draw_column.cpp +++ b/src/r_draw_column.cpp @@ -260,7 +260,7 @@ static void R_DrawColumnTemplate(drawcolumndata_t *dc) // texture has no height, so just go while (--count >= 0) { - *dest = R_DrawColumnPixel(dc, dest, frac>>FRACBITS, source, colormap); + *dest = R_DrawColumnPixel(dc, dest, (frac>>FRACBITS), source, colormap); dest += stride; frac += fracstep; diff --git a/src/r_draw_span.cpp b/src/r_draw_span.cpp index b1870685c..377115b64 100644 --- a/src/r_draw_span.cpp +++ b/src/r_draw_span.cpp @@ -208,15 +208,15 @@ static void R_CalcTiltedLighting(std::vector& lightbuffer, INT32 x1, INT3 for (i = x1; i <= x2; i++) { - fixed_t light = start >> FRACBITS; + const fixed_t light = start >> FRACBITS; lightbuffer[i] = CLAMP(light, 0, MAXLIGHTSCALE - 1); start += step; } } -static void R_GetTiltedLighting(std::vector& tiltlighting, const drawspandata_t* ds, const float iz, const int width, const INT32 stride) +static void R_GetTiltedLighting(std::vector& tiltlighting, const drawspandata_t* ds, const float iz, const INT32 width, const INT32 stride) { - float planelightfloat = PLANELIGHTFLOAT; + const float planelightfloat = PLANELIGHTFLOAT; const fixed_t lightstart = FloatToFixed(iz * planelightfloat); const fixed_t lightend = FloatToFixed((iz + ds->szp.x * width) * planelightfloat); @@ -232,7 +232,7 @@ static void R_GetTiltedLighting(std::vector& tiltlighting, const drawspan template static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) { - int width = ds->x2 - ds->x1; + INT32 width = ds->x2 - ds->x1; float iz, uz, vz; UINT32 u, v; int i; @@ -246,7 +246,6 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) UINT32 stepu, stepv; UINT32 bit; - INT32 x1 = ds->x1; const INT32 nflatxshift = ds->nflatxshift; const INT32 nflatyshift = ds->nflatyshift; const INT32 nflatmask = ds->nflatmask; @@ -300,7 +299,6 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) izstep = ds->szp.x * SPANSIZE; uzstep = ds->sup.x * SPANSIZE; vzstep = ds->svp.x * SPANSIZE; - //x1 = 0; width++; while (width >= SPANSIZE) @@ -317,7 +315,7 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) u = (INT64)(startu); v = (INT64)(startv); - x1 = ds->x1; + const INT32 x1 = ds->x1; for (i = 0; i < SPANSIZE; i++) { @@ -410,7 +408,7 @@ DEFINE_SPAN_COMBO(R_DrawTranslucentWaterSpan, DS_TRANSMAP|DS_RIPPLE) */ void R_DrawFogSpan(drawspandata_t* ds) { - INT32 count = ds->x2 - ds->x1 + 1; + intptr_t count = ds->x2 - ds->x1 + 1; const UINT8 * restrict colormap = ds->colormap; UINT8 * restrict dest = R_Address(ds->x1, ds->y); @@ -435,13 +433,12 @@ void R_DrawFogSpan(drawspandata_t* ds) void R_DrawFogSpan_Tilted(drawspandata_t* ds) { - int width = ds->x2 - ds->x1; - float iz = ds->szp.z + ds->szp.y*(centery-ds->y) + ds->szp.x*(ds->x1-centerx); - UINT8 * restrict dest; - local_for_thread std::vector tiltlighting; - - dest = R_Address(ds->x1, ds->y); + INT32 width = ds->x2 - ds->x1; const INT32 stride = vid.width; + const float iz = ds->szp.z + ds->szp.y*(centery-ds->y) + ds->szp.x*(ds->x1-centerx); + UINT8 * restrict dest = R_Address(ds->x1, ds->y); + + local_for_thread std::vector tiltlighting; // Lighting is simple. It's just linear interpolation from start to end R_GetTiltedLighting(tiltlighting, ds, iz, width, stride); -- 2.54.0 From 056f919bbeae8d068b854c1c1675d3062623dd36 Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 27 Oct 2025 00:50:30 +0100 Subject: [PATCH 038/116] DrawTiltedSpan: more micro optimize - do pointerdiff outside the loops, no need to do them 16 times per span - cache tiltilighting and planezlight, mark as const and restrict --- src/r_draw_span.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/r_draw_span.cpp b/src/r_draw_span.cpp index 377115b64..11415d2d5 100644 --- a/src/r_draw_span.cpp +++ b/src/r_draw_span.cpp @@ -262,6 +262,11 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) const UINT8 * restrict source = ds->source; const UINT8 * restrict colormap = ds->colormap; + const ptrdiff_t colormap_diff = (colormap - colormaps); + + const INT32 * restrict tiltlight = tiltlighting.data(); + lighttable_t * const * restrict planezlight = ds->planezlight; + if constexpr (Type & DS_RIPPLE) { dsrc = vid.screens[1] + (ds->y + ds->bgofs) * stride + ds->x1; @@ -320,7 +325,7 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) for (i = 0; i < SPANSIZE; i++) { bit = (((v + stepv * i) >> nflatyshift) & nflatmask) | ((u + stepu * i) >> nflatxshift); - colormap = ds->planezlight[tiltlighting[x1 + i]] + (ds->colormap - colormaps); + colormap = planezlight[tiltlight[x1 + i]] + colormap_diff; if constexpr (Type & DS_RIPPLE) dest[i] = R_DrawSpanPixel(ds, &dsrc[i], colormap, bit, source); else @@ -343,7 +348,7 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) u = (INT64)(startu); v = (INT64)(startv); bit = ((v >> nflatyshift) & nflatmask) | (u >> nflatxshift); - colormap = ds->planezlight[tiltlighting[ds->x1]] + (ds->colormap - colormaps); + colormap = planezlight[tiltlight[ds->x1]] + colormap_diff; if constexpr (Type & DS_RIPPLE) *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); else @@ -369,7 +374,7 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) for (; width != 0; width--) { bit = ((v >> ds->nflatyshift) & ds->nflatmask) | (u >> ds->nflatxshift); - colormap = ds->planezlight[tiltlighting[ds->x1]] + (ds->colormap - colormaps); + colormap = planezlight[tiltlight[ds->x1]] + colormap_diff; if constexpr (Type & DS_RIPPLE) *dest = R_DrawSpanPixel(ds, dsrc, colormap, bit, source); else @@ -437,15 +442,19 @@ void R_DrawFogSpan_Tilted(drawspandata_t* ds) const INT32 stride = vid.width; const float iz = ds->szp.z + ds->szp.y*(centery-ds->y) + ds->szp.x*(ds->x1-centerx); UINT8 * restrict dest = R_Address(ds->x1, ds->y); + const ptrdiff_t colormap_diff = (ds->colormap - colormaps); local_for_thread std::vector tiltlighting; // Lighting is simple. It's just linear interpolation from start to end R_GetTiltedLighting(tiltlighting, ds, iz, width, stride); + const INT32 * restrict tiltlight = tiltlighting.data(); + lighttable_t * const * restrict planezlight = ds->planezlight; + do { - UINT8 *colormap = ds->planezlight[tiltlighting[ds->x1++]] + (ds->colormap - colormaps); + UINT8 *colormap = planezlight[tiltlight[ds->x1++]] + colormap_diff; *dest = colormap[*dest]; dest++; } -- 2.54.0 From 509e7140e3ba7144832fcf60f06bc49fcfdfb730 Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 27 Oct 2025 21:20:39 +0100 Subject: [PATCH 039/116] use strlcpy for filling playerinfo names MAXPLAYERNAME+1 so it copies 21 and null terminates the last --- src/d_clisrv.c | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 61afc0eb7..a88954867 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -1656,12 +1656,7 @@ static void SV_SendPlayerInfo(INT32 node) netbuffer->u.playerinfo[i].node = i; - // Can't really change this because net compatibility, but the warning is annoying -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstringop-truncation" - strncpy(netbuffer->u.playerinfo[i].name, (const char *)&player_names[i], MAXPLAYERNAME+1); -#pragma GCC diagnostic pop - netbuffer->u.playerinfo[i].name[MAXPLAYERNAME] = '\0'; + strlcpy(netbuffer->u.playerinfo[i].name, (const char *)&player_names[i], MAXPLAYERNAME+1); //fetch IP address //No, don't do that, you fuckface. -- 2.54.0 From 88363cf45d819047f93f9656909620c781e4a206 Mon Sep 17 00:00:00 2001 From: Alug Date: Mon, 27 Oct 2025 22:58:42 +0100 Subject: [PATCH 040/116] add NOHOLEPUNCH flag to disable holepunch entirely --- src/Makefile | 1 + src/Makefile.d/features.mk | 3 ++- src/doomdef.h | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Makefile b/src/Makefile index d7a8345cd..0456990f3 100644 --- a/src/Makefile +++ b/src/Makefile @@ -49,6 +49,7 @@ # Already enabled by default for 32-bit # Windows. # NOCURL=1 - Disable libcurl--HTTP capability. +# NOHOLEPUNCH=1 - Disable holepunch capability. # NOLIBGME=1 - Disable game music emu, retro VGM support. # NOOPENMPT=1 - Disable module (tracker) music support. # NOMIXER=1 - Disable SDL Mixer (audio playback). diff --git a/src/Makefile.d/features.mk b/src/Makefile.d/features.mk index fc1e8b69f..b191ae2c1 100644 --- a/src/Makefile.d/features.mk +++ b/src/Makefile.d/features.mk @@ -6,7 +6,8 @@ passthru_opts+=\ NOHW NOMD5 NOPOSTPROCESSING\ MOBJCONSISTANCY PACKETDROP ZDEBUG\ HAVE_MINIUPNPC\ - HAVE_DISCORDRPC DEVELOP + HAVE_DISCORDRPC DEVELOP\ + NOHOLEPUNCH\ # build with debugging information ifdef DEBUGMODE diff --git a/src/doomdef.h b/src/doomdef.h index 00b4bc1f0..a0c76fa61 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -651,7 +651,9 @@ extern const char *compdate, *comptime, *comprevision, *compbranch; #if defined (HAVE_CURL) #define MASTERSERVER +#ifndef NOHOLEPUNCH #define HOLEPUNCH +#endif #else #undef UPDATE_ALERT #endif -- 2.54.0 From 908bba2c8a3b35a872398600ab6c65452d2785b9 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 28 Oct 2025 00:11:49 +0100 Subject: [PATCH 041/116] rename subsector variable in P_TryCameraMove to be more descriptive --- src/p_map.c | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/src/p_map.c b/src/p_map.c index 9e428d999..c24e338af 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -2189,7 +2189,7 @@ static boolean P_CheckCameraPosition(fixed_t x, fixed_t y, camera_t *thiscam) // boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) { - subsector_t *s; + subsector_t *subsec; UINT8 i; floatok = false; @@ -2198,9 +2198,9 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) return false; if (thiscam->x != x || thiscam->y != y || thiscam->subsector == NULL) - s = R_PointInSubsectorFast(x, y); + subsec = R_PointInSubsectorFast(x, y); else - s = thiscam->subsector; + subsec = thiscam->subsector; if (players[displayplayers[0]].mo) { @@ -2220,7 +2220,7 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) thiscam->ceilingz = thiscam->z + thiscam->height; thiscam->x = x; thiscam->y = y; - thiscam->subsector = s; + thiscam->subsector = subsec; return true; } } @@ -2232,6 +2232,7 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) tryx -= MAXRADIUS; else tryx = x; + if (y-tryy > MAXRADIUS) tryy += MAXRADIUS; else if (y-tryy < -MAXRADIUS) @@ -2249,14 +2250,14 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) if (tmceilingz - thiscam->z < thiscam->height) { - if (s == thiscam->subsector && tmceilingz >= thiscam->z) + if (subsec == thiscam->subsector && tmceilingz >= thiscam->z) { floatok = true; thiscam->floorz = tmfloorz; thiscam->ceilingz = tmfloorz + thiscam->height; thiscam->x = x; thiscam->y = y; - thiscam->subsector = s; + thiscam->subsector = subsec; return true; } else @@ -2281,7 +2282,7 @@ boolean P_TryCameraMove(fixed_t x, fixed_t y, camera_t *thiscam) thiscam->ceilingz = tmceilingz; thiscam->x = x; thiscam->y = y; - thiscam->subsector = s; + thiscam->subsector = subsec; return true; } @@ -2394,6 +2395,7 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) tryx -= radius; else tryx = x; + if (y-tryy > radius) tryy += radius; else if (y-tryy < -radius) @@ -2425,12 +2427,15 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) } if (thing->type == MT_SKIM) + { maxstep = 0; + } if (tmceilingz - tmfloorz < thing->height) { if (tmfloorthing) tmhitthing = tmfloorthing; + return false; // doesn't fit } @@ -2489,10 +2494,14 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) if (thing->eflags & MFE_VERTICALFLIP) { if (tmdrpoffceilz - tmceilingz > maxstep) + { return false; + } } else if (tmfloorz - tmdropoffz > maxstep) + { return false; // don't stand over a dropoff + } } } } while (tryx != x || tryy != y); @@ -2568,6 +2577,7 @@ boolean P_SceneryTryMove(mobj_t *thing, fixed_t x, fixed_t y) tryx = thing->x; tryy = thing->y; + do { if (x-tryx > MAXRADIUS) tryx += MAXRADIUS; @@ -2575,6 +2585,7 @@ boolean P_SceneryTryMove(mobj_t *thing, fixed_t x, fixed_t y) tryx -= MAXRADIUS; else tryx = x; + if (y-tryy > MAXRADIUS) tryy += MAXRADIUS; else if (y-tryy < -MAXRADIUS) @@ -2928,6 +2939,7 @@ static boolean PTR_SlideTraverse(intercept_t *in) { if (P_PointOnLineSide(slidemo->x, slidemo->y, li)) return true; // don't hit the back side + goto isblocking; } @@ -3346,10 +3358,12 @@ void P_BouncePlayerMove(mobj_t *mo) { mobj_t *fx = P_SpawnMobj(mo->x, mo->y, mo->z, MT_BUMP); + if (mo->eflags & MFE_VERTICALFLIP) fx->eflags |= MFE_VERTICALFLIP; else fx->eflags &= ~MFE_VERTICALFLIP; + fx->scale = mo->scale; S_StartSound(mo, sfx_s3k49); @@ -3363,7 +3377,8 @@ void P_BouncePlayerMove(mobj_t *mo) mo->player->cmomx = tmxmove; mo->player->cmomy = tmymove; - if (!P_TryMove(mo, mo->x + tmxmove, mo->y + tmymove, true)) { + if (!P_TryMove(mo, mo->x + tmxmove, mo->y + tmymove, true)) + { P_TryMove(mo, mo->x - oldmomx, mo->y - oldmomy, true); } } @@ -3740,6 +3755,7 @@ boolean P_CheckSector(sector_t *sector, boolean crunch) { size_t i; sector_t *sec; + for (i = 0; i < sector->numattached; i++) { sec = §ors[sector->attached[i]]; @@ -3946,6 +3962,7 @@ static msecnode_t *P_DelSecnode(msecnode_t *node) tp = node->m_sectorlist_prev; tn = node->m_sectorlist_next; + if (tp) tp->m_sectorlist_next = tn; if (tn) @@ -3956,6 +3973,7 @@ static msecnode_t *P_DelSecnode(msecnode_t *node) sp = node->m_thinglist_prev; sn = node->m_thinglist_next; + if (sp) sp->m_thinglist_next = sn; else @@ -4003,7 +4021,7 @@ static inline boolean PIT_GetSectors(line_t *ld) // allowed to move to this position, then the sector_list // will be attached to the Thing's mobj_t at touching_sectorlist. - sector_list = P_AddSecnode(ld->frontsector,tmthing,sector_list); + sector_list = P_AddSecnode(ld->frontsector, tmthing, sector_list); // Don't assume all lines are 2-sided, since some Things // like MT_TFOG are allowed regardless of whether their radius takes -- 2.54.0 From 694a8eeb69f3e8e92d48cdea204599161508bbfd Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 28 Oct 2025 00:47:12 +0100 Subject: [PATCH 042/116] P_TryMove: save one R_PointInSubsector call per player by reusing the special sector calculated earlier, this didnt change for when its checked another time also one fixedmul in P_SceneryTryMove in some cases --- src/p_map.c | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/p_map.c b/src/p_map.c index c24e338af..aea01c6a7 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -2411,19 +2411,22 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) { //All things are affected by their scale. fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); + INT32 special = 0; if (thing->player) { - const INT32 special = GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1); + special = GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1); // If using type Section1:13, double the maxstep. - if (P_PlayerTouchingSectorSpecial(thing->player, 1, 13) - || special == 13) + if (P_PlayerTouchingSectorSpecial(thing->player, 1, 13) || special == 13) + { maxstep <<= 1; + } // If using type Section1:12, no maxstep. For ledges you don't want the player to climb! (see: Egg Zeppelin & SMK port walls) - else if (P_PlayerTouchingSectorSpecial(thing->player, 1, 12) - || special == 12) + else if (P_PlayerTouchingSectorSpecial(thing->player, 1, 12) || special == 12) + { maxstep = 0; + } } if (thing->type == MT_SKIM) @@ -2468,11 +2471,8 @@ boolean P_TryMove(mobj_t *thing, fixed_t x, fixed_t y, boolean allowdropoff) return false; // mobj must lower itself to fit } } - else if (maxstep > 0 && !( - thing->player && ( - P_PlayerTouchingSectorSpecial(thing->player, 1, 14) - || GETSECSPECIAL(R_PointInSubsector(x, y)->sector->special, 1) == 14) - )) // Step down + else if (maxstep > 0 && !(thing->player && + (P_PlayerTouchingSectorSpecial(thing->player, 1, 14) || special == 14))) // Step down { // If the floor difference is MAXSTEPMOVE or less, and the sector isn't Section1:14, ALWAYS // step down! Formerly required a Section1:13 sector for the full MAXSTEPMOVE, but no more. @@ -2598,14 +2598,14 @@ boolean P_SceneryTryMove(mobj_t *thing, fixed_t x, fixed_t y) if (!(thing->flags & MF_NOCLIP)) { - const fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); - if (tmceilingz - tmfloorz < thing->height) return false; // doesn't fit if (tmceilingz - thing->z < thing->height) return false; // mobj must lower itself to fit + const fixed_t maxstep = FixedMul(MAXSTEPMOVE, mapobjectscale); + if (tmfloorz - thing->z > maxstep) return false; // too big a step up } -- 2.54.0 From 45ee50b47d02fd64e64c8f6c2ae475e538ed22e6 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 28 Oct 2025 01:21:26 +0100 Subject: [PATCH 043/116] remove reduntant stuff from D_ClearState and G_StopDemo we only need R_ExecuteSetViewSize from splitscreen_onchange, the rest doesent do anything due to SV_StopServer call earlier setting cl_mode to CL_ABORTED SV_StopServer also calls Y_EndIntermission and Y_EndVote if necessary --- src/d_main.c | 22 +++------------------- src/g_demo.c | 5 ----- 2 files changed, 3 insertions(+), 24 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index d4cef24c3..ca2ffa4f7 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -954,24 +954,6 @@ 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 // @@ -992,7 +974,9 @@ void D_ClearState(void) CL_ClearPlayer(i); splitscreen = 0; - ResetSplitScreen(); // splitscreen onchange resets us to singleplayer :chaosleep: + + // recompute screen size + R_ExecuteSetViewSize(); botingame = false; botskin = 0; diff --git a/src/g_demo.c b/src/g_demo.c index 96ff33e65..bd3905160 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -3494,11 +3494,6 @@ void G_StopDemo(void) demo.rewinding = false; CL_ClearRewinds(); - if (gamestate == GS_INTERMISSION) - Y_EndIntermission(); // cleanup - if (gamestate == GS_VOTING) - Y_EndVote(); - D_ClearState(); } -- 2.54.0 From db2062ed1d3552728741a88a502dfdd357e2f254 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 29 Oct 2025 15:59:25 +0100 Subject: [PATCH 044/116] some i_tcp fixes - SOCK_Get return true when receiving good packet from a lan player - SOCK_GetAddr fix handling of ipv6 addresses, so ipv6 servers can be found in the serverlist taken from srb2/classic --- src/d_net.c | 5 ++--- src/i_tcp.c | 52 ++++++++++++++++++++++++++-------------------------- 2 files changed, 28 insertions(+), 29 deletions(-) diff --git a/src/d_net.c b/src/d_net.c index 05df1320c..61492f2a8 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -1127,9 +1127,7 @@ boolean HGetPacket(void) while (true) { - I_NetGet(); - - if (doomcom->remotenode == -1) // No packet received + if (!I_NetGet()) // No packets received return false; getbytes += packetheaderlength + doomcom->datalength; // For stat @@ -1165,6 +1163,7 @@ boolean HGetPacket(void) GotAcks(); continue; } + doomcom->datalength -= BASEPACKETSIZE; break; } diff --git a/src/i_tcp.c b/src/i_tcp.c index 09cba908f..2690bbc7e 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -28,14 +28,14 @@ #endif #ifdef _WIN32 -#define USE_WINSOCK + #define USE_WINSOCK #endif //WIN32 OS #ifdef USE_WINSOCK -#include -#define addrinfo_t ADDRINFOA + #include + #define addrinfo_t ADDRINFOA #else -#define addrinfo_t struct addrinfo + #define addrinfo_t struct addrinfo #endif #include "doomdef.h" @@ -148,16 +148,16 @@ static UINT8 UPNP_support = TRUE; #define DEFAULTPORT "5029" -#if defined (USE_WINSOCK) -typedef SOCKET SOCKET_TYPE; -#define ERRSOCKET (SOCKET_ERROR) +#ifdef USE_WINSOCK + typedef SOCKET SOCKET_TYPE; + #define ERRSOCKET (SOCKET_ERROR) #else -#if defined (__unix__) || defined (__APPLE__) || defined (__HAIKU__) -typedef int SOCKET_TYPE; -#else -typedef unsigned long SOCKET_TYPE; -#endif -#define ERRSOCKET (-1) + #if defined (__unix__) || defined (__APPLE__) || defined (__HAIKU__) + typedef int SOCKET_TYPE; + #else + typedef unsigned long SOCKET_TYPE; + #endif + #define ERRSOCKET (-1) #endif #define IPV6_MULTICAST_ADDRESS "ff15::57e1:1a12" @@ -345,17 +345,15 @@ 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_IPV6 int v6 = (sk->any.sa_family == AF_INET6); #else int v6 = 0; #endif - void *addr; int e = 0; // save error code so it can't be modified later code and avoid calling WSAGetLastError() more then once - if(sk->any.sa_family == AF_INET) + if (sk->any.sa_family == AF_INET) addr = &sk->ip4.sin_addr; #ifdef HAVE_IPV6 else if(sk->any.sa_family == AF_INET6) @@ -364,9 +362,11 @@ static const char *SOCK_AddrToStr(mysockaddr_t *sk) else addr = NULL; - if(addr == NULL) + if (addr == NULL) + { sprintf(s, "No address"); - else if(inet_ntop(sk->any.sa_family, addr, &s[v6], sizeof (s) - v6) == NULL) + } + else if (inet_ntop(sk->any.sa_family, addr, &s[v6], sizeof (s) - v6) == NULL) { e = errno; sprintf(s, "Unknown family type, error #%u: %s", e, strerror(e)); @@ -381,7 +381,7 @@ static const char *SOCK_AddrToStr(mysockaddr_t *sk) strcat(s, va(":%d", ntohs(sk->ip6.sin6_port))); } #endif - else if(sk->any.sa_family == AF_INET && sk->ip4.sin_port != 0) + else if (sk->any.sa_family == AF_INET && sk->ip4.sin_port != 0) strcat(s, va(":%d", ntohs(sk->ip4.sin_port))); return s; @@ -481,7 +481,6 @@ static boolean SOCK_cmpaddr(mysockaddr_t *a, mysockaddr_t *b, UINT8 mask) return false; } - // This is a hack. For some reason, nodes aren't being freed properly. // This goes through and cleans up what nodes were supposed to be freed. /** \warning This function causes the file downloading to stop if someone joins. @@ -636,7 +635,7 @@ static boolean SOCK_Get(void) c = recvfrom(mysockets[n], (char *)&doomcom->data, MAXPACKETLENGTH, 0, (void *)&fromaddress, &fromlen); - if (c > 0) + if (c != ERRSOCKET) { #ifdef USE_STUN if (STUN_got_response(doomcom->data, c)) @@ -652,20 +651,21 @@ static boolean SOCK_Get(void) #endif // find remote node number - for (j = 1; j <= MAXNETNODES; j++) //include LAN + for (j = 1; j <= MAXNETNODES; j++) // include LAN { if (SOCK_cmpaddr(&fromaddress, &clientaddress[j], 0)) { doomcom->remotenode = (INT16)j; // good packet from a game player doomcom->datalength = (INT16)c; nodesocket[j] = mysockets[n]; - return false; + return true; } } // not found // find a free slot j = getfreenode(); + if (j > 0) { const time_t curTime = time(NULL); @@ -1269,7 +1269,7 @@ void I_ShutdownTcpDriver(void) init_tcp_driver = false; } -static boolean SOCK_GetAddr(struct sockaddr_in *sin, const char *address, const char *port, boolean test) +static boolean SOCK_GetAddr(mysockaddr_t *sin, const char *address, const char *port, boolean test) { addrinfo_t *ai = NULL, *runp, hints; int gaie; @@ -1330,7 +1330,7 @@ static SINT8 SOCK_NetMakeNodewPort(const char *address, const char *port) if (newnode != -1) { - if (!SOCK_GetAddr(&clientaddress[newnode].ip4, address, port, true)) + if (!SOCK_GetAddr(&clientaddress[newnode], address, port, true)) { nodeconnected[newnode] = false; return -1; @@ -1358,7 +1358,7 @@ static void rendezvous(int size) if (tic != refreshtic) { - if (SOCK_GetAddr(&rzv.ip4, host, (port ? port : "7777"), false)) + if (SOCK_GetAddr(&rzv, host, (port ? port : "7777"), false)) { refreshtic = tic; } -- 2.54.0 From cb5c4e482e95e646c68fd0ab80f8a00e4371199c Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 29 Oct 2025 16:24:44 +0100 Subject: [PATCH 045/116] SOCK_GetAddr: freeaddrinfo does not need to be called on getaddrinfo failure --- src/i_tcp.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/i_tcp.c b/src/i_tcp.c index 2690bbc7e..18c20dd5d 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -1271,7 +1271,7 @@ void I_ShutdownTcpDriver(void) static boolean SOCK_GetAddr(mysockaddr_t *sin, const char *address, const char *port, boolean test) { - addrinfo_t *ai = NULL, *runp, hints; + addrinfo_t *ai, *runp, hints; int gaie; size_t i; @@ -1287,10 +1287,7 @@ static boolean SOCK_GetAddr(mysockaddr_t *sin, const char *address, const char * gaie = getaddrinfo(address, port, &hints, &ai); if (gaie != 0) - { - freeaddrinfo(ai); return false; - } runp = ai; -- 2.54.0 From 129f88b6a779b9e618a1c9ac8f82f8015bd44606 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustaf=20Alh=C3=A4ll?= Date: Tue, 28 Oct 2025 23:01:02 +0100 Subject: [PATCH 046/116] Fix buffer underflow when querying invalid nodes --- src/i_tcp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/i_tcp.c b/src/i_tcp.c index 18c20dd5d..b58c134c1 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -752,7 +752,7 @@ static void SOCK_Send(void) int e = 0; // save error code so it can't be modified later code and avoid calling WSAGetLastError() more then once size_t i, j; - if (!nodeconnected[doomcom->remotenode]) + if (doomcom->remotenode < 0 || !nodeconnected[doomcom->remotenode]) return; if (doomcom->remotenode == BROADCASTADDR) -- 2.54.0 From 24895874ed840a0a5a52d8a31fb143994d976854 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 29 Oct 2025 22:53:09 +0100 Subject: [PATCH 047/116] UDP_Bind: check socket send buffer size aswell if to small than adjust, like receive buffer --- src/i_tcp.c | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/src/i_tcp.c b/src/i_tcp.c index b58c134c1..531db4ab9 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -970,7 +970,7 @@ static SOCKET_TYPE UDP_Bind(int family, struct sockaddr *addr, socklen_t addrlen e = errno; I_OutputMsg("getting SO_RCVBUF failed: #%u, %s\n", e, strerror(e)); } - CONS_Printf(M_GetText("Network system buffer: %dKb\n"), opt>>10); + CONS_Printf(M_GetText("Network receive buffer: %dKb\n"), opt>>10); if (opt < 64<<10) // 64k { @@ -991,9 +991,44 @@ static SOCKET_TYPE UDP_Bind(int family, struct sockaddr *addr, socklen_t addrlen } if (opt < 64<<10) - CONS_Alert(CONS_WARNING, M_GetText("Can't set buffer length to 64k, file transfer will be bad\n")); + CONS_Alert(CONS_WARNING, M_GetText("Can't set receive buffer length to 64k, file transfer will be bad\n")); else - CONS_Printf(M_GetText("Network system buffer set to: %dKb\n"), opt>>10); + CONS_Printf(M_GetText("Network receive buffer set to: %dKb\n"), opt>>10); + } + + opt = 0; + opts = (socklen_t)sizeof(opt); + rc = getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&opt, &opts); + if (rc <= -1) + { + e = errno; + I_OutputMsg("getting SO_SNDBUF failed: #%u, %s\n", e, strerror(e)); + } + CONS_Printf(M_GetText("Network send buffer: %dKb\n"), opt>>10); + + if (opt < 64<<10) // 64k + { + opt = 64<<10; + opts = (socklen_t)sizeof(opt); + rc = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&opt, opts); + if (rc <= -1) + { + e = errno; + I_OutputMsg("setting SO_SNDBUF to %dKb failed: #%u, %s\n", opt>>10, e, strerror(e)); + } + + opt = 0; + rc = getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&opt, &opts); + if (rc <= -1) + { + e = errno; + I_OutputMsg("getting SO_SNDBUF failed: #%u, %s\n", e, strerror(e)); + } + + if (opt < 64<<10) + CONS_Alert(CONS_WARNING, M_GetText("Can't set send buffer length to 64k, file transfer will be bad\n")); + else + CONS_Printf(M_GetText("Network send system buffer set to: %dKb\n"), opt>>10); } rc = getsockname(s, &straddr.any, &len); -- 2.54.0 From f34a47c50d9554318ba992da779537dbdd08e30d Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 31 Oct 2025 02:01:30 +0100 Subject: [PATCH 048/116] HWR_PrecacheLevelFlats: only run flat encore case when having an "encoremap" not when its just encore mode might save some time on some maps, as we dont need to check for remapping --- src/hardware/hw_cache.c | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index edbd83b77..339cce3f9 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -603,7 +603,7 @@ static void HWR_PrecacheLevelFlats(void) // special case for encore #ifdef GLENCORE - if (encoremode) + if (encoremap) { // go through all sectors to determine if it should be remapped for encore for (i = 0; i < numsectors; i++) @@ -678,8 +678,6 @@ static void HWR_PrecacheLevelTextures(void) const line_t *line = &lines[i]; #ifdef GLENCORE const int noencoremap = ((encoremap && (line->flags & ML_TFERLINE)) ? 2 : 1); -#else - const int noencoremap = 1; #endif // two sides for (j = 0; j < 2; j++) @@ -695,11 +693,14 @@ static void HWR_PrecacheLevelTextures(void) for (f = 0; f < 3; f++) { const INT32 texnum = sidetex[f]; + if (texnum < 0 || texnum >= numtextures || texturepresent[texnum]) continue; - +#ifdef GLENCORE texturepresent[texnum] = 1|noencoremap; - +#else + texturepresent[texnum] = 1; +#endif HWR_GetTexture(texnum, false); #ifdef GLENCORE if (noencoremap & 2) -- 2.54.0 From 36c43d89e6454dc05078bd77ab551758e894b6fe Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 31 Oct 2025 02:20:53 +0100 Subject: [PATCH 049/116] GL encore: use struct for encore texture handling struct with two sets of maptextures, one for normal another for encore textures functionally identical, hopefully also performancewise more explicit than doing this with just one set and indexing stuff :bloblcatpats: --- src/hardware/hw_cache.c | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index 339cce3f9..e58169e14 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -437,8 +437,16 @@ void HWR_MakePatch(const patch_t *patch, GLPatch_t *glPatch, GLMipmap_t *glMipma // CACHING HANDLING // ================================================= +typedef struct +{ + GLMapTexture_t normal; +#ifdef GLENCORE + GLMapTexture_t encore; +#endif +} GLMapTextureSet_t; // idk i suck at naming things + static size_t gl_numtextures = 0; // Texture count -static GLMapTexture_t *gl_textures; // For all textures +static GLMapTextureSet_t *gl_textures; // For all textures static void HWR_FreeTextureData(patch_t *patch) { @@ -578,13 +586,12 @@ void HWR_FreeMapTextures(void) { size_t i; -#ifdef GLENCORE - for (i = 0; i < gl_numtextures*2; i++) -#else for (i = 0; i < gl_numtextures; i++) -#endif { - FreeMapTexture(&gl_textures[i]); + FreeMapTexture(&gl_textures[i].normal); +#ifdef GLENCORE + FreeMapTexture(&gl_textures[i].encore); +#endif } // now the heap don't have any 'user' pointing to our @@ -824,11 +831,8 @@ void HWR_LoadMapTextures(size_t pnumtextures) HWR_FreeMapTextures(); gl_numtextures = pnumtextures; -#ifdef GLENCORE - gl_textures = calloc(gl_numtextures, sizeof (*gl_textures)*2); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore) -#else - gl_textures = calloc(gl_numtextures, sizeof (*gl_textures)); -#endif + gl_textures = calloc(gl_numtextures, sizeof(*gl_textures)); // *2 - 1 for encore-remapped texture and another for noencore texture (unused when not in encore), see: GLMapTextureSet_t + if (gl_textures == NULL) I_Error("HWR_LoadMapTextures: ran out of memory for OpenGL textures. Sad!"); } @@ -852,7 +856,7 @@ GLMapTexture_t *HWR_GetTexture(INT32 tex, boolean noencore) // Every texture in memory, stored in the // hardware renderer's bit depth format. Wow! #ifdef GLENCORE - gltex = &gl_textures[tex*2 + (encoremap && !noencore ? 0 : 1)]; + gltex = (encoremap && !noencore) ? &gl_textures[tex].encore : &gl_textures[tex].normal; #else gltex = &gl_textures[tex]; #endif -- 2.54.0 From e45c72f5253b3b14d5f6174caacbbaa011564dca Mon Sep 17 00:00:00 2001 From: toaster Date: Sun, 5 Nov 2023 18:50:33 +0000 Subject: [PATCH 050/116] SV_StopServer: Use G_SetGamestate instead of a direct write An apparent oversight identified while working on the previous commit. --- src/d_clisrv.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index a88954867..ef4112018 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4649,7 +4649,9 @@ void SV_StopServer(void) Y_EndIntermission(); if (gamestate == GS_VOTING) Y_EndVote(); - gamestate = wipegamestate = GS_NULL; + + G_SetGamestate(GS_NULL); + wipegamestate = GS_NULL; for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) localtextcmd[i][0] = 0; -- 2.54.0 From 03de30df3e2b10ba072c50f3c7622738e2958d06 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 03:00:19 +0100 Subject: [PATCH 051/116] SV_StopServer: reset textcmdbuf fixes an issue where in some rare cases, the game may get stuck in a weird limbo state due to the text command buffer being full and never be cleared, so net commands can never be executed --- src/d_clisrv.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index ef4112018..aed5ee347 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -4654,8 +4654,17 @@ void SV_StopServer(void) wipegamestate = GS_NULL; for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { localtextcmd[i][0] = 0; + while (textcmdbuf[i] != NULL) + { + textcmdbuf_t *buf = textcmdbuf[i]; + textcmdbuf[i] = textcmdbuf[i]->next; + Z_Free(buf); + } + } + for (i = firstticstosend; i < firstticstosend + BACKUPTICS; i++) D_Clearticcmd(i); -- 2.54.0 From ae306351ba469682f345339e74922bbc2dd1bec8 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 16:25:43 +0100 Subject: [PATCH 052/116] add cv_precachetextures to advanced video options --- src/m_menudefs.c | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 6bda9c733..6633085bf 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -944,21 +944,23 @@ static menuitem_t OP_ExpOptionsMenu[] = {IT_STRING | IT_CVAR, NULL, "Skyboxes", &cv_skybox, 40}, - {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 50}, + {IT_STRING | IT_CVAR, NULL, "Precache Level Textures", &cv_precachetextures, 50}, - {IT_STRING | IT_CVAR, NULL, "Frameskip", &cv_frameskip, 60}, + {IT_STRING | IT_CVAR, NULL, "FPS counter sampling", &cv_accuratefps, 60}, - {IT_STRING | IT_CVAR, NULL, "Votescreen Scaling", &cv_votebgscaling, 70}, + {IT_STRING | IT_CVAR, NULL, "Frameskip", &cv_frameskip, 70}, + + {IT_STRING | IT_CVAR, NULL, "Votescreen Scaling", &cv_votebgscaling, 80}, #ifdef HWRENDER - {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 80}, + {IT_STRING | IT_CVAR, NULL, "Screen Textures", &cv_glscreentextures, 90}, #ifdef USE_FBO_OGL - {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 85}, - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 95}, - {IT_DISABLED, NULL, "", NULL, 105}, // dummy text + {IT_STRING | IT_CVAR, NULL, "FBO Downsampling support", &cv_glframebuffer, 95}, + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 105}, + {IT_DISABLED, NULL, "", NULL, 115}, // dummy text #else - {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 90}, - {IT_DISABLED, NULL, "", NULL, 100}, // dummy text + {IT_STRING | IT_CVAR, NULL, "Palette Depth", &cv_glpalettedepth, 100}, + {IT_DISABLED, NULL, "", NULL, 110}, // dummy text #endif #endif }; @@ -971,6 +973,7 @@ static const char* OP_ExpTooltips[] = "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.", + "Preload all level textures on level load.\nMassively reduces texture related stuttering during gameplay\nat the cost of longer level loading times.\nDisable this if you experience timeouts during level switches.", "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.", @@ -991,6 +994,7 @@ enum op_exp_secbright, //op_exp_dirlight, op_exp_skybox, + op_exp_texcache, op_exp_accuratefps, op_exp_frameskip, op_exp_votescrn, -- 2.54.0 From feff5a7c17487681b0a1680ebdb4d105303e70b3 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 16:32:04 +0100 Subject: [PATCH 053/116] make a toggle for using angleturn in replays while this is more accurate to how the player experienced stuff in the actual game, this also can be somewhat jittery and stuttery depending on the net conditions the replay was recorded in, so make this toggable if someone wants it --- src/d_netcmd.c | 5 +++++ src/d_netcmd.h | 2 ++ src/p_user.c | 2 +- 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 92d9fb935..86c9b12b1 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -292,6 +292,10 @@ consvar_t cv_mouseturn = {"mouseturn", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, // Lagless camera! Yay! consvar_t cv_laglesscam = {"lagless_camera", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +// makes the camera use the saved angleturn in replays instead of the players angle +// more accurate to how the recording player seen things in game, but may be jittery if they encountered net issues +consvar_t cv_demoangturn = {"useangleturninreplays", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; + consvar_t cv_verticallook[MAXSPLITSCREENPLAYERS] = { {"verticallook", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, {"verticallook2", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}, @@ -1043,6 +1047,7 @@ void D_RegisterClientCommands(void) CV_RegisterVar(&cv_betainterscreen); CV_RegisterVar(&cv_laglesscam); + CV_RegisterVar(&cv_demoangturn); for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { diff --git a/src/d_netcmd.h b/src/d_netcmd.h index 52f777e2b..6b7382403 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -209,6 +209,8 @@ extern consvar_t cv_betainterscreen; extern consvar_t cv_laglesscam; +extern consvar_t cv_demoangturn; + typedef enum { SKINMENUTYPE_SCROLL = 0, diff --git a/src/p_user.c b/src/p_user.c index b99998844..5ccc43f0a 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -3824,7 +3824,7 @@ boolean P_MoveChaseCamera(player_t *player, camera_t *thiscam, boolean resetcall // 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) + if (cv_demoangturn.value && leveltime > starttime) focusangle = player->cmd.angleturn << 16; else focusangle = mo->angle; // Just use something known sane. -- 2.54.0 From c428472c6f919f1981c52b81b1ad262b72676e56 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 16:12:05 +0100 Subject: [PATCH 054/116] dont precache anything ever in HWR_PrecacheLevel if disabled before some cvar callbacks called this unconditionally --- src/hardware/hw_cache.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index e58169e14..1a09ee33f 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -812,7 +812,7 @@ static void HWR_PrecacheLevelSprites(void) void HWR_PrecacheLevel(void) { - if (gamestate != GS_LEVEL) + if (gamestate != GS_LEVEL || !cv_precachetextures.value) return; // Precache flats. -- 2.54.0 From 456a380e3a975311ecfbc898635a17232e12e8f3 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 15:39:21 +0100 Subject: [PATCH 055/116] HWR_PrecacheLevel: disable sprite precaching in some cases this may lead to crashes, its mostly useless in gl eitherway due to how colourmapped sprites work --- src/hardware/hw_cache.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index 1a09ee33f..4d9fdb54c 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -745,7 +745,7 @@ static void HWR_PrecacheLevelTextures(void) free(texturepresent); } -static void HWR_PrecacheLevelSprites(void) +/*static void HWR_PrecacheLevelSprites(void) { patch_t *spritepatch; char *spritepresent; @@ -808,7 +808,7 @@ static void HWR_PrecacheLevelSprites(void) } } free(spritepresent); -} +}*/ void HWR_PrecacheLevel(void) { @@ -822,7 +822,7 @@ void HWR_PrecacheLevel(void) HWR_PrecacheLevelTextures(); // Precache sprites. - HWR_PrecacheLevelSprites(); + //HWR_PrecacheLevelSprites(); } void HWR_LoadMapTextures(size_t pnumtextures) -- 2.54.0 From eaee95a026244cc793cd8c6eb60adee9b0cb8cb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustaf=20Alh=C3=A4ll?= Date: Tue, 29 Jul 2025 13:10:44 +0200 Subject: [PATCH 056/116] Add -workdir --- src/d_main.c | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index ca2ffa4f7..50b3330e9 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1721,8 +1721,14 @@ void D_SRB2Main(void) else { // use user specific config file + if (M_CheckParm("-workdir") && M_IsNextParm()) + snprintf(srb2home, sizeof srb2home, "%s", M_GetNextParm()); + else #ifdef DEFAULTDIR - snprintf(srb2home, sizeof srb2home, "%s" PATHSEP DEFAULTDIR, userhome); + snprintf(srb2home, sizeof srb2home, "%s" PATHSEP DEFAULTDIR, userhome); +#else // DEFAULTDIR + snprintf(srb2home, sizeof srb2home, "%s", userhome); +#endif // DEFAULTDIR snprintf(downloaddir, sizeof downloaddir, "%s" PATHSEP "DOWNLOAD", srb2home); if (dedicated) snprintf(configfile, sizeof configfile, "%s" PATHSEP "d"CONFIGFILENAME, srb2home); @@ -1731,17 +1737,6 @@ void D_SRB2Main(void) // can't use sprintf since there is %u in savegamename strcatbf(savegamename, srb2home, PATHSEP); -#else - snprintf(srb2home, sizeof srb2home, "%s", userhome); - snprintf(downloaddir, sizeof downloaddir, "%s", userhome); - if (dedicated) - snprintf(configfile, sizeof configfile, "%s" PATHSEP "d"CONFIGFILENAME, userhome); - else - snprintf(configfile, sizeof configfile, "%s" PATHSEP CONFIGFILENAME, userhome); - - // can't use sprintf since there is %u in savegamename - strcatbf(savegamename, userhome, PATHSEP); -#endif } configfile[sizeof configfile - 1] = '\0'; @@ -1767,6 +1762,9 @@ void D_SRB2Main(void) } } + // make sure workdir exists + I_mkdir(srb2home, 0755); + // Create addons dir snprintf(addonsdir, sizeof addonsdir, "%s%s%s", srb2home, PATHSEP, "addons"); I_mkdir(addonsdir, 0755); -- 2.54.0 From 908e07362872c132ebb4c8360d318194ef37918c Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 18:28:47 +0100 Subject: [PATCH 057/116] removed unused autoload variables M_ConnectMenuModChecks been checking an uninitialized bool the whole time Zzz... --- src/d_main.c | 10 ++++------ src/d_main.h | 2 -- src/m_menu.c | 4 ++-- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 50b3330e9..1f425a468 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -102,10 +102,8 @@ static char *startuppwads[MAX_WADFILES]; // autoloading static char *autoloadwadfiles[MAX_WADFILES]; static char *autoloadwadfilespost[MAX_WADFILES]; -boolean autoloading; -boolean autoloaded; +static boolean autoloaded = false; boolean postautoloaded = false; -boolean wasautoloaded = false; // boolean devparm = false; // started game with -devparm @@ -1158,7 +1156,7 @@ static void D_FindAddonsToAutoload(void) // If the file is found, run our shit if (!autoloadconfigfile) // nope outta here { - wasautoloaded = postautoloaded = true; // so D_AddAutoloadFiles can skip everything since nothings there to autoload + autoloaded = postautoloaded = true; // so D_AddAutoloadFiles can skip everything since nothings there to autoload return; } @@ -1206,7 +1204,7 @@ static void D_FindAddonsToAutoload(void) static void D_AddAutoloadFiles(void) { - if (wasautoloaded) + if (autoloaded) return; CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); @@ -1214,7 +1212,7 @@ static void D_AddAutoloadFiles(void) CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); D_CleanFile(autoloadwadfiles); - wasautoloaded = true; + autoloaded = true; } void D_AddPostloadFiles(void) diff --git a/src/d_main.h b/src/d_main.h index 86c79a63c..deeca4c07 100644 --- a/src/d_main.h +++ b/src/d_main.h @@ -61,8 +61,6 @@ extern boolean minilighticon; // mkwii-style minimap headlight // // autoload stuff -extern boolean autoloading; -extern boolean autoloaded; extern boolean postautoloaded; void D_AddPostloadFiles(void); diff --git a/src/m_menu.c b/src/m_menu.c index 6eaccdce0..49398df34 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -6956,9 +6956,9 @@ static void M_ConnectMenuModChecks(INT32 choice) (void)choice; // okay never mind we want to COMMUNICATE to the player pre-emptively instead of letting them try and then get confused when it doesn't work - if (modifiedgame || autoloaded) + if (modifiedgame) { - M_StartMessage(M_GetText("You have addons loaded.\nYou won't be able to join netgames!\n\nTo play online, restart the game\nand don't load any addons.\nSRB2Kart will automatically add\neverything you need when you join.\n\n(Press a key)\n"),M_ConnectMenu,MM_EVENTHANDLER); + M_StartMessage("You have addons loaded.\nYou won't be able to join netgames!\n\nTo play online, restart the game\nand don't load any addons.\nSRB2Kart will automatically add\neverything you need when you join.\n\n(Press a key)\n", M_ConnectMenu, MM_EVENTHANDLER); return; } -- 2.54.0 From de73c536658a8f3b479ba5123967f0f42418128d Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 19:20:04 +0100 Subject: [PATCH 058/116] optimize addon autoload handling --- src/d_main.c | 73 ++++++++++++++++++++++++++++++++++------------------ 1 file changed, 48 insertions(+), 25 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 1f425a468..1fde58a7b 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -102,6 +102,8 @@ static char *startuppwads[MAX_WADFILES]; // autoloading static char *autoloadwadfiles[MAX_WADFILES]; static char *autoloadwadfilespost[MAX_WADFILES]; +static size_t autoloadcount = 0; +static size_t postloadcount = 0; static boolean autoloaded = false; boolean postautoloaded = false; // @@ -1057,6 +1059,7 @@ static void D_AddFile(const char *file, char **filearray) static void D_CleanFile(char **filearray) { size_t pnumwadfiles; + for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) { free(filearray[pnumwadfiles]); @@ -1064,6 +1067,17 @@ static void D_CleanFile(char **filearray) } } +static void D_CleanAutoloadFile(char **filearray, size_t count) +{ + size_t i; + + for (i = 0; i < count; i++) + { + free(filearray[i]); + filearray[i] = NULL; + } +} + // Taken from TSoURDt3rd // https://github.com/StarManiaKG/The-Story-of-Uncapped-Revengence-Discord-the-3rd/blob/main/src/STAR/star_functions.c static INT32 D_DetectFileType(const char* filename) @@ -1092,9 +1106,8 @@ static INT32 D_DetectFileType(const char* filename) } // autoload that shit -static void D_AutoloadFile(const char *file, char **filearray) +static void D_AutoloadFile(const char *file, char **filearray, size_t count) { - size_t pnumwadfiles; char *newfile; INT32 fileType = D_DetectFileType(file); @@ -1104,9 +1117,6 @@ static void D_AutoloadFile(const char *file, char **filearray) return; } - for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) - ; - if (fileType <= 6) { newfile = malloc(strlen(file) + 1); @@ -1114,7 +1124,7 @@ static void D_AutoloadFile(const char *file, char **filearray) I_Error("No more free memory to AutoloadFile %s",file); strcpy(newfile, file); - filearray[pnumwadfiles] = newfile; + filearray[count] = newfile; } else { @@ -1144,13 +1154,14 @@ static void D_FindAddonsToAutoload(void) { FILE *autoloadconfigfile; const char *autoloadpath; + char *newline; + boolean postload; - INT32 i; char wadsToAutoload[256] = ""; // does it exist tho - autoloadpath = va("%s"PATHSEP"%s",srb2home,AUTOLOADCONFIGFILENAME); + autoloadpath = va("%s"PATHSEP"%s", srb2home, AUTOLOADCONFIGFILENAME); autoloadconfigfile = fopen(autoloadpath, "r"); // If the file is found, run our shit @@ -1160,26 +1171,27 @@ static void D_FindAddonsToAutoload(void) return; } - while (fgets(wadsToAutoload, sizeof wadsToAutoload, autoloadconfigfile) != NULL) + while (fgets(wadsToAutoload, sizeof(wadsToAutoload), autoloadconfigfile) != NULL) { postload = false; + // skip if commented or empty - if ((wadsToAutoload[1] == '\0' || wadsToAutoload[1] == '\n') - || (wadsToAutoload[0] == '#')) + if (wadsToAutoload[0] == '\n' || + wadsToAutoload[0] == '#' || + wadsToAutoload[0] == '\0') continue; + // this marks it so that it loads after loading server addons - else if (fastncmp(wadsToAutoload, "postload ", 9)) + if (fastncmp(wadsToAutoload, "postload ", 9)) { strremove(wadsToAutoload, "postload "); postload = true; } // Remove Any Empty or Skipped Lines - for (i = 0; wadsToAutoload[i] != '\0'; i++) - { - if (wadsToAutoload[i] == '\n') - wadsToAutoload[i] = '\0'; - } + newline = strchr(wadsToAutoload, '\n'); + if (newline) + *newline = '\0'; if (!postload && W_CheckPostLoadList(wadsToAutoload)) { @@ -1189,15 +1201,20 @@ static void D_FindAddonsToAutoload(void) // LOAD IT if (!postload) - D_AutoloadFile(wadsToAutoload, autoloadwadfiles); + { + D_AutoloadFile(wadsToAutoload, autoloadwadfiles, autoloadcount); + autoloadcount++; + } else - D_AutoloadFile(wadsToAutoload, autoloadwadfilespost); - - // end it here - for (i = 0; wadsToAutoload[i] != '\0'; i++) - wadsToAutoload[i] = '\0'; + { + D_AutoloadFile(wadsToAutoload, autoloadwadfilespost, postloadcount); + postloadcount++; + } } + autoloadwadfiles[autoloadcount] = NULL; + autoloadwadfilespost[postloadcount] = NULL; + // we dont want memory leaks around here do we? fclose(autoloadconfigfile); } @@ -1208,10 +1225,13 @@ static void D_AddAutoloadFiles(void) return; CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfiles); + D_CleanAutoloadFile(autoloadwadfiles, autoloadcount); + + autoloadcount = 0; autoloaded = true; } @@ -1221,10 +1241,13 @@ void D_AddPostloadFiles(void) return; CONS_Printf("D_AddPostloadFiles(): Loading postloaded addons...\n"); + if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) CONS_Printf("D_AddPostloadFiles(): Are you sure you put in valid files or what?\n"); - D_CleanFile(autoloadwadfilespost); + D_CleanAutoloadFile(autoloadwadfilespost, postloadcount); + + postloadcount = 0; postautoloaded = true; } -- 2.54.0 From c0f24ebbbcdacde32f0753ba4a7bee6a247561c6 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 19:36:28 +0100 Subject: [PATCH 059/116] postautoloaded can be static not used outside of d_main --- src/d_main.c | 2 +- src/d_main.h | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 1fde58a7b..f3b2486c8 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -105,7 +105,7 @@ static char *autoloadwadfilespost[MAX_WADFILES]; static size_t autoloadcount = 0; static size_t postloadcount = 0; static boolean autoloaded = false; -boolean postautoloaded = false; +static boolean postautoloaded = false; // boolean devparm = false; // started game with -devparm diff --git a/src/d_main.h b/src/d_main.h index deeca4c07..d9954a5b0 100644 --- a/src/d_main.h +++ b/src/d_main.h @@ -61,7 +61,6 @@ extern boolean minilighticon; // mkwii-style minimap headlight // // autoload stuff -extern boolean postautoloaded; void D_AddPostloadFiles(void); // the infinite loop of D_SRB2Loop() called from win_main for windows version -- 2.54.0 From 42b1f849c030e35f5db44b905e4a808920f0ca3d Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 20:00:43 +0100 Subject: [PATCH 060/116] cleanup and optimize startup wad handling --- src/d_main.c | 102 ++++++++++++++++++++++++--------------------------- 1 file changed, 47 insertions(+), 55 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index f3b2486c8..b7704318b 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -97,7 +97,9 @@ UINT8 window_notinfocus = false; static char *startupiwadfiles[MAX_WADFILES]; +static size_t startupiwadcount = 0; static char *startuppwads[MAX_WADFILES]; +static size_t startuppwadcount = 0; // autoloading static char *autoloadwadfiles[MAX_WADFILES]; @@ -1038,14 +1040,10 @@ void D_StartTitle(void) // // D_AddFile // -static void D_AddFile(const char *file, char **filearray) +static void D_AddFile(const char *file, char **filearray, size_t count) { - size_t pnumwadfiles; char *newfile; - for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) - ; - newfile = malloc(strlen(file) + 1); if (!newfile) { @@ -1053,21 +1051,10 @@ static void D_AddFile(const char *file, char **filearray) } strcpy(newfile, file); - filearray[pnumwadfiles] = newfile; + filearray[count] = newfile; } -static void D_CleanFile(char **filearray) -{ - size_t pnumwadfiles; - - for (pnumwadfiles = 0; filearray[pnumwadfiles]; pnumwadfiles++) - { - free(filearray[pnumwadfiles]); - filearray[pnumwadfiles] = NULL; - } -} - -static void D_CleanAutoloadFile(char **filearray, size_t count) +static void D_CleanFile(char **filearray, size_t count) { size_t i; @@ -1229,7 +1216,7 @@ static void D_AddAutoloadFiles(void) if (W_AddAutoloadedLocalFiles(autoloadwadfiles) == 0) CONS_Printf("D_AutoloadFile(): Are you sure you put in valid files or what?\n"); - D_CleanAutoloadFile(autoloadwadfiles, autoloadcount); + D_CleanFile(autoloadwadfiles, autoloadcount); autoloadcount = 0; autoloaded = true; @@ -1245,7 +1232,7 @@ void D_AddPostloadFiles(void) if (W_AddAutoloadedLocalFiles(autoloadwadfilespost) == 0) CONS_Printf("D_AddPostloadFiles(): Are you sure you put in valid files or what?\n"); - D_CleanAutoloadFile(autoloadwadfilespost, postloadcount); + D_CleanFile(autoloadwadfilespost, postloadcount); postloadcount = 0; postautoloaded = true; @@ -1255,13 +1242,13 @@ void D_AddPostloadFiles(void) // Identify the SRB2 version, and IWAD file to use. // ========================================================================== -static boolean AddIWAD(void) +static boolean AddIWAD(const char * file, const char *dir) { - char * path = va(pandf, srb2path, "srb2.srb"); + char * path = va(pandf, dir, file); if (FIL_ReadFileOK(path)) { - D_AddFile(path, startupiwadfiles); + D_AddFile(path, startupiwadfiles, startupiwadcount++); return true; } @@ -1304,7 +1291,7 @@ static void IdentifyVersion(void) } // Load the IWAD - if (!AddIWAD()) + if (!AddIWAD("srb2.srb", srb2path)) // not sure why this uses srb2path and not srb2waddir? { I_Error("SRB2.SRB not found! Expected in %s\n", srb2waddir); } @@ -1318,48 +1305,51 @@ static void IdentifyVersion(void) #ifdef USE_PATCH_DTA // Add our crappy patches to fix our bugs - D_AddFile(va(pandf,srb2waddir,"patch.dta")); + if (!AddIWAD("patch.dta", srb2waddir)) + { + I_Error("patch.dta not found! Expected in %s\n", srb2waddir); + } #endif + if (!AddIWAD("gfx.kart", srb2waddir)) + { + I_Error("gfx.kart not found! Expected in %s\n", srb2waddir); + } - D_AddFile(va(pandf, srb2waddir, "gfx.kart"), startupiwadfiles); - D_AddFile(va(pandf, srb2waddir, "textures.kart"), startupiwadfiles); - D_AddFile(va(pandf, srb2waddir, "chars.kart"), startupiwadfiles); - D_AddFile(va(pandf, srb2waddir, "maps.kart"), startupiwadfiles); + if (!AddIWAD("textures.kart", srb2waddir)) + { + I_Error("textures.kart not found! Expected in %s\n", srb2waddir); + } + + if (!AddIWAD("chars.kart", srb2waddir)) + { + I_Error("chars.kart not found! Expected in %s\n", srb2waddir); + } + + if (!AddIWAD("maps.kart", srb2waddir)) + { + I_Error("maps.kart not found! Expected in %s\n", srb2waddir); + } #ifdef USE_PATCH_KART - D_AddFile(va(pandf,srb2waddir,"patch.kart"), startupiwadfiles); + if (!AddIWAD("patch.kart", srb2waddir)) + { + I_Error("patch.kart not found! Expected in %s\n", srb2waddir); + } #endif - const char *path = NULL; - - path = va(pandf, srb2waddir, "extra.kart"); - // completely optional - if (FIL_ReadFileOK(path)) - { - D_AddFile(path, startupiwadfiles); + if (AddIWAD("extra.kart", srb2waddir)) found_extra_kart = true; - } - - path = va(pandf, srb2waddir, "extra2.kart"); // completely optional 2: Back with a vengence - if (FIL_ReadFileOK(path)) - { - D_AddFile(path, startupiwadfiles); + if (AddIWAD("extra2.kart", srb2waddir)) found_extra2_kart = true; - } - path = va(pandf, srb2waddir, "extra3.kart"); - - if (FIL_ReadFileOK(path)) - { - D_AddFile(path, startupiwadfiles); + if (AddIWAD("extra3.kart", srb2waddir)) found_extra3_kart = true; - } #if !defined (HAVE_SDL) || defined (HAVE_MIXER) #define MUSICTEST(str) \ - musicpath = va(pandf,srb2waddir,str);\ + musicpath = va(pandf, srb2waddir, str);\ handle = W_OpenWadFile(&musicpath, false); \ if (handle) \ {\ @@ -1368,7 +1358,7 @@ static void IdentifyVersion(void) if (ms == 0) \ I_Error("File " str " has been modified with non-music/sound lumps"); \ if (ms == 1) \ - D_AddFile(musicpath, startupiwadfiles); \ + D_AddFile(musicpath, startupiwadfiles, startupiwadcount++); \ } { const char *musicpath; @@ -1814,7 +1804,7 @@ void D_SRB2Main(void) const char *s = M_GetNextParm(); if (s) // Check for NULL? - D_AddFile(s, startuppwads); + D_AddFile(s, startuppwads, startuppwadcount++); } } } @@ -1848,7 +1838,8 @@ void D_SRB2Main(void) CONS_Printf("W_InitMultipleFiles(): Adding IWAD and main PWADs.\n"); W_InitMultipleFiles(startupiwadfiles, false); - D_CleanFile(startupiwadfiles); + D_CleanFile(startupiwadfiles, startupiwadcount); + startupiwadcount = 0; mainwads = 0; #ifndef DEVELOP @@ -1895,7 +1886,8 @@ void D_SRB2Main(void) D_CheckMaps(true); } - D_CleanFile(startuppwads); + D_CleanFile(startuppwads, startuppwadcount); + startuppwadcount = 0; cht_Init(); -- 2.54.0 From c8ae4a89d9a7b73210a17301f094786b99050c15 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 19:28:41 +0100 Subject: [PATCH 061/116] throw motion blur effect stuff behind an ifdef so we can get rid of the unused array prob could just remove it at this point, but maybe ill fix it someday for the funnis --- src/d_main.c | 6 ++++++ src/doomstat.h | 3 +++ src/p_user.c | 14 +++++++++----- src/v_video.c | 11 +++++++++-- 4 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index b7704318b..ee587cfdc 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -115,7 +115,9 @@ boolean devparm = false; // started game with -devparm boolean singletics = false; // timedemo boolean lastdraw = false; +#ifdef MOTIONBLUR INT32 postimgparam[MAXSPLITSCREENPLAYERS]; +#endif // These variables are only true if // whether the respective sound system is disabled @@ -399,7 +401,11 @@ static void D_Renderview(void) if (i == 0) R_ApplyViewMorph(); +#ifdef MOTIONBLUR V_DoPostProcessor(i, postimgparam[i]); +#else + V_DoPostProcessor(i, 0); +#endif } } diff --git a/src/doomstat.h b/src/doomstat.h index 46c3d61f9..a9bd9bbac 100644 --- a/src/doomstat.h +++ b/src/doomstat.h @@ -116,7 +116,10 @@ extern UINT8 window_notinfocus; // are we in focus? (backend independant -- hand extern boolean nodrawers; extern boolean noblit; extern boolean lastdraw; + +#ifdef MOTIONBLUR extern INT32 postimgparam[MAXSPLITSCREENPLAYERS]; +#endif extern INT32 viewwindowx, viewwindowy; extern INT32 viewwidth; diff --git a/src/p_user.c b/src/p_user.c index 5ccc43f0a..481cd6060 100644 --- a/src/p_user.c +++ b/src/p_user.c @@ -4315,17 +4315,19 @@ static void P_CalcPostImg(player_t *player, camera_t *thiscam) { sector_t *sector = NULL; UINT8 postimgtype = 0; - //INT32 *param; fixed_t pviewheight = 0; +#ifdef MOTIONBLUR + INT32 *param; - /*for (i = 0; i <= splitscreen; i++) + for (i = 0; i <= splitscreen; i++) { if (player == &players[displayplayers[i]]) { param = &postimgparam[i]; break; } - }*/ + } +#endif if (encoremode) // srb2kart postimgtype |= POSTIMG_MIRROR; @@ -4361,16 +4363,18 @@ static void P_CalcPostImg(player_t *player, camera_t *thiscam) else if (P_CameraCheckHeatFirstperson(player, sector, pviewheight)) postimgtype |= POSTIMG_HEAT; +#ifdef MOTIONBLUR // Motion blur // unused - /*if (player->speed > (35<speed > (35<speed - 32)/4; if (*param > 5) *param = 5; - }*/ + } +#endif thiscam->postimg = postimgtype; } diff --git a/src/v_video.c b/src/v_video.c index 9805e910c..e7d9a87ca 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -3581,6 +3581,9 @@ boolean *heatshifter = NULL; INT32 lastheight = 0; INT32 heatindex[MAXSPLITSCREENPLAYERS] = {0, 0, 0, 0}; +// unused motion blur effect, probably non functional +//#define MOTIONBLUR + // // V_DoPostProcessor // @@ -3595,7 +3598,9 @@ void V_DoPostProcessor(INT32 view, INT32 param) (void)type; (void)param; #else +#ifndef MOTIONBLUR (void)param; // unused motion blur stuff +#endif INT32 yoffset, xoffset; #ifdef HWRENDER @@ -3730,7 +3735,8 @@ void V_DoPostProcessor(INT32 view, INT32 param) srcscr = tmp; } - /*if (thiscam->postimg & POSTIMG_MOTION) // Motion Blur! +#ifdef MOTIONBLUR + if (thiscam->postimg & POSTIMG_MOTION) // Motion Blur! { INT32 x, y; @@ -3742,7 +3748,8 @@ void V_DoPostProcessor(INT32 view, INT32 param) for (x = xoffset; x < xoffset+viewwidth; x++) tmpscr[y*vid.width + x] = colormaps[*(transme + (srcscr [(y*vid.width)+x ] <<8) + (tmpscr[(y*vid.width)+x]))]; } - }*/ + } +#endif if ((thiscam->postimg & POSTIMG_FLIP) && !(thiscam->postimg & POSTIMG_MIRROR)) // Flip the screen upside-down { -- 2.54.0 From 7c1f17bb8dcbc2dc6ea8ace3c11e9e80368720c0 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 20:47:19 +0100 Subject: [PATCH 062/116] pass our file counts to W_InitMultipleFiles smol opzimiation, skips some ptr deref --- src/d_main.c | 17 +++++++++-------- src/w_wad.c | 13 +++++++------ src/w_wad.h | 2 +- 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index ee587cfdc..7bb932b1b 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1046,7 +1046,7 @@ void D_StartTitle(void) // // D_AddFile // -static void D_AddFile(const char *file, char **filearray, size_t count) +static void D_AddFile(const char *file, char **filearray, size_t index) { char *newfile; @@ -1057,14 +1057,14 @@ static void D_AddFile(const char *file, char **filearray, size_t count) } strcpy(newfile, file); - filearray[count] = newfile; + filearray[index] = newfile; } -static void D_CleanFile(char **filearray, size_t count) +static void D_CleanFile(char **filearray, size_t index) { size_t i; - for (i = 0; i < count; i++) + for (i = 0; i < index; i++) { free(filearray[i]); filearray[i] = NULL; @@ -1358,7 +1358,7 @@ static void IdentifyVersion(void) musicpath = va(pandf, srb2waddir, str);\ handle = W_OpenWadFile(&musicpath, false); \ if (handle) \ - {\ + { \ int ms = W_VerifyNMUSlumps(musicpath, handle, false); \ fclose(handle); \ if (ms == 0) \ @@ -1843,7 +1843,8 @@ void D_SRB2Main(void) // load wad, including the main wad file CONS_Printf("W_InitMultipleFiles(): Adding IWAD and main PWADs.\n"); - W_InitMultipleFiles(startupiwadfiles, false); + W_InitMultipleFiles(startupiwadfiles, startupiwadcount, false); + //mainwads = startupiwadcount - musicwads; D_CleanFile(startupiwadfiles, startupiwadcount); startupiwadcount = 0; mainwads = 0; @@ -1884,10 +1885,10 @@ void D_SRB2Main(void) D_CheckMaps(false); - W_InitMultipleFiles(startuppwads, true); + W_InitMultipleFiles(startuppwads, startuppwadcount, true); // Only search for pwad maps if we actually have a pwad added - if (startuppwads[0] != NULL) + if (startuppwadcount > 0) { D_CheckMaps(true); } diff --git a/src/w_wad.c b/src/w_wad.c index 756dee4a6..f9eb9b361 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -971,24 +971,25 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) * \return 1 if all files were loaded, 0 if at least one was missing or * invalid. */ -INT32 W_InitMultipleFiles(char **filenames, boolean addons) +INT32 W_InitMultipleFiles(char **filenames, size_t count, boolean addons) { INT32 rc = 1; INT32 overallrc = 1; - + size_t i; (void)addons; - // will be realloced as lumps are added - for (; *filenames; filenames++) + for (i = 0; i < count; i++) { + const char *filename = filenames[i]; + // Previously, W_VerifyNMUSlumps was called to mark game modified // for addons... but W_InitFile already does exactly that! //CONS_Debug(DBG_SETUP, "Loading %s\n", *filenames); - rc = W_InitFile(*filenames, false, true); + rc = W_InitFile(filename, false, true); if (rc == INT16_MAX) - CONS_Printf(M_GetText("Errors occurred while loading %s; not added.\n"), *filenames); + CONS_Printf(M_GetText("Errors occurred while loading %s; not added.\n"), filename); overallrc &= (rc != INT16_MAX) ? 1 : 0; } diff --git a/src/w_wad.h b/src/w_wad.h index c3cae627f..6240c31f3 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -167,7 +167,7 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup); // W_InitMultipleFiles returns 1 if all is okay, 0 otherwise, // so that it stops with a message if a file was not found, but not if all is okay. -INT32 W_InitMultipleFiles(char **filenames, boolean addons); +INT32 W_InitMultipleFiles(char **filenames, size_t count, boolean addons); // Used for autoload. Uses P_AddWadFileLocal instead of W_InitFiles. INT32 W_AddAutoloadedLocalFiles(char **filenames); -- 2.54.0 From 3e0150d4f31be79d30c99d0d6f8b00a02e85360b Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 20:53:21 +0100 Subject: [PATCH 063/116] remove auto/postload check variables we can just check our counts since D_FindAddonsToAutoload will never be called again --- src/d_main.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index 7bb932b1b..aa6c905c2 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -106,8 +106,6 @@ static char *autoloadwadfiles[MAX_WADFILES]; static char *autoloadwadfilespost[MAX_WADFILES]; static size_t autoloadcount = 0; static size_t postloadcount = 0; -static boolean autoloaded = false; -static boolean postautoloaded = false; // boolean devparm = false; // started game with -devparm @@ -1160,7 +1158,7 @@ static void D_FindAddonsToAutoload(void) // If the file is found, run our shit if (!autoloadconfigfile) // nope outta here { - autoloaded = postautoloaded = true; // so D_AddAutoloadFiles can skip everything since nothings there to autoload + autoloadcount = postloadcount = 0; // so D_AddAutoloadFiles can skip everything since nothings there to autoload return; } @@ -1214,7 +1212,8 @@ static void D_FindAddonsToAutoload(void) static void D_AddAutoloadFiles(void) { - if (autoloaded) + // nothing to autoload + if (autoloadcount == 0) return; CONS_Printf("D_AutoloadFile(): Loading autoloaded addons...\n"); @@ -1225,12 +1224,12 @@ static void D_AddAutoloadFiles(void) D_CleanFile(autoloadwadfiles, autoloadcount); autoloadcount = 0; - autoloaded = true; } void D_AddPostloadFiles(void) { - if (postautoloaded || !netgame) + // nothing to postload + if (postloadcount == 0 || !netgame) return; CONS_Printf("D_AddPostloadFiles(): Loading postloaded addons...\n"); @@ -1241,7 +1240,6 @@ void D_AddPostloadFiles(void) D_CleanFile(autoloadwadfilespost, postloadcount); postloadcount = 0; - postautoloaded = true; } // ========================================================================== -- 2.54.0 From 4fccb48d2ab44360890e24375e7593124039fadc Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 20:57:55 +0100 Subject: [PATCH 064/116] fix wonky variable names --- src/d_main.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/d_main.c b/src/d_main.c index aa6c905c2..032a9189e 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1058,11 +1058,11 @@ static void D_AddFile(const char *file, char **filearray, size_t index) filearray[index] = newfile; } -static void D_CleanFile(char **filearray, size_t index) +static void D_CleanFile(char **filearray, size_t count) { size_t i; - for (i = 0; i < index; i++) + for (i = 0; i < count; i++) { free(filearray[i]); filearray[i] = NULL; @@ -1097,7 +1097,7 @@ static INT32 D_DetectFileType(const char* filename) } // autoload that shit -static void D_AutoloadFile(const char *file, char **filearray, size_t count) +static void D_AutoloadFile(const char *file, char **filearray, size_t index) { char *newfile; INT32 fileType = D_DetectFileType(file); @@ -1115,7 +1115,7 @@ static void D_AutoloadFile(const char *file, char **filearray, size_t count) I_Error("No more free memory to AutoloadFile %s",file); strcpy(newfile, file); - filearray[count] = newfile; + filearray[index] = newfile; } else { -- 2.54.0 From cae5e73d7dd681881a42026a2aa822cae3967ae1 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 30 Oct 2025 18:04:46 +0100 Subject: [PATCH 065/116] LUA_RawPushUserdata "Same as LUA_PushUserdata but don't set a metatable yet." from RR --- src/lua_script.c | 25 ++++++++++++++++++++++--- src/lua_script.h | 8 ++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/lua_script.c b/src/lua_script.c index e59841940..448d7221d 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -492,25 +492,37 @@ void LUA_InvalidateMathlibCache(const char *name) // Pushes it to the stack and stores it in the registry. void LUA_PushUserdata(lua_State *L, void *data, const char *meta) { + if (LUA_RawPushUserdata(L, data) == LPUSHED_NEW) + { + luaL_getmetatable(L, meta); + lua_setmetatable(L, -2); + } +} + +// Same as LUA_PushUserdata but don't set a metatable yet. +lpushed_t LUA_RawPushUserdata(lua_State *L, void *data) +{ + lpushed_t status = LPUSHED_NIL; + void **userdata; if (!data) { // push a NULL lua_pushnil(L); - return; + return status; } lua_getfield(L, LUA_REGISTRYINDEX, LREG_VALID); I_Assert(lua_istable(L, -1)); + lua_pushlightuserdata(L, data); lua_rawget(L, -2); + if (lua_isnil(L, -1)) { // no userdata? deary me, we'll have to make one. lua_pop(L, 1); // pop the nil // create the userdata userdata = lua_newuserdata(L, sizeof(void *)); *userdata = data; - luaL_getmetatable(L, meta); - lua_setmetatable(L, -2); // Set it in the registry so we can find it again lua_pushlightuserdata(L, data); // k (store the userdata via the data's pointer) @@ -518,8 +530,15 @@ void LUA_PushUserdata(lua_State *L, void *data, const char *meta) lua_rawset(L, -4); // stack is left with the userdata on top, as if getting it had originally succeeded. + + status = LPUSHED_NEW; } + else + status = LPUSHED_EXISTING; + lua_remove(L, -2); // remove LREG_VALID + + return status; } // When userdata is freed, use this function to remove it from Lua. diff --git a/src/lua_script.h b/src/lua_script.h index af218978d..a7edf89ca 100644 --- a/src/lua_script.h +++ b/src/lua_script.h @@ -59,7 +59,15 @@ fixed_t LUA_GetConstant(const char *word); // Need better name for this ;-; void LUA_InvalidateMathlibCache(const char *name); +typedef enum { + LPUSHED_NIL, + LPUSHED_NEW, + LPUSHED_EXISTING, +} lpushed_t; + void LUA_PushUserdata(lua_State *L, void *data, const char *meta); +lpushed_t LUA_RawPushUserdata(lua_State *L, void *data); + void LUA_InvalidateUserdata(void *data); void LUA_InvalidateLevel(void); void LUA_InvalidateMapthings(void); -- 2.54.0 From f53d37052af1fd0fcb3c250bbbfa19985da34386 Mon Sep 17 00:00:00 2001 From: James R Date: Sun, 2 May 2021 21:59:23 -0700 Subject: [PATCH 066/116] Replace LUA_PushLightUserdata with LUA_PushUserdata See c92378fa and a7e20f70. I didn't realize that light userdata's metatable is shared--like numbers or strings. So it cannot be paired with a metatable. I also made a few minor tweaks to Lua cvars, other than accounting for the double pointer in the userdata. --- src/command.c | 2 +- src/lua_consolelib.c | 65 ++++++++++++-------------------------------- src/lua_script.h | 2 +- 3 files changed, 19 insertions(+), 50 deletions(-) diff --git a/src/command.c b/src/command.c index e73125649..eae29f07f 100644 --- a/src/command.c +++ b/src/command.c @@ -1474,7 +1474,7 @@ finish: var->flags |= CV_MODIFIED; // raise 'on change' code - LUA_CVarChanged(var->name); // let consolelib know what cvar this is. + LUA_CVarChanged(var); // let consolelib know what cvar this is. if (var->flags & CV_CALL && !stealth) var->func(); diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index 36c3a6c45..f148a8dcb 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -28,7 +28,7 @@ #define NOHUD if (hud_running) return luaL_error(L, "HUD rendering code should not call this function!"); -static const char *cvname = NULL; +static consvar_t *this_cvar; void Got_Luacmd(UINT8 **cp, INT32 playernum) { @@ -284,16 +284,13 @@ static int lib_comBufInsertText(lua_State *L) return 0; } -void LUA_CVarChanged(const char *name) +void LUA_CVarChanged(void *cvar) { - cvname = name; + this_cvar = cvar; } static void Lua_OnChange(void) { - I_Assert(gL != NULL); - I_Assert(cvname != NULL); - /// \todo Network this! XD_LUAVAR // Why?.. @@ -305,13 +302,10 @@ static void Lua_OnChange(void) // From CV_OnChange registry field, get the function for this cvar by name. lua_getfield(gL, LUA_REGISTRYINDEX, "CV_OnChange"); I_Assert(lua_istable(gL, -1)); - lua_getfield(gL, -1, cvname); // get function + lua_pushlightuserdata(gL, this_cvar); + lua_rawget(gL, -2); // get function - // From the CV_Vars registry field, get the cvar's userdata by name. - lua_getfield(gL, LUA_REGISTRYINDEX, "CV_Vars"); - I_Assert(lua_istable(gL, -1)); - lua_getfield(gL, -1, cvname); // get consvar_t* userdata. - lua_remove(gL, -2); // pop the CV_Vars table. + LUA_RawPushUserdata(gL, this_cvar); LUA_Call(gL, 1, 0, error_handler_i); // call function(cvar) lua_pop(gL, 2); // pop CV_OnChange table and error handler @@ -329,9 +323,8 @@ static int lib_cvRegisterVar(lua_State *L) luaL_checktype(L, 1, LUA_TTABLE); lua_settop(L, 1); // Clear out all other possible arguments, leaving only the first one. NOHUD - cvar = lua_newuserdata(L, sizeof(consvar_t)); - luaL_getmetatable(L, META_CVAR); - lua_setmetatable(L, -2); + cvar = ZZ_Calloc(sizeof(consvar_t)); + LUA_PushUserdata(L, cvar, META_CVAR); #define FIELDERROR(f, e) luaL_error(L, "bad value for " LUA_QL(f) " in table passed to " LUA_QL("CV_RegisterVar") " (%s)", e); #define TYPEERROR(f, t) FIELDERROR(f, va("%s expected, got %s", lua_typename(L, t), luaL_typename(L, -1))) @@ -384,7 +377,7 @@ static int lib_cvRegisterVar(lua_State *L) lua_getfield(L, LUA_REGISTRYINDEX, "CV_PossibleValue"); I_Assert(lua_istable(L, 5)); - lua_pushvalue(L, 2); // cvar userdata + lua_pushlightuserdata(L, cvar); cvpv = lua_newuserdata(L, sizeof(CV_PossibleValue_t) * (count+1)); lua_rawset(L, 5); lua_pop(L, 1); // pop CV_PossibleValue registry table @@ -412,13 +405,14 @@ static int lib_cvRegisterVar(lua_State *L) TYPEERROR("func", LUA_TFUNCTION) lua_getfield(L, LUA_REGISTRYINDEX, "CV_OnChange"); I_Assert(lua_istable(L, 5)); + lua_pushlightuserdata(L, cvar); lua_pushvalue(L, 4); - lua_setfield(L, 5, cvar->name); + lua_rawset(L, 5); lua_pop(L, 1); cvar->func = Lua_OnChange; } else if (((i == 5 && !(cvar->flags & CV_CALL)) - || (cvar->flags & CV_CALL && i == 6)) + || (cvar->flags & CV_CALL && i == 6)) || (k && fasticmp(k, "category"))) { category = lua_isnoneornil(L, 4) ? NULL : lua_tostring(L, 4); @@ -434,19 +428,6 @@ static int lib_cvRegisterVar(lua_State *L) #undef FIELDERROR #undef TYPEERROR - // stack: cvar table, cvar userdata - lua_getfield(L, LUA_REGISTRYINDEX, "CV_Vars"); - I_Assert(lua_istable(L, 3)); - - lua_getfield(L, 3, cvar->name); - if (lua_type(L, -1) != LUA_TNIL) - return luaL_error(L, M_GetText("Variable %s is already defined\n"), cvar->name); - lua_pop(L, 1); - - lua_pushvalue(L, 2); - lua_setfield(L, 3, cvar->name); - lua_pop(L, 1); - // actually time to register it to the console now! Finally! cvar->flags |= CV_MODIFIED; CV_RegisterVar(cvar); @@ -477,22 +458,9 @@ static int lib_cvRegisterVar(lua_State *L) static int lib_cvFindVar(lua_State *L) { - consvar_t *cv; - if (( cv = CV_FindVar(luaL_checkstring(L,1)) )) - { - lua_settop(L,1);/* We only want one argument in the stack. */ - lua_pushlightuserdata(L, cv);/* Now the second value on stack. */ - luaL_getmetatable(L, META_CVAR); - /* - The metatable is the last value on the stack, so this - applies it to the second value, which is the cvar. - */ - lua_setmetatable(L,2); - lua_pushvalue(L,2); - return 1; - } - else - return 0; + const char *name = luaL_checkstring(L, 1); + LUA_PushUserdata(L, CV_FindVar(name), META_CVAR); + return 1; } static int CVarSetFunction @@ -501,7 +469,7 @@ static int CVarSetFunction void (*Set)(consvar_t *, const char *), void (*SetValue)(consvar_t *, INT32) ){ - consvar_t *cvar = (consvar_t *)luaL_checkudata(L, 1, META_CVAR); + consvar_t *cvar = *(consvar_t **)luaL_checkudata(L, 1, META_CVAR); switch (lua_type(L, 2)) { @@ -531,6 +499,7 @@ static int lib_cvStealthSet(lua_State *L) static int lib_cvAddValue(lua_State *L) { consvar_t *cvar = (consvar_t *)luaL_checkudata(L, 1, META_CVAR); + CV_AddValue(cvar, (INT32)luaL_checknumber(L, 2)); return 0; } diff --git a/src/lua_script.h b/src/lua_script.h index a7edf89ca..f1b58cced 100644 --- a/src/lua_script.h +++ b/src/lua_script.h @@ -77,7 +77,7 @@ void LUA_Archive(savebuffer_t *save, boolean network); void LUA_UnArchive(savebuffer_t *save, boolean network); void Got_Luacmd(UINT8 **cp, INT32 playernum); // lua_consolelib.c -void LUA_CVarChanged(const char *name); // lua_consolelib.c +void LUA_CVarChanged(void *cvar); // lua_consolelib.c int Lua_optoption(lua_State *L, int narg, int def, int list_ref); int Lua_CreateFieldTable(lua_State *L, const char *const lst[]); void LUA_HookNetArchive(lua_CFunction archFunc, savebuffer_t *save); -- 2.54.0 From 1d0fb17da4e72e41d325e8c0a631e04c8d2f49e2 Mon Sep 17 00:00:00 2001 From: Monster Iestyn Date: Tue, 20 Aug 2019 18:18:29 +0100 Subject: [PATCH 067/116] Fixes for lib_cvRegisterVar (the Lua version of CV_RegisterVar): * Make sure the consvar's properties are all initialised to zeros as defaults * Error if the consvar is not given a name * Error if the consvar has CV_CALL but no call function * Error if the consvar has CV_NOINIT but not CV_CALL --- src/lua_consolelib.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index f148a8dcb..260ba6532 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -428,6 +428,13 @@ static int lib_cvRegisterVar(lua_State *L) #undef FIELDERROR #undef TYPEERROR + if (!cvar->name) + return luaL_error(L, M_GetText("Variable has no name!\n")); + if ((cvar->flags & CV_NOINIT) && !(cvar->flags & CV_CALL)) + return luaL_error(L, M_GetText("Variable %s has CV_NOINIT without CV_CALL\n"), cvar->name); + if ((cvar->flags & CV_CALL) && !cvar->func) + return luaL_error(L, M_GetText("Variable %s has CV_CALL without a function\n"), cvar->name); + // actually time to register it to the console now! Finally! cvar->flags |= CV_MODIFIED; CV_RegisterVar(cvar); -- 2.54.0 From 5675eefeb22336031715ac197baa33d80f947dd7 Mon Sep 17 00:00:00 2001 From: James R Date: Sun, 11 Feb 2024 05:33:20 -0800 Subject: [PATCH 068/116] Got_Luacmd: ensure lua stack is large enough for command arguments --- src/lua_consolelib.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index 260ba6532..f54349206 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -30,6 +30,12 @@ static consvar_t *this_cvar; +static void clear_lua_stack(void) +{ + if (gL) // check if Lua is actually turned on first, you dummmy -- Monster Iestyn 04/07/18 + lua_settop(gL, 0); // clear stack +} + void Got_Luacmd(UINT8 **cp, INT32 playernum) { UINT8 i, argc, flags; @@ -74,6 +80,13 @@ void Got_Luacmd(UINT8 **cp, INT32 playernum) lua_remove(gL, -2); // pop command info table + if (!lua_checkstack(gL, argc)) // player + command arguments + { + clear_lua_stack(); + CONS_Alert(CONS_WARNING, "lua command stack overflow from %s (%d, need %d more)\n", player_names[playernum], lua_gettop(gL), argc); + return; + } + LUA_PushUserdata(gL, &players[playernum], META_PLAYER); for (i = 1; i < argc; i++) { @@ -88,8 +101,7 @@ void Got_Luacmd(UINT8 **cp, INT32 playernum) deny: //must be hacked/buggy client - if (gL) // check if Lua is actually turned on first, you dummmy -- Monster Iestyn 04/07/18 - lua_settop(gL, 0); // clear stack + clear_lua_stack(); CONS_Alert(CONS_WARNING, M_GetText("Illegal lua command received from %s\n"), player_names[playernum]); if (server) -- 2.54.0 From f603106ac84859035d16ed0b412092fa65db6760 Mon Sep 17 00:00:00 2001 From: Eidolon Date: Sun, 11 Feb 2024 15:10:51 -0600 Subject: [PATCH 069/116] Check Lua stack before pushing cons args Prevents a Lua stack overrun when executing absurd console commands for local-only lua commands. --- src/lua_consolelib.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index f54349206..c69fdcc10 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -190,6 +190,11 @@ void COM_Lua_f(void) I_Assert(lua_isfunction(gL, -1)); lua_remove(gL, -2); // pop command info table + if (!lua_checkstack(gL, COM_Argc() + 1)) + { + CONS_Alert(CONS_WARNING, "lua command stack overflow (%d, need %s more)\n", lua_gettop(gL), sizeu1(COM_Argc() + 1)); + return; + } LUA_PushUserdata(gL, &players[playernum], META_PLAYER); for (i = 1; i < COM_Argc(); i++) lua_pushstring(gL, COM_Argv(i)); -- 2.54.0 From 81f7335b05c0ea2d8cc9134f5a1f61433660448a Mon Sep 17 00:00:00 2001 From: James R Date: Sun, 11 Feb 2024 15:40:04 -0800 Subject: [PATCH 070/116] Got_Luacmd: always read netxcmd data, even if command is not executed --- src/lua_consolelib.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index c69fdcc10..ead7c16a9 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -39,8 +39,18 @@ static void clear_lua_stack(void) void Got_Luacmd(UINT8 **cp, INT32 playernum) { UINT8 i, argc, flags; + const char *argv[256]; char buf[256]; + argc = READUINT8(*cp); + argv[0] = (const char*)*cp; + SKIPSTRINGN(*cp, 255); + for (i = 1; i < argc; i++) + { + argv[i] = (const char*)*cp; + SKIPSTRINGN(*cp, 255); + } + // don't use I_Assert here, goto the deny code below // to clean up and kick people who try nefarious exploits // like sending random junk lua commands to crash the server @@ -53,8 +63,7 @@ void Got_Luacmd(UINT8 **cp, INT32 playernum) lua_getfield(gL, LUA_REGISTRYINDEX, "COM_Command"); // push COM_Command if (!lua_istable(gL, -1)) goto deny; - argc = READUINT8(*cp); - READSTRINGN(*cp, buf, 255); + strlcpy(buf, argv[0], 255); strlwr(buf); // must lowercase buffer lua_getfield(gL, -1, buf); // push command info table if (!lua_istable(gL, -1)) goto deny; @@ -90,7 +99,7 @@ void Got_Luacmd(UINT8 **cp, INT32 playernum) LUA_PushUserdata(gL, &players[playernum], META_PLAYER); for (i = 1; i < argc; i++) { - READSTRINGN(*cp, buf, 255); + strlcpy(buf, argv[i], 255); lua_pushstring(gL, buf); } LUA_Call(gL, (int)argc, 0, 1); // argc is 1-based, so this will cover the player we passed too. -- 2.54.0 From 26b26b8f254ff2bdc947325e53ff65115e1e57f3 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 30 Oct 2025 15:58:03 +0100 Subject: [PATCH 071/116] consolelib: fix some early returns not properly cleaning lua stack --- src/lua_consolelib.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index ead7c16a9..979179ab6 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -154,7 +154,7 @@ void COM_Lua_f(void) { if (!splitscreen) { - lua_pop(gL, 1); // pop command info table + lua_pop(gL, 2); // pop command info table and LUA_GetErrorMessage return; // can't execute splitscreen command without player 2! } @@ -202,8 +202,10 @@ void COM_Lua_f(void) if (!lua_checkstack(gL, COM_Argc() + 1)) { CONS_Alert(CONS_WARNING, "lua command stack overflow (%d, need %s more)\n", lua_gettop(gL), sizeu1(COM_Argc() + 1)); + lua_pop(gL, 2); // pop function and LUA_GetErrorMessage return; } + LUA_PushUserdata(gL, &players[playernum], META_PLAYER); for (i = 1; i < COM_Argc(); i++) lua_pushstring(gL, COM_Argv(i)); @@ -547,6 +549,7 @@ static int lib_consPrintf(lua_State *L) if (n < 2) return luaL_error(L, "CONS_Printf requires at least two arguments: player and text."); //HUDSAFE + plr = *((player_t **)luaL_checkudata(L, 1, META_PLAYER)); if (!plr) return LUA_ErrInvalid(L, "player_t"); -- 2.54.0 From 52a9486974d26f441e16c1b94c080d65795fb2d4 Mon Sep 17 00:00:00 2001 From: toaster Date: Tue, 3 Jan 2023 20:20:22 +0000 Subject: [PATCH 072/116] Remove heinous pointer-sent-over-the-network hack remnants This used to be used for `P_RelinkPointers()`, but was superseded by the far saner mobjnum. HOWEVER, its lingering effect was to leave `mobj->info` in an invalid state until a later `P_FinishMobjs()` was called. This is memory unsafety :D After removing the last remnants of this ancient hack, it is now once again possible to connect to a server without crashing immediately. However, I did get a crash after a few seconds, so there is definitely still *something* nasty going on under the hood. --- src/p_saveg.c | 28 +++------------------------- 1 file changed, 3 insertions(+), 25 deletions(-) diff --git a/src/p_saveg.c b/src/p_saveg.c index d3a162e2d..65b15ec8e 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -1203,7 +1203,7 @@ static void SaveMobjThinker(savebuffer_t *save, const thinker_t *th, const UINT8 if (diff & MD_MORE) WRITEUINT16(save->p, diff2); - // save pointer, at load time we will search this pointer to reinitilize pointers + // keep here for vanilla compat WRITEUINT32(save->p, (size_t)mobj); WRITEFIXED(save->p, mobj->z); // Force this so 3dfloor problems don't arise. @@ -1982,7 +1982,6 @@ static void CalculateDoomednumToMobjtype(void) static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) { - thinker_t *next; mobj_t *mobj; UINT32 diff; UINT16 diff2; @@ -1995,7 +1994,8 @@ static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) else diff2 = 0; - next = (void *)(size_t)READUINT32(save->p); + // here for vanilla compat + save->p += sizeof(UINT32); z = READFIXED(save->p); // Force this so 3dfloor problems don't arise. floorz = READFIXED(save->p); @@ -2234,8 +2234,6 @@ static void LoadMobjThinker(savebuffer_t *save, actionf_p1 thinker) if (diff2 & MD2_WAYPOINTCAP) P_SetTarget(&waypointcap, mobj); - mobj->info = (mobjinfo_t *)next; // temporarily, set when leave this function - R_AddMobjInterpolator(mobj); } @@ -3200,25 +3198,6 @@ FUNCINLINE static ATTRINLINE void P_UnArchivePolyObjects(savebuffer_t *save) for (i = 0; i < numSavedPolys; ++i) P_UnArchivePolyObj(save, &PolyObjects[i]); } -// -// P_FinishMobjs -// -FUNCINLINE static ATTRINLINE void P_FinishMobjs(void) -{ - thinker_t *currentthinker; - mobj_t *mobj; - - // put info field there real value - for (currentthinker = thinkercap.next; currentthinker != &thinkercap; - currentthinker = currentthinker->next) - { - if (currentthinker->function != (actionf_p1)P_MobjThinker) - continue; - - mobj = (mobj_t *)currentthinker; - mobj->info = &mobjinfo[mobj->type]; - } -} FUNCINLINE static ATTRINLINE mobj_t *RelinkMobj(mobj_t **ptr) { @@ -3807,7 +3786,6 @@ boolean P_LoadNetGame(savebuffer_t *save, boolean reloading) P_NetUnArchiveThinkers(save); P_NetUnArchiveSpecials(save); P_RelinkPointers(); - P_FinishMobjs(); } LUA_UnArchive(save, true); -- 2.54.0 From e00783da82565062ac1ba7df765cd1dd7018b568 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 30 Oct 2025 16:06:26 +0100 Subject: [PATCH 073/116] fix stuff from merge conflict --- src/lua_consolelib.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index 979179ab6..ee5de8356 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -533,7 +533,7 @@ static int lib_cvStealthSet(lua_State *L) static int lib_cvAddValue(lua_State *L) { - consvar_t *cvar = (consvar_t *)luaL_checkudata(L, 1, META_CVAR); + consvar_t *cvar = *(consvar_t **)luaL_checkudata(L, 1, META_CVAR); CV_AddValue(cvar, (INT32)luaL_checknumber(L, 2)); return 0; @@ -610,7 +610,7 @@ static int cvar_fields_ref = LUA_NOREF; static int cvar_get(lua_State *L) { - consvar_t *cvar = (consvar_t *)luaL_checkudata(L, 1, META_CVAR); + consvar_t *cvar = *(consvar_t **)luaL_checkudata(L, 1, META_CVAR); enum cvar_e field = Lua_optoption(L, 2, -1, cvar_fields_ref); switch (field) -- 2.54.0 From ec757ceb2cebfc04563c7d8b95a541f7edb55d76 Mon Sep 17 00:00:00 2001 From: James R Date: Sun, 11 Feb 2024 05:40:52 -0800 Subject: [PATCH 074/116] Pass const pointer to all netxcmd handlers Ensure buffer data is read-only and not modified by handler --- src/byteptr.h | 62 +++++++++++++++--------------- src/command.c | 18 +++++---- src/command.h | 2 +- src/d_clisrv.c | 22 +++++------ src/d_clisrv.h | 2 +- src/d_netcmd.c | 88 ++++++++++++++++++++++--------------------- src/g_demo.c | 4 +- src/hu_stuff.c | 9 +++-- src/lua_consolelib.c | 2 +- src/lua_script.h | 2 +- src/p_saveg.c | 2 +- src/sdl/mixer_sound.c | 6 +-- 12 files changed, 114 insertions(+), 105 deletions(-) diff --git a/src/byteptr.h b/src/byteptr.h index 058e81b25..85141c21c 100644 --- a/src/byteptr.h +++ b/src/byteptr.h @@ -1,7 +1,8 @@ -// SONIC ROBO BLAST 2 +// SONIC ROBO BLAST 2 KART //----------------------------------------------------------------------------- -// Copyright (C) 1998-2000 by DooM Legacy Team. -// Copyright (C) 1999-2025 by Sonic Team Junior. +// Copyright (C) 2025 by Kart Krew. +// Copyright (C) 2020 by Sonic Team Junior. +// Copyright (C) 2000 by DooM Legacy Team. // // This program is free software distributed under the // terms of the GNU General Public License, version 2. @@ -24,6 +25,7 @@ extern "C" { // // Little-endian machines // + #define WRITEUINT8(p,b) do { UINT8 *p_tmp = ( UINT8 *)p; const UINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) #define WRITESINT8(p,b) do { SINT8 *p_tmp = ( SINT8 *)p; const SINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) #define WRITEINT16(p,b) do { INT16 *p_tmp = ( INT16 *)p; const INT16 tv = ( INT16)(b); memcpy(p, &tv, sizeof( INT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) @@ -36,25 +38,25 @@ extern "C" { // what is this? #if defined (__GNUC__) -#define READUINT8(p) ({ UINT8 *p_tmp = (UINT8 *)p; UINT8 b; memcpy(&b, p, sizeof( UINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READSINT8(p) ({ SINT8 *p_tmp = (SINT8 *)p; SINT8 b; memcpy(&b, p, sizeof( SINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READINT16(p) ({ INT16 *p_tmp = (INT16 *)p; INT16 b; memcpy(&b, p, sizeof( INT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READUINT16(p) ({ UINT16 *p_tmp = (UINT16 *)p; UINT16 b; memcpy(&b, p, sizeof( UINT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READINT32(p) ({ INT32 *p_tmp = (INT32 *)p; INT32 b; memcpy(&b, p, sizeof( INT32)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READUINT32(p) ({ UINT32 *p_tmp = (UINT32 *)p; UINT32 b; memcpy(&b, p, sizeof( UINT32)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READCHAR(p) ({ char *p_tmp = (char *)p; char b; memcpy(&b, p, sizeof( char)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READFIXED(p) ({ fixed_t *p_tmp = (fixed_t *)p; fixed_t b; memcpy(&b, p, sizeof(fixed_t)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) -#define READANGLE(p) ({ angle_t *p_tmp = (angle_t *)p; angle_t b; memcpy(&b, p, sizeof(angle_t)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; b; }) +#define READUINT8(p) ({ const UINT8 *p_tmp = (const UINT8 *)p; UINT8 b; memcpy(&b, p, sizeof( UINT8)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READSINT8(p) ({ const SINT8 *p_tmp = (const SINT8 *)p; SINT8 b; memcpy(&b, p, sizeof( SINT8)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READINT16(p) ({ const INT16 *p_tmp = (const INT16 *)p; INT16 b; memcpy(&b, p, sizeof( INT16)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READUINT16(p) ({ const UINT16 *p_tmp = (const UINT16 *)p; UINT16 b; memcpy(&b, p, sizeof( UINT16)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READINT32(p) ({ const INT32 *p_tmp = (const INT32 *)p; INT32 b; memcpy(&b, p, sizeof( INT32)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READUINT32(p) ({ const UINT32 *p_tmp = (const UINT32 *)p; UINT32 b; memcpy(&b, p, sizeof( UINT32)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READCHAR(p) ({ const char *p_tmp = (const char *)p; char b; memcpy(&b, p, sizeof( char)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READFIXED(p) ({ const fixed_t *p_tmp = (const fixed_t *)p; fixed_t b; memcpy(&b, p, sizeof(fixed_t)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) +#define READANGLE(p) ({ const angle_t *p_tmp = (const angle_t *)p; angle_t b; memcpy(&b, p, sizeof(angle_t)); p_tmp++; *(const void**)(&(p)) = (const void *)p_tmp; b; }) #else -#define READUINT8(p) ((UINT8*)(*(void**)(&(p)) = (void*)&((UINT8*)(p))[1]))[-1] -#define READSINT8(p) ((SINT8*)(*(void**)(&(p)) = (void*)&((SINT8*)(p))[1]))[-1] -#define READINT16(p) ((INT16*)(*(void**)(&(p)) = (void*)&((INT16*)(p))[1]))[-1] -#define READUINT16(p) ((UINT16*)(*(void**)(&(p)) = (void*)&((UINT16*)(p))[1]))[-1] -#define READINT32(p) ((INT32*)(*(void**)(&(p)) = (void*)&((INT32*)(p))[1]))[-1] -#define READUINT32(p) ((UINT32*)(*(void**)(&(p)) = (void*)&((UINT32*)(p))[1]))[-1] -#define READCHAR(p) ((char*)(*(void**)(&(p)) = (void*)&((char*)(p))[1]))[-1] -#define READFIXED(p) ((fixed_t*)(*(void**)(&(p)) = (void*)&((fixed_t*)(p))[1]))[-1] -#define READANGLE(p) ((angle_t*)(*(void**)(&(p)) = (void*)&((angle_t*)(p))[1]))[-1] +#define READUINT8(p) ((const UINT8*) (*(const void**)(&(p)) = (const void*)&((const UINT8*) (p))[1]))[-1] +#define READSINT8(p) ((const SINT8*) (*(const void**)(&(p)) = (const void*)&((const SINT8*) (p))[1]))[-1] +#define READINT16(p) ((const INT16*) (*(const void**)(&(p)) = (const void*)&((const INT16*) (p))[1]))[-1] +#define READUINT16(p) ((const UINT16*) (*(const void**)(&(p)) = (const void*)&((const UINT16*) (p))[1]))[-1] +#define READINT32(p) ((const INT32*) (*(const void**)(&(p)) = (const void*)&((const INT32*) (p))[1]))[-1] +#define READUINT32(p) ((const UINT32*) (*(const void**)(&(p)) = (const void*)&((const UINT32*) (p))[1]))[-1] +#define READCHAR(p) ((const char*) (*(const void**)(&(p)) = (const void*)&((const char*) (p))[1]))[-1] +#define READFIXED(p) ((const fixed_t*)(*(const void**)(&(p)) = (const void*)&((const fixed_t*)(p))[1]))[-1] +#define READANGLE(p) ((const angle_t*)(*(const void**)(&(p)) = (const void*)&((const angle_t*)(p))[1]))[-1] #endif #else //SRB2_BIG_ENDIAN @@ -117,15 +119,15 @@ FUNCINLINE static ATTRINLINE UINT32 readulong(void *ptr) return (ucp[3] << 24) | (ucp[2] << 16) | (ucp[1] << 8) | ucp[0]; } -#define READUINT8(p) ((UINT8*)(p = (void*)&((UINT8*)p)[1]))[-1] -#define READSINT8(p) ((SINT8*)(p = (void*)&((SINT8*)p)[1]))[-1] -#define READINT16(p) readshort(&((INT16*)(p = (void*)&((INT16*)p)[1]))[-1]) -#define READUINT16(p) readushort(&((UINT16*)(p = (void*)&((UINT16*)p)[1]))[-1]) -#define READINT32(p) readlong(&((INT32*)(p = (void*)&((INT32*)p)[1]))[-1]) -#define READUINT32(p) readulong(&((UINT32*)(p = (void*)&((UINT32*)p)[1])) -#define READCHAR(p) ((char*)(p = (void*)&((char*)p)[1]))[-1] -#define READFIXED(p) readlong(&((fixed_t*)(p = (void*)&((fixed_t*)p)[1]))[-1]) -#define READANGLE(p) readulong(&((angle_t*)(p = (void*)&((angle_t*)p)[1]))[-1]) +#define READUINT8(p) ((const UINT8*)(p = (const void*)&((const UINT8*)p)[1]))[-1] +#define READSINT8(p) ((const SINT8*)(p = (const void*)&((const SINT8*)p)[1]))[-1] +#define READINT16(p) readshort(&((const INT16*)(p = (const void*)&((const INT16*)p)[1]))[-1]) +#define READUINT16(p) readushort(&((const UINT16*)(p = (const void*)&((const UINT16*)p)[1]))[-1]) +#define READINT32(p) readlong(&((const INT32*)(p = (const void*)&((const INT32*)p)[1]))[-1]) +#define READUINT32(p) readulong(&((const UINT32*)(p = (const void*)&((const UINT32*)p)[1])) +#define READCHAR(p) ((const char*)(p = (const void*)&((const char*)p)[1]))[-1] +#define READFIXED(p) readlong(&((const fixed_t*)(p = (const void*)&((const fixed_t*)p)[1]))[-1]) +#define READANGLE(p) readulong(&((const angle_t*)(p = (const void*)&((const angle_t*)p)[1]))[-1]) #endif //SRB2_BIG_ENDIAN #define WRITESTRINGN(p, s, n) do { \ diff --git a/src/command.c b/src/command.c index eae29f07f..ba93a592a 100644 --- a/src/command.c +++ b/src/command.c @@ -281,7 +281,7 @@ char *com_argv[MAX_ARGS]; static const char *com_null_string = ""; static char *com_args = NULL; // current command args or NULL -static void Got_NetVar(UINT8 **p, INT32 playernum); +static void Got_NetVar(const UINT8 **p, INT32 playernum); /** Initializes command buffer and adds basic commands. */ @@ -1500,11 +1500,11 @@ badinput: static boolean serverloading = false; -static void Got_NetVar(UINT8 **p, INT32 playernum) +static void Got_NetVar(const UINT8 **p, INT32 playernum) { consvar_t *cvar; UINT16 netid; - char *svalue; + const char *svalue; UINT8 stealth = false; if (playernum != serverplayer && !IsPlayerAdmin(playernum) && !serverloading) @@ -1518,9 +1518,10 @@ static void Got_NetVar(UINT8 **p, INT32 playernum) } return; } + netid = READUINT16(*p); cvar = CV_FindNetVar(netid); - svalue = (char *)*p; + svalue = (const char *)*p; SKIPSTRING(*p); stealth = READUINT8(*p); @@ -1576,8 +1577,9 @@ void CV_SaveNetVars(UINT8 **p, boolean isdemorecording) WRITEUINT16(count_p, count); } -void CV_LoadNetVars(UINT8 **p) +size_t CV_LoadNetVars(const UINT8 *bufstart) { + const UINT8 *p = bufstart; consvar_t *cvar; UINT16 count; @@ -1588,11 +1590,13 @@ void CV_LoadNetVars(UINT8 **p) if (cvar->flags & CV_NETVAR) Setvalue(cvar, cvar->defaultvalue, true); - count = READUINT16(*p); + count = READUINT16(p); while (count--) - Got_NetVar(p, 0); + Got_NetVar(&p, 0); serverloading = false; + + return p - bufstart; } static void CV_SetCVar(consvar_t *var, const char *value, boolean stealth); diff --git a/src/command.h b/src/command.h index 6d1944f9a..7074158e1 100644 --- a/src/command.h +++ b/src/command.h @@ -182,7 +182,7 @@ void CV_SaveVariables(FILE *f); // load/save gamesate (load and save option and for network join in game) void CV_SaveNetVars(UINT8 **p, boolean isdemorecording); -void CV_LoadNetVars(UINT8 **p); +size_t CV_LoadNetVars(const UINT8 *p); // reset cheat netvars after cheats is deactivated void CV_ResetCheatNetVars(void); diff --git a/src/d_clisrv.c b/src/d_clisrv.c index aed5ee347..5bc5b6d5e 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -312,9 +312,9 @@ static inline tic_t ExpandTics(INT32 low, tic_t basetic) // Some extra data function for handle textcmd buffer // ----------------------------------------------------------------- -static void (*listnetxcmd[MAXNETXCMD])(UINT8 **p, INT32 playernum); +static void (*listnetxcmd[MAXNETXCMD])(const UINT8 **p, INT32 playernum); -void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(UINT8 **p, INT32 playernum)) +void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(const UINT8 **p, INT32 playernum)) { #ifdef PARANOIA if (id >= MAXNETXCMD) @@ -460,12 +460,12 @@ static void ExtraDataTicker(void) { if (playeringame[i] || i == 0) { - UINT8 *bufferstart = D_GetExistingTextcmd(gametic, i); + const UINT8 *bufferstart = D_GetExistingTextcmd(gametic, i); if (bufferstart) { - UINT8 *curpos = bufferstart; - UINT8 *bufferend = &curpos[curpos[0]+1]; + const UINT8 *curpos = bufferstart; + const UINT8 *bufferend = &curpos[curpos[0]+1]; curpos++; while (curpos < bufferend) @@ -3756,7 +3756,7 @@ static void Command_Kick(void) CONS_Printf(M_GetText("Only the server or a remote admin can use this.\n")); } -static void Got_KickCmd(UINT8 **p, INT32 playernum) +static void Got_KickCmd(const UINT8 **p, INT32 playernum) { INT32 pnum, msg; char buf[3 + MAX_REASONLENGTH]; @@ -4146,8 +4146,8 @@ consvar_t cv_connectawaittime = {"connectawaittime", "5", CV_SAVE, connectawaitt consvar_t cv_serverinfoscreen = {"serverinfoscreen", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -static void Got_AddPlayer(UINT8 **p, INT32 playernum); -static void Got_RemovePlayer(UINT8 **p, INT32 playernum); +static void Got_AddPlayer(const UINT8 **p, INT32 playernum); +static void Got_RemovePlayer(const UINT8 **p, INT32 playernum); static void Joinable_OnChange(void) { @@ -4399,7 +4399,7 @@ static inline void SV_AddNode(INT32 node) } // Xcmd XD_ADDPLAYER -static void Got_AddPlayer(UINT8 **p, INT32 playernum) +static void Got_AddPlayer(const UINT8 **p, INT32 playernum) { INT16 node, newplayernum; UINT8 splitscreenplayer = 0; @@ -4486,7 +4486,7 @@ static void Got_AddPlayer(UINT8 **p, INT32 playernum) } // Xcmd XD_REMOVEPLAYER -static void Got_RemovePlayer(UINT8 **p, INT32 playernum) +static void Got_RemovePlayer(const UINT8 **p, INT32 playernum) { SINT8 pnum, reason; @@ -5226,7 +5226,7 @@ static void PT_ServerCFG(SINT8 node) scp = netbuffer->u.servercfg.varlengthinputs; CV_LoadPlayerNames(&scp); - CV_LoadNetVars(&scp); + scp += CV_LoadNetVars(scp); /// \note Wait. What if a Lua script uses some global custom variables synched with the NetVars hook? /// Shouldn't them be downloaded even at intermission time? diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 74bed4cdb..91074af63 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -604,7 +604,7 @@ extern consvar_t cv_serverinfoscreen; void D_ClientServerInit(void); // Initialise the other field -void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(UINT8 **p, INT32 playernum)); +void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(const UINT8 **p, INT32 playernum)); void SendNetXCmdForPlayer(UINT8 playerid, netxcmd_t id, const void *param, size_t nparam); #define SendNetXCmd(id, param, nparam) SendNetXCmdForPlayer(0, id, param, nparam) // Shortcut for P1 void SendKick(UINT8 playernum, UINT8 msg); diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 86c9b12b1..2b334d048 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -68,22 +68,22 @@ // protos // ------ -static void Got_NameAndColor(UINT8 **cp, INT32 playernum); -static void Got_WeaponPref(UINT8 **cp, INT32 playernum); -static void Got_Mapcmd(UINT8 **cp, INT32 playernum); -static void Got_ExitLevelcmd(UINT8 **cp, INT32 playernum); -static void Got_SetupVotecmd(UINT8 **cp, INT32 playernum); -static void Got_ModifyVotecmd(UINT8 **cp, INT32 playernum); -static void Got_PickVotecmd(UINT8 **cp, INT32 playernum); -static void Got_RequestAddfilecmd(UINT8 **cp, INT32 playernum); -static void Got_Addfilecmd(UINT8 **cp, INT32 playernum); -static void Got_Pause(UINT8 **cp, INT32 playernum); -static void Got_Respawn(UINT8 **cp, INT32 playernum); -static void Got_RandomSeed(UINT8 **cp, INT32 playernum); -static void Got_RunSOCcmd(UINT8 **cp, INT32 playernum); -static void Got_Teamchange(UINT8 **cp, INT32 playernum); -static void Got_Clearscores(UINT8 **cp, INT32 playernum); -static void Got_DiscordInfo(UINT8 **cp, INT32 playernum); +static void Got_NameAndColor(const UINT8 **cp, INT32 playernum); +static void Got_WeaponPref(const UINT8 **cp, INT32 playernum); +static void Got_Mapcmd(const UINT8 **cp, INT32 playernum); +static void Got_ExitLevelcmd(const UINT8 **cp, INT32 playernum); +static void Got_SetupVotecmd(const UINT8 **cp, INT32 playernum); +static void Got_ModifyVotecmd(const UINT8 **cp, INT32 playernum); +static void Got_PickVotecmd(const UINT8 **cp, INT32 playernum); +static void Got_RequestAddfilecmd(const UINT8 **cp, INT32 playernum); +static void Got_Addfilecmd(const UINT8 **cp, INT32 playernum); +static void Got_Pause(const UINT8 **cp, INT32 playernum); +static void Got_Respawn(const UINT8 **cp, INT32 playernum); +static void Got_RandomSeed(const UINT8 **cp, INT32 playernum); +static void Got_RunSOCcmd(const UINT8 **cp, INT32 playernum); +static void Got_Teamchange(const UINT8 **cp, INT32 playernum); +static void Got_Clearscores(const UINT8 **cp, INT32 playernum); +static void Got_DiscordInfo(const UINT8 **cp, INT32 playernum); static void PointLimit_OnChange(void); static void TimeLimit_OnChange(void); @@ -178,13 +178,13 @@ static void Command_Clearscores_f(void); // Remote Administration static void Command_Changepassword_f(void); static void Command_Login_f(void); -static void Got_Login(UINT8 **cp, INT32 playernum); -static void Got_Verification(UINT8 **cp, INT32 playernum); -static void Got_Removal(UINT8 **cp, INT32 playernum); +static void Got_Login(const UINT8 **cp, INT32 playernum); +static void Got_Verification(const UINT8 **cp, INT32 playernum); +static void Got_Removal(const UINT8 **cp, INT32 playernum); static void Command_Verify_f(void); static void Command_RemoveAdmin_f(void); static void Command_MotD_f(void); -static void Got_MotD_f(UINT8 **cp, INT32 playernum); +static void Got_MotD_f(const UINT8 **cp, INT32 playernum); static void Command_ShowScores_f(void); static void Command_ShowTime_f(void); @@ -1913,7 +1913,7 @@ static void SendNameAndColor4(void) SendNetXCmdForPlayer(3, XD_NAMEANDCOLOR, buf, p - buf); } -static void Got_NameAndColor(UINT8 **cp, INT32 playernum) +static void Got_NameAndColor(const UINT8 **cp, INT32 playernum) { player_t *p = &players[playernum]; char name[MAXPLAYERNAME+1]; @@ -2041,15 +2041,17 @@ void SendWeaponPref4(void) SendNetXCmdForPlayer(3, XD_WEAPONPREF, buf, 1); } -static void Got_WeaponPref(UINT8 **cp,INT32 playernum) +static void Got_WeaponPref(const UINT8 **cp, INT32 playernum) { + player_t *player = &players[playernum]; + UINT8 prefs = READUINT8(*cp); - players[playernum].pflags &= ~(PF_FLIPCAM|PF_ANALOGMODE); + player->pflags &= ~(PF_FLIPCAM|PF_ANALOGMODE); if (prefs & 1) - players[playernum].pflags |= PF_FLIPCAM; + player->pflags |= PF_FLIPCAM; if (prefs & 2) - players[playernum].pflags |= PF_ANALOGMODE; + player->pflags |= PF_ANALOGMODE; } void D_SendPlayerConfig(void) @@ -2848,7 +2850,7 @@ static void Command_Map_f(void) * ::serverplayer or ::adminplayer. * \sa D_MapChange */ -static void Got_Mapcmd(UINT8 **cp, INT32 playernum) +static void Got_Mapcmd(const UINT8 **cp, INT32 playernum) { char mapname[MAX_WADPATH+1]; UINT8 flags; @@ -2967,7 +2969,7 @@ static void Command_Pause(void) CONS_Printf(M_GetText("Only the server or a remote admin can use this.\n")); } -static void Got_Pause(UINT8 **cp, INT32 playernum) +static void Got_Pause(const UINT8 **cp, INT32 playernum) { UINT8 dedicatedpause = false; const char *playername; @@ -3079,7 +3081,7 @@ static void Command_Respawn(void) SendNetXCmd(XD_RESPAWN, &buf, 4); } -static void Got_Respawn(UINT8 **cp, INT32 playernum) +static void Got_Respawn(const UINT8 **cp, INT32 playernum) { INT32 respawnplayer = READINT32(*cp); @@ -3114,7 +3116,7 @@ static void Got_Respawn(UINT8 **cp, INT32 playernum) * \param playernum Player responsible for the message. Must be ::serverplayer. * \author Graue */ -static void Got_RandomSeed(UINT8 **cp, INT32 playernum) +static void Got_RandomSeed(const UINT8 **cp, INT32 playernum) { UINT32 seed; @@ -3149,7 +3151,7 @@ static void Command_Clearscores_f(void) * \sa XD_CLEARSCORES, Command_Clearscores_f * \author SSNTails */ -static void Got_Clearscores(UINT8 **cp, INT32 playernum) +static void Got_Clearscores(const UINT8 **cp, INT32 playernum) { INT32 i; @@ -3666,7 +3668,7 @@ static void Command_ServerTeamChange_f(void) } //todo: This and the other teamchange functions are getting too long and messy. Needs cleaning. -static void Got_Teamchange(UINT8 **cp, INT32 playernum) +static void Got_Teamchange(const UINT8 **cp, INT32 playernum) { changeteam_union NetPacket; boolean error = false, wasspectator = false; @@ -4023,7 +4025,7 @@ static void Command_Login_f(void) #endif } -static void Got_Login(UINT8 **cp, INT32 playernum) +static void Got_Login(const UINT8 **cp, INT32 playernum) { #ifdef NOMD5 // If we have no MD5 support then completely disable XD_LOGIN responses for security. @@ -4133,7 +4135,7 @@ static void Command_Verify_f(void) SendNetXCmd(XD_VERIFIED, buf, 1); } -static void Got_Verification(UINT8 **cp, INT32 playernum) +static void Got_Verification(const UINT8 **cp, INT32 playernum) { INT16 num = READUINT8(*cp); @@ -4185,7 +4187,7 @@ static void Command_RemoveAdmin_f(void) SendNetXCmd(XD_DEMOTED, buf, 1); } -static void Got_Removal(UINT8 **cp, INT32 playernum) +static void Got_Removal(const UINT8 **cp, INT32 playernum) { INT16 num = READUINT8(*cp); @@ -4261,7 +4263,7 @@ static void Command_MotD_f(void) Z_Free(mymotd); } -static void Got_MotD_f(UINT8 **cp, INT32 playernum) +static void Got_MotD_f(const UINT8 **cp, INT32 playernum) { char *mymotd = Z_Malloc(sizeof(motd), PU_STATIC, NULL); INT32 i; @@ -4328,7 +4330,7 @@ static void Command_RunSOC(void) SendNetXCmd(XD_RUNSOC, buf, length); } -static void Got_RunSOCcmd(UINT8 **cp, INT32 playernum) +static void Got_RunSOCcmd(const UINT8 **cp, INT32 playernum) { char filename[256]; filestatus_t ncs = FS_NOTCHECKED; @@ -4606,7 +4608,7 @@ static void Command_GLocalSkin (void) } } -static void Got_RequestAddfilecmd(UINT8 **cp, INT32 playernum) +static void Got_RequestAddfilecmd(const UINT8 **cp, INT32 playernum) { char filename[241]; filestatus_t ncs = FS_NOTCHECKED; @@ -4665,7 +4667,7 @@ static void Got_RequestAddfilecmd(UINT8 **cp, INT32 playernum) COM_BufAddText(va("addfile %s\n", filename)); } -static void Got_Addfilecmd(UINT8 **cp, INT32 playernum) +static void Got_Addfilecmd(const UINT8 **cp, INT32 playernum) { char filename[241]; filestatus_t ncs = FS_NOTCHECKED; @@ -5465,7 +5467,7 @@ static void Command_ExitLevel_f(void) SendNetXCmd(XD_EXITLEVEL, NULL, 0); } -static void Got_ExitLevelcmd(UINT8 **cp, INT32 playernum) +static void Got_ExitLevelcmd(const UINT8 **cp, INT32 playernum) { (void)cp; @@ -5486,7 +5488,7 @@ static void Got_ExitLevelcmd(UINT8 **cp, INT32 playernum) G_ExitLevel(); } -static void Got_SetupVotecmd(UINT8 **cp, INT32 playernum) +static void Got_SetupVotecmd(const UINT8 **cp, INT32 playernum) { INT32 i; UINT8 gt, secondgt; @@ -5538,7 +5540,7 @@ static void Got_SetupVotecmd(UINT8 **cp, INT32 playernum) Y_StartVote(); } -static void Got_ModifyVotecmd(UINT8 **cp, INT32 playernum) +static void Got_ModifyVotecmd(const UINT8 **cp, INT32 playernum) { SINT8 voted = READSINT8(*cp); UINT8 p = READUINT8(*cp); @@ -5547,7 +5549,7 @@ static void Got_ModifyVotecmd(UINT8 **cp, INT32 playernum) votes[p] = voted; } -static void Got_PickVotecmd(UINT8 **cp, INT32 playernum) +static void Got_PickVotecmd(const UINT8 **cp, INT32 playernum) { SINT8 pick = READSINT8(*cp); SINT8 level = READSINT8(*cp); @@ -6187,7 +6189,7 @@ static void KartEliminateLast_OnChange(void) P_CheckRacers(); } -void Got_DiscordInfo(UINT8 **p, INT32 playernum) +void Got_DiscordInfo(const UINT8 **p, INT32 playernum) { if (playernum != serverplayer /*&& !IsPlayerAdmin(playernum)*/) { diff --git a/src/g_demo.c b/src/g_demo.c index bd3905160..f5268ad02 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -2815,7 +2815,7 @@ void G_DoPlayDemo(char *defdemoname) } // net var data - CV_LoadNetVars(&demobuf.p); + demobuf.p += CV_LoadNetVars(demobuf.p); // Sigh ... it's an empty demo. if (*demobuf.p == DEMOMARKER) @@ -2853,7 +2853,7 @@ void G_DoPlayDemo(char *defdemoname) #endif // net var data - CV_LoadNetVars(&demobuf.p); + demobuf.p += CV_LoadNetVars(demobuf.p); // Sigh ... it's an empty demo. if (*demobuf.p == DEMOMARKER) diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 0e29a5124..955bebb2f 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -280,7 +280,7 @@ static void Command_Say_f(void); static void Command_Sayto_f(void); static void Command_Sayteam_f(void); static void Command_CSay_f(void); -static void Got_Saycmd(UINT8 **p, INT32 playernum); +static void Got_Saycmd(const UINT8 **p, INT32 playernum); void HU_LoadGraphics(void) { @@ -879,11 +879,12 @@ const char *HU_SkinColorToConsoleColor(skincolors_t color) * \sa DoSayCommand * \author Graue */ -static void Got_Saycmd(UINT8 **p, INT32 playernum) +static void Got_Saycmd(const UINT8 **p, INT32 playernum) { SINT8 target; UINT8 flags; const char *dispname; + char buf[HU_MAXMSGLEN + 1]; char *msg; boolean action = false; char *ptr; @@ -893,8 +894,8 @@ static void Got_Saycmd(UINT8 **p, INT32 playernum) target = READSINT8(*p); flags = READUINT8(*p); - msg = (char *)*p; - SKIPSTRINGL(*p, HU_MAXMSGLEN + 1); + msg = buf; + READSTRINGL(*p, msg, HU_MAXMSGLEN + 1); if ((cv_mute.value || flags & (HU_CSAY|HU_SERVER_SAY)) && playernum != serverplayer && !(IsPlayerAdmin(playernum))) { diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index ee5de8356..9a89361a8 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -36,7 +36,7 @@ static void clear_lua_stack(void) lua_settop(gL, 0); // clear stack } -void Got_Luacmd(UINT8 **cp, INT32 playernum) +void Got_Luacmd(const UINT8 **cp, INT32 playernum) { UINT8 i, argc, flags; const char *argv[256]; diff --git a/src/lua_script.h b/src/lua_script.h index f1b58cced..35dd5b364 100644 --- a/src/lua_script.h +++ b/src/lua_script.h @@ -76,7 +76,7 @@ void LUA_InvalidatePlayer(player_t *player); void LUA_Archive(savebuffer_t *save, boolean network); void LUA_UnArchive(savebuffer_t *save, boolean network); -void Got_Luacmd(UINT8 **cp, INT32 playernum); // lua_consolelib.c +void Got_Luacmd(const UINT8 **cp, INT32 playernum); // lua_consolelib.c void LUA_CVarChanged(void *cvar); // lua_consolelib.c int Lua_optoption(lua_State *L, int narg, int def, int list_ref); int Lua_CreateFieldTable(lua_State *L, const char *const lst[]); diff --git a/src/p_saveg.c b/src/p_saveg.c index 65b15ec8e..9b7ff7776 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -3772,7 +3772,7 @@ boolean P_LoadGame(savebuffer_t *save, INT16 mapoverride) boolean P_LoadNetGame(savebuffer_t *save, boolean reloading) { - CV_LoadNetVars(&save->p); + save->p += CV_LoadNetVars(save->p); if (!P_NetUnArchiveMisc(save, reloading)) return false; diff --git a/src/sdl/mixer_sound.c b/src/sdl/mixer_sound.c index 646d44135..e4e21949b 100644 --- a/src/sdl/mixer_sound.c +++ b/src/sdl/mixer_sound.c @@ -266,13 +266,13 @@ void I_UpdateSound(void) // this is as fast as I can possibly make it. // sorry. more asm needed. -static Mix_Chunk *ds2chunk(void *stream) +static Mix_Chunk *ds2chunk(const void *stream) { UINT16 ver, freq; UINT32 samples, i, newsamples; UINT8 *sound; - SINT8 *s; + const SINT8 *s; INT16 *d; INT16 o; fixed_t step, frac; @@ -325,7 +325,7 @@ static Mix_Chunk *ds2chunk(void *stream) sound = Z_Malloc(newsamples<<2, PU_SOUND, NULL); // samples * frequency shift * bytes per sample * channels - s = (SINT8 *)stream; + s = (const SINT8 *)stream; d = (INT16 *)sound; i = 0; -- 2.54.0 From aeb172f2abd858d19b5a4d1eaaa09d0d84ba21fd Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 22:35:34 +0100 Subject: [PATCH 075/116] do some smol cleanup r_skins mostly style fixes, some minor caching for some things --- src/r_skins.c | 228 +++++++++++++++++++++++++++----------------------- 1 file changed, 124 insertions(+), 104 deletions(-) diff --git a/src/r_skins.c b/src/r_skins.c index 9d289f936..bf731f708 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -33,7 +33,7 @@ #include "qs22j.h" -CV_PossibleValue_t Forceskin_cons_t[MAXSKINS+2]; +CV_PossibleValue_t Forceskin_cons_t[MAXSKINS+2]; // huehuehuehuehue #include "discord.h" @@ -41,6 +41,7 @@ INT32 numskins = 0; INT32 numallskins = 0; INT32 numlocalskins = 0; skin_t skins[MAXSKINS]; + UINT8 skinstats[9][9][MAXSKINS]; UINT8 skinstatscount[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0}, @@ -53,6 +54,7 @@ UINT8 skinstatscount[9][9] = { {0, 1, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0} }; + UINT8 skinsorted[MAXSKINS]; skin_t localskins[MAXLOCALSKINS]; skin_t allskins[MAXSKINS+MAXLOCALSKINS]; @@ -71,12 +73,13 @@ static void Sk_SetDefaultValue(skin_t *skin, boolean local) // set default skin values // memset(skin, 0, sizeof (skin_t)); + snprintf(skin->name, sizeof skin->name, "skin %u", K_GetMobjSkinNum(skin, local)); skin->name[sizeof skin->name - 1] = '\0'; - skin->wadnum = INT16_MAX; - strcpy(skin->sprite, ""); - skin->flags = 0; + skin->wadnum = INT16_MAX; + + strcpy(skin->sprite, ""); strcpy(skin->realname, "Someone"); strcpy(skin->hudname, "???"); @@ -95,8 +98,12 @@ static void Sk_SetDefaultValue(skin_t *skin, boolean local) skin->highresscale = FRACUNIT>>1; for (i = 0; i < sfx_skinsoundslot0; i++) - if (S_sfx[i].skinsound != -1) - skin->soundsid[S_sfx[i].skinsound] = i; + { + const INT32 skinsound = S_sfx[i].skinsound; + + if (skinsound != -1) + skin->soundsid[skinsound] = i; + } } // @@ -124,6 +131,7 @@ void R_InitSkins(void) skin = &skins[0]; numskins = 1; Sk_SetDefaultValue(skin, false); + memset(skinstats, 0, sizeof(skinstats)); memset(skinsorted, 0, sizeof(skinsorted)); @@ -132,13 +140,16 @@ void R_InitSkins(void) #ifdef SKINVALUES skin_cons_t[0].strvalue = skins[0].name; #endif - skin->flags = 0; + strcpy(skin->realname, "Sonic"); strcpy(skin->hudname, "SONIC"); strncpy(skin->facerank, "PLAYRANK", 9); strncpy(skin->facewant, "PLAYWANT", 9); strncpy(skin->facemmap, "PLAYMMAP", 9); + + skin->flags = 0; + skin->wadnum = 0; // god what have you brought to this world skin->prefcolor = SKINCOLOR_BLUE; skin->localskin = false; @@ -177,9 +188,10 @@ INT32 R_SkinAvailable(const char *name) for (i = 0; i < numskins; i++) { - if (stricmp(skins[i].name,name) == 0) + if (stricmp(skins[i].name, name) == 0) return i; } + return -1; } @@ -191,9 +203,10 @@ INT32 R_AnySkinAvailable(const char *name) for (i = 0; i < numallskins; i++) { - if (stricmp(allskins[i].name,name) == 0) + if (stricmp(allskins[i].name, name) == 0) return i; } + return -1; } @@ -205,20 +218,20 @@ INT32 R_LocalSkinAvailable(const char *name, boolean local) { for (i = 0; i < numlocalskins; i++) { - if (stricmp(localskins[i].name,name) == 0) + if (stricmp(localskins[i].name, name) == 0) return i; } + return -1; } - else - return R_SkinAvailable(name); + + return R_SkinAvailable(name); } // network code calls this when a 'skin change' is received boolean SetPlayerSkin(INT32 playernum, const char *skinname) { INT32 i; - player_t *player = &players[playernum]; for (i = 0; i < numskins; i++) { @@ -230,7 +243,7 @@ boolean SetPlayerSkin(INT32 playernum, const char *skinname) } } - if (P_IsLocalPlayer(player)) + if (P_IsLocalPlayer(&players[playernum])) CONS_Alert(CONS_WARNING, M_GetText("Skin '%s' not found.\n"), skinname); else if (server || IsPlayerAdmin(consoleplayer)) CONS_Alert(CONS_WARNING, M_GetText("Player %d (%s) skin '%s' not found\n"), playernum, player_names[playernum], skinname); @@ -253,6 +266,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) { player->localskin = 1 + i; player->skinlocal = true; + if (player->mo) { player->mo->localskin = &localskins[i]; @@ -270,6 +284,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) { player->localskin = 1 + i; player->skinlocal = false; + if (player->mo) { player->mo->localskin = &skins[i]; @@ -284,6 +299,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) { player->localskin = 0; player->skinlocal = false; + if (player->mo) { player->mo->localskin = 0; @@ -318,6 +334,7 @@ void SetPlayerSkinByNum(INT32 playernum, INT32 skinnum) if (skinnum >= 0 && skinnum < numskins) // Make sure it exists! { player->skin = skinnum; + if (player->mo) player->mo->skin = skin; @@ -360,117 +377,97 @@ void SetPlayerSkinByNum(INT32 playernum, INT32 skinnum) static UINT16 W_CheckForSkinMarkerInPwad(UINT16 wadid, UINT16 startlump) { UINT16 i; - const char *S_SKIN = "S_SKIN"; lumpinfo_t *lump_p; // scan forward, start at if (startlump < wadfiles[wadid]->numlumps) { lump_p = wadfiles[wadid]->lumpinfo + startlump; + for (i = startlump; i < wadfiles[wadid]->numlumps; i++, lump_p++) - if (memcmp(lump_p->name,S_SKIN,6)==0) + { + if (memcmp(lump_p->name, "S_SKIN", 6) == 0) return i; + } } + return INT16_MAX; // not found } //sort function for sorting skin names -static int skinSortFunc(const void *a, const void *b) //tbh i have no clue what the naming conventions for local functions are +static int skinSortFunc(const void *a, const void *b) // tbh i have no clue what the naming conventions for local functions are { - const skin_t *in1 = &skins[*(const UINT8 *)a]; - const skin_t *in2 = &skins[*(const UINT8 *)b]; - INT32 temp = 0; - const UINT8 val_a = *((const UINT8 *)a); - const UINT8 val_b = *((const UINT8 *)b); + int diff = 0; + const UINT8 val_a = *(const UINT8 *)a; + const UINT8 val_b = *(const UINT8 *)b; + const skin_t *in1 = &skins[val_a]; + const skin_t *in2 = &skins[val_b]; - //return (strcmp(in1->realname, in2->realname) < 0) || (strcmp(in1->realname, in2->realname) ==); + // return (strcmp(in1->realname, in2->realname) < 0) || (strcmp(in1->realname, in2->realname) ==); switch (cv_skinselectgridsort.value) { case SKINMENUSORT_REALNAME: - //CONS_Printf("Sorting by realname\n"); + // CONS_Printf("Sorting by realname\n"); // check name - if ((temp = strcmp(in1->realname, in2->realname))) - return temp; - // sort by internal name - return strcmp(in1->name, in2->name); - break; + diff = strcmp(in1->realname, in2->realname); + if (diff != 0) return diff; - case SKINMENUSORT_NAME: - //CONS_Printf("Sorting by name\n"); - return strcmp(in1->name, in2->name); break; - case SKINMENUSORT_SPEED: - //CONS_Printf("Sorting by speed\n"); + // CONS_Printf("Sorting by speed\n"); // check speed - if (in1->kartspeed < in2->kartspeed) - return -1; - else if (in2->kartspeed < in1->kartspeed) - return 1; + diff = in1->kartspeed - in2->kartspeed; + if (diff != 0) return diff; + // then check weight - if (in1->kartweight < in2->kartweight) - return -1; - else if (in2->kartweight < in1->kartweight) - return 1; - // then check name - if ((temp = strcmp(in1->realname, in2->realname))) - return temp; - // sort by internal name - return strcmp(in1->name, in2->name); - break; + diff = in1->kartweight - in2->kartweight; + if (diff != 0) return diff; + // then check name + diff = strcmp(in1->realname, in2->realname); + if (diff != 0) return diff; + + break; case SKINMENUSORT_WEIGHT: - //CONS_Printf("Sorting by weight\n"); + // CONS_Printf("Sorting by weight\n"); // check weight - if (in1->kartweight < in2->kartweight) - return -1; - else if (in2->kartweight < in1->kartweight) - return 1; + diff = in1->kartweight - in2->kartweight; + if (diff != 0) return diff; + // then check speed - if (in1->kartspeed < in2->kartspeed) - return -1; - else if (in2->kartspeed < in1->kartspeed) - return 1; - // then check name - if ((temp = strcmp(in1->realname, in2->realname))) - return temp; - // sort by internal name - return strcmp(in1->name, in2->name); - break; + diff = in1->kartspeed - in2->kartspeed; + if (diff != 0) return diff; + // then check name + diff = strcmp(in1->realname, in2->realname); + if (diff != 0) return diff; + + break; case SKINMENUSORT_PREFCOLOR: - //CONS_Printf("Sorting by prefcolor\n"); + // CONS_Printf("Sorting by prefcolor\n"); // check prefcolor - if (in1->prefcolor < in2->prefcolor) - return -1; - else if (in2->prefcolor < in1->prefcolor) - return 1; + diff = in1->prefcolor - in2->prefcolor; + if (diff != 0) return diff; + // then check name - if ((temp = strcmp(in1->realname, in2->realname))) - return temp; - // sort by internal name - return strcmp(in1->name, in2->name); + diff = strcmp(in1->realname, in2->realname); + if (diff != 0) return diff; + break; - case SKINMENUSORT_ID: - //CONS_Printf("Sorting by id\n"); - //how do i do by ID????? - //wait why dont i just convert the inputs to UINT32s - //please tell me im allowed to define variables in here since its a block - - if (val_a == val_b) - return 0; - else if (val_a < val_b) - return -1; - else - return 1; - + // CONS_Printf("Sorting by id\n"); + // how do i do by ID????? + // wait why dont i just convert the inputs to UINT32s + // please tell me im allowed to define variables in here since its a block + return (int)val_a - (int)val_b; + case SKINMENUSORT_NAME: default: - return strcmp(in1->name, in2->name); break; } - //im scared this somehow will sometimes end up here so im gonna add this here just to be safe + + // im scared this somehow will sometimes end up here so im gonna add this here just to be safe + // now it will often end up here >:3 return strcmp(in1->name, in2->name); } @@ -531,6 +528,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) Sk_SetDefaultValue(skin, local); skin->wadnum = wadnum; hudname = realname = false; + // parse stoken = strtok (buf2, "\r\n= "); while (stoken) @@ -562,18 +560,18 @@ void R_AddSkins(UINT16 wadnum, boolean local) // using the default skin name's number set above else { - const size_t stringspace = - strlen(value) + sizeof lnumskins + 1; + const size_t stringspace = strlen(value) + sizeof lnumskins + 1; char *value2 = Z_Malloc(stringspace, PU_STATIC, NULL); - snprintf(value2, stringspace, - "%s%d", value, lnumskins); + + snprintf(value2, stringspace, "%s%d", value, lnumskins); value2[stringspace - 1] = '\0'; + if (R_LocalSkinAvailable(value2, local) == -1) { - STRBUFCPY(skin->name, - value2); + STRBUFCPY(skin->name, value2); strlwr(skin->name); } + Z_Free(value2); } @@ -589,6 +587,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) { STRBUFCPY(skin->hudname, skin->name); strupr(skin->hudname); + for (value = skin->hudname; *value; value++) if (*value == '_') *value = ' '; // turn _ into spaces. } @@ -597,8 +596,10 @@ void R_AddSkins(UINT16 wadnum, boolean local) { // Display name (eg. "Knuckles") realname = true; STRBUFCPY(skin->realname, value); + for (value = skin->realname; *value; value++) if (*value == '_') *value = ' '; // turn _ into spaces. + if (!hudname) STRBUFCPY(skin->hudname, skin->realname); } @@ -606,12 +607,13 @@ void R_AddSkins(UINT16 wadnum, boolean local) { // Life icon name (eg. "K.T.E") hudname = true; STRBUFCPY(skin->hudname, value); + for (value = skin->hudname; *value; value++) if (*value == '_') *value = ' '; // turn _ into spaces. + if (!realname) STRBUFCPY(skin->realname, skin->hudname); } - else if (!stricmp(stoken, "sprite")) { strupr(value); @@ -642,6 +644,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) else if (!stricmp(stoken, "kartspeed")) { skin->kartspeed = atoi(value); + if (skin->kartspeed < 1) skin->kartspeed = 1; if (skin->kartspeed > 9) @@ -650,6 +653,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) else if (!stricmp(stoken, "kartweight")) { skin->kartweight = atoi(value); + if (skin->kartweight < 1) skin->kartweight = 1; if (skin->kartweight > 9) @@ -657,47 +661,60 @@ void R_AddSkins(UINT16 wadnum, boolean local) } // custom translation table else if (!stricmp(stoken, "startcolor")) + { skin->starttranscolor = atoi(value); + } else if (!stricmp(stoken, "prefcolor")) + { skin->prefcolor = K_GetKartColorByName(value); + } else if (!stricmp(stoken, "highresscale")) + { skin->highresscale = FLOAT_TO_FIXED(atof(value)); + } else { INT32 found = false; sfxenum_t i; + // copy name of sounds that are remapped // for this skin for (i = 0; i < sfx_skinsoundslot0; i++) { - if (!S_sfx[i].name) + const sfxinfo_t *sfx = &S_sfx[i]; + + if (!sfx->name) continue; - if (S_sfx[i].skinsound != -1 - && !stricmp(S_sfx[i].name, - stoken + 2)) + + if (sfx->skinsound != -1 + && !stricmp(sfx->name, stoken + 2)) { - skin->soundsid[S_sfx[i].skinsound] = - S_AddSoundFx(value+2, S_sfx[i].singularity, S_sfx[i].pitch, true); + skin->soundsid[sfx->skinsound] = S_AddSoundFx(value+2, sfx->singularity, sfx->pitch, true); found = true; } } + if (!found) CONS_Debug(DBG_SETUP, "R_AddSkins: Unknown keyword '%s' in S_SKIN lump# %d (WAD %s)\n", stoken, lump, wadfiles[wadnum]->filename); } stoken = strtok(NULL, "\r\n= "); } + free(buf2); lump++; // if no sprite defined use spirte just after this one + if (skin->sprite[0] == '\0') { const char *csprname = W_CheckNameForNumPwad(wadnum, lump); // skip to end of this skin's frames lastlump = lump; + while (W_CheckNameForNumPwad(wadnum, lastlump) && memcmp(W_CheckNameForNumPwad(wadnum, lastlump), csprname,4)==0) lastlump++; + // allocate (or replace) sprite frames, and set spritedef R_AddSingleSpriteDef(csprname, &skin->spritedef, wadnum, lump, lastlump); } @@ -707,12 +724,15 @@ void R_AddSkins(UINT16 wadnum, boolean local) size_t name; boolean found = false; const char *sprname = skin->sprite; - for (name = 0;sprnames[name][0] != '\0';name++) + + for (name = 0; sprnames[name][0] != '\0'; name++) + { if (strncmp(sprnames[name], sprname, 4) == 0) { - found = true; skin->spritedef = sprites[name]; + found = true; } + } // not found so make a new one // go through the entire current wad looking for our sprite @@ -726,7 +746,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) while ((lname = W_CheckNameForNumPwad(wadnum, localllump))) { // If this is a valid sprite... - if (!memcmp(lname, sprname,4) && lname[4] && lname[5] && lname[5] >= '0' && lname[5] <= '8') + if (!memcmp(lname, sprname, 4) && lname[4] && lname[5] && lname[5] >= '0' && lname[5] <= '8') { if (lstart == UINT16_MAX) lstart = localllump; @@ -741,6 +761,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) } // If not already set do nothing } + ++localllump; } @@ -760,7 +781,6 @@ void R_AddSkins(UINT16 wadnum, boolean local) (local ? localskin_cons_t : skin_cons_t)[lnumskins].value = lnumskins; (local ? localskin_cons_t : skin_cons_t)[lnumskins].strvalue = skin->name; #endif - if (!local) { // Update the forceskin possiblevalues -- 2.54.0 From 871545024d13b48643f6cc91b03758f347c1486b Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 23:15:21 +0100 Subject: [PATCH 076/116] experiment: replace every strcmp with fastcmp did some profiling and in basically every single test fastcmp was twice as fast as strcmp maybe this speeds up some things --- src/blua/lauxlib.c | 6 ++++-- src/blua/lfastcmp.h | 32 ++++++++++++++++++++++++++++++++ src/command.c | 10 +++++----- src/console.c | 2 +- src/d_clisrv.c | 4 ++-- src/d_main.c | 2 +- src/d_netcmd.c | 12 ++++++------ src/d_netfil.c | 28 ++++++++++++++-------------- src/d_protocol.c | 4 ++-- src/dedicated/i_system.c | 4 ++-- src/discord.c | 6 +++--- src/doomdef.h | 2 ++ src/filesrch.c | 10 +++++----- src/g_game.c | 11 +++++++---- src/hardware/hw_main.cpp | 2 +- src/hardware/hw_model.c | 8 ++++---- src/lua_hooklib.c | 6 +++--- src/m_aatree.c | 4 ++-- src/m_menu.c | 22 +++++++++++----------- src/m_perfstats.c | 2 +- src/p_saveg.c | 2 +- src/r_data.c | 15 ++++++++------- src/r_patch.cpp | 8 ++++---- src/sdl/hwsym_sdl.c | 3 --- src/sdl/i_system.cpp | 3 ++- src/sdl/i_video.c | 4 ++-- src/sdl/ogl_sdl.c | 4 ++-- src/v_video.c | 5 ++--- 28 files changed, 129 insertions(+), 92 deletions(-) create mode 100644 src/blua/lfastcmp.h diff --git a/src/blua/lauxlib.c b/src/blua/lauxlib.c index e898e38d6..eacce9b44 100644 --- a/src/blua/lauxlib.c +++ b/src/blua/lauxlib.c @@ -24,6 +24,8 @@ #include "lauxlib.h" +#include "lfastcmp.h" + #define FREELIST_REF 0 /* free list of references */ @@ -40,7 +42,7 @@ LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); lua_getinfo(L, "n", &ar); - if (strcmp(ar.namewhat, "method") == 0) { + if (fastcmp(ar.namewhat, "method")) { narg--; /* do not count `self' */ if (narg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling " LUA_QS " on bad self (%s)", @@ -97,7 +99,7 @@ LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, luaL_checkstring(L, narg); int i; for (i=0; lst[i]; i++) - if (strcmp(lst[i], name) == 0) + if (fastcmp(lst[i], name)) return i; return luaL_argerror(L, narg, lua_pushfstring(L, "invalid option " LUA_QS, name)); diff --git a/src/blua/lfastcmp.h b/src/blua/lfastcmp.h new file mode 100644 index 000000000..f25c59896 --- /dev/null +++ b/src/blua/lfastcmp.h @@ -0,0 +1,32 @@ +#ifndef __FASTCMP_H__ +#define __FASTCMP_H__ + +#include +#include + +// same as fastcmp but we cant use our fancy macros + +// returns false if s != c +// returns true if s == c +__attribute__((always_inline)) static inline bool fasticmp(const char *s, const char *c) +{ + for (; *s && toupper(*s) == toupper(*c); s++, c++) ; + return (*s == *c); // make sure both strings ended +} + +// case-sensitive of the above +__attribute__((always_inline)) static inline bool fastcmp(const char *s, const char *c) +{ + for (; *s && *s == *c; s++, c++) ; + return (*s == *c); // make sure both strings ended +} + +// length-limited of the above +// only true if both strings are at least l characters long AND match, case-sensitively! +__attribute__((always_inline)) static inline bool fastncmp(const char *s, const char *c, uint16_t l) +{ + for (; *s && *s == *c && --l; s++, c++) ; + return !l; // make sure you reached the end +} + +#endif diff --git a/src/command.c b/src/command.c index e73125649..676212703 100644 --- a/src/command.c +++ b/src/command.c @@ -879,7 +879,7 @@ static void COM_Help_f(void) { for (cmd = com_commands; cmd; cmd = cmd->next) { - if (strcmp(cmd->name, help)) + if (!fastcmp(cmd->name, help)) continue; CONS_Printf("\x82""Command %s:\n", cmd->name); @@ -1610,7 +1610,7 @@ void CV_ResetCheatNetVars(void) // Returns true if the variable's current value is its default value boolean CV_IsSetToDefault(consvar_t *v) { - return (!(strcmp(v->defaultvalue, v->string))); + return (fastcmp(v->defaultvalue, v->string)); } // If any cheats CVars are not at their default settings, return true. @@ -1622,7 +1622,7 @@ UINT8 CV_CheatsEnabled(void) consvar_t *cvar; for (cvar = consvar_vars; cvar; cvar = cvar->next) - if ((cvar->flags & CV_CHEAT) && strcmp(cvar->defaultvalue, cvar->string)) + if ((cvar->flags & CV_CHEAT) && !fastcmp(cvar->defaultvalue, cvar->string)) return 1; return 0; } @@ -1799,7 +1799,7 @@ void CV_AddValue(consvar_t *var, INT32 increment) } #define MINVAL 0 #define MAXVAL 1 - else if (var->PossibleValue[MINVAL].strvalue && !strcmp(var->PossibleValue[MINVAL].strvalue, "MIN")) + else if (var->PossibleValue[MINVAL].strvalue && fastcmp(var->PossibleValue[MINVAL].strvalue, "MIN")) { // SRB2Kart #ifdef PARANOIA if (!var->PossibleValue[MAXVAL].strvalue) @@ -2139,7 +2139,7 @@ void CV_SaveVariables(FILE *f) char stringtowrite[MAXTEXTCMD+1]; // Silly hack for Min/Max vars - if (!strcmp(cvar->string, "MAX") || !strcmp(cvar->string, "MIN")) + if (fastcmp(cvar->string, "MAX") || fastcmp(cvar->string, "MIN")) { if (cvar->flags & CV_FLOAT) sprintf(stringtowrite, "%f", FixedToFloat(cvar->value)); diff --git a/src/console.c b/src/console.c index 3959d9b98..062e6ebf3 100644 --- a/src/console.c +++ b/src/console.c @@ -1010,7 +1010,7 @@ boolean CON_Responder(event_t *ev) Lock_state(); // Only add command to history if it differs from previous one - if (strcmp(input.buffer, inputlines[(inputline-1) & 31])) + if (!fastcmp(input.buffer, inputlines[(inputline-1) & 31])) { inputline = (inputline+1) & 31; M_TextInputInit(&input, inputlines[inputline], CON_MAXPROMPTCHARS); diff --git a/src/d_clisrv.c b/src/d_clisrv.c index aed5ee347..2ca42df65 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -2174,7 +2174,7 @@ static void SL_InsertServer(serverinfo_pak* info, SINT8 node) if (info->subversion != SUBVERSION) return; // Close, but no cigar. - if (strcmp(info->application, SRB2APPLICATION)) + if (!fastcmp(info->application, SRB2APPLICATION)) return;/* that's a different mod */ i = serverlistcount++; @@ -2219,7 +2219,7 @@ void CL_QueryServerList (msg_server_t *server_list) // thwart nefarious servers who lie to the MS. /* lol bruh, that version COMES from the servers */ - //if (strcmp(version, server_list[i].version) == 0) + //if (fastcmp(version, server_list[i].version)) { INT32 node = I_NetMakeNodewPort(server_list[i].ip, server_list[i].port); if (node == -1) diff --git a/src/d_main.c b/src/d_main.c index 032a9189e..fd643213c 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1288,7 +1288,7 @@ static void IdentifyVersion(void) } #if (1) // reduce the amount of findfile by only using full cwd in this func - if (strcmp(tempsrb2path, srb2waddir)) + if (!fastcmp(tempsrb2path, srb2waddir)) #endif { strlcpy(srb2path, srb2waddir, sizeof (srb2path)); diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 86c9b12b1..3a5e0ca7e 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -1508,9 +1508,9 @@ static void SendNameAndColor(void) CV_StealthSet(&cv_playercolor, cv_playercolor.defaultvalue); } - if (!strcmp(cv_playername.string, player_names[consoleplayer]) + if (fastcmp(cv_playername.string, player_names[consoleplayer]) && cv_playercolor.value == players[consoleplayer].skincolor - && !strcmp(cv_skin.string, skins[players[consoleplayer].skin].name)) + && fastcmp(cv_skin.string, skins[players[consoleplayer].skin].name)) return; // We'll handle it later if we're not playing. @@ -2322,8 +2322,8 @@ static void Command_Playdemo_f(void) CONS_Printf(M_GetText("Playing back demo '%s'.\n"), name); - demo.loadfiles = strcmp(COM_Argv(2), "-addfiles") == 0; - demo.ignorefiles = strcmp(COM_Argv(2), "-force") == 0; + demo.loadfiles = fastcmp(COM_Argv(2), "-addfiles"); + demo.ignorefiles = fastcmp(COM_Argv(2), "-force"); // Internal if no extension, external if one exists // If external, convert the file name to a path in SRB2's home directory @@ -5209,14 +5209,14 @@ static void Ringslinger_OnChange(void) static void Gravity_OnChange(void) { if (!M_SecretUnlocked(SECRET_PANDORA) && !netgame && !cv_debug - && strcmp(cv_gravity.string, cv_gravity.defaultvalue)) + && !fastcmp(cv_gravity.string, cv_gravity.defaultvalue)) { CONS_Printf(M_GetText("You haven't earned this yet.\n")); CV_StealthSet(&cv_gravity, cv_gravity.defaultvalue); return; } #ifndef NETGAME_GRAVITY - if(netgame) + if (netgame) { CV_StealthSet(&cv_gravity, cv_gravity.defaultvalue); return; diff --git a/src/d_netfil.c b/src/d_netfil.c index 5a1272172..f279eaee0 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -946,17 +946,17 @@ void Got_Filetxpak(void) char *filename = file->filename; static INT32 filetime = 0; - if (!(strcmp(filename, "srb2.srb") - //&& strcmp(filename, "srb2.wad") - //&& strcmp(filename, "patch.dta") - //&& strcmp(filename, "music.dta") - && strcmp(filename, "gfx.kart") - && strcmp(filename, "textures.kart") - && strcmp(filename, "chars.kart") - && strcmp(filename, "maps.kart") - && strcmp(filename, "sounds.kart") - && strcmp(filename, "music.kart") - && strcmp(filename, "patch.kart") + if ((fastcmp(filename, "srb2.srb") + //|| fastcmp(filename, "srb2.wad") + //|| fastcmp(filename, "patch.dta") + //|| fastcmp(filename, "music.dta") + || fastcmp(filename, "gfx.kart") + || fastcmp(filename, "textures.kart") + || fastcmp(filename, "chars.kart") + || fastcmp(filename, "maps.kart") + || fastcmp(filename, "sounds.kart") + || fastcmp(filename, "music.kart") + || fastcmp(filename, "patch.kart") )) I_Error("Tried to download \"%s\"", filename); @@ -1197,7 +1197,7 @@ filestatus_t findfile(char *filename, const UINT8 *wantedmd5sum, boolean complet } // next, check SRB2's "home" directory (if non-'.') - if (strcmp(srb2home, ".")) + if (!fastcmp(srb2home, ".")) { homecheck = filesearch(filename, srb2home, wantedmd5sum, completepath, 10); @@ -1209,7 +1209,7 @@ filestatus_t findfile(char *filename, const UINT8 *wantedmd5sum, boolean complet } // next, check SRB2's "path" directory (also if non-'.') - if (strcmp(srb2path, ".")) + if (!fastcmp(srb2path, ".")) { homecheck = filesearch(filename, srb2path, wantedmd5sum, completepath, 10); @@ -1554,7 +1554,7 @@ CURLGetLogin (const char *url, HTTP_login ***return_prev_next) ( login = (*prev_next)); prev_next = &login->next ){ - if (strcmp(login->url, url) == 0) + if (fastcmp(login->url, url) != 0) { if (return_prev_next) (*return_prev_next) = prev_next; diff --git a/src/d_protocol.c b/src/d_protocol.c index 6ceb05100..963d8e587 100644 --- a/src/d_protocol.c +++ b/src/d_protocol.c @@ -211,12 +211,12 @@ void D_SetupProtocol(void) if (result) { - if (strcmp(buffer, "no") == 0) + if (!fastcmp(buffer, "no")) { fclose(fp); return; } - else if (strcmp(buffer, exe_path) != 0) + else if (fastcmp(buffer, exe_path)) { // overwrite fclose(fp); diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index 78f265e2a..d2ffa12ad 100644 --- a/src/dedicated/i_system.c +++ b/src/dedicated/i_system.c @@ -1709,9 +1709,9 @@ char *I_GetUserName(void) strncpy(username, p, MAXPLAYERNAME); } - - if (strcmp(username, "") != 0) + if (!fastcmp(username, "")) return username; + return NULL; // dummy for platform independent version } diff --git a/src/discord.c b/src/discord.c index f94cd574d..8f937cfc1 100644 --- a/src/discord.c +++ b/src/discord.c @@ -277,7 +277,7 @@ static void DRPC_HandleJoinRequest(const DiscordUser *requestUser) while (append != NULL) { // CHECK FOR DUPES!! Ignore any that already exist from the same user. - if (!strcmp(newRequest->userID, append->userID)) + if (fastcmp(newRequest->userID, append->userID)) { Discord_Respond(newRequest->userID, DISCORD_REPLY_IGNORE); DRPC_RemoveRequest(newRequest); @@ -419,7 +419,7 @@ static const char *DRPC_GetServerIP(void) // If you're connected if (I_GetNodeAddress && (address = I_GetNodeAddress(servernode)) != NULL) { - if (strcmp(address, "self")) + if (!fastcmp(address, "self")) { // We're not the server, so we could successfully get the IP! // No need to do anything else :) @@ -684,7 +684,7 @@ void DRPC_UpdatePresence(void) // Character image while (supportedSkins[checkSkin] != NULL) { - if (!strcmp(skins[players[consoleplayer].skin].name, supportedSkins[checkSkin])) + if (fastcmp(skins[players[consoleplayer].skin].name, supportedSkins[checkSkin])) { snprintf(charimg, 21, "char%s", supportedSkins[checkSkin]); discordPresence.smallImageKey = charimg; diff --git a/src/doomdef.h b/src/doomdef.h index a0c76fa61..0329eb7f8 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -69,6 +69,8 @@ extern "C" { #include #include +#include "fastcmp.h" + #ifdef _WIN32 #include #endif diff --git a/src/filesrch.c b/src/filesrch.c index 628a221c2..b9821d368 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -353,7 +353,7 @@ void searchfilemenu(char *tempname) { for (i = first; i < sizedirmenu; i++) { - if (!strcmp(dirmenu[i]+DIR_STRING, tempname)) + if (fastcmp(dirmenu[i]+DIR_STRING, tempname)) { dir_on[menudepthleft] = i; break; @@ -400,7 +400,7 @@ void searchfilemenu(char *tempname) { if (filemenucmp(coredirmenu[i]+DIR_STRING, localmenusearch)) { - if (tempname && !strcmp(coredirmenu[i]+DIR_STRING, tempname)) + if (tempname && fastcmp(coredirmenu[i]+DIR_STRING, tempname)) { dir_on[menudepthleft] = sizedirmenu; Z_Free(tempname); @@ -587,7 +587,7 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) nameonly(filenamebuf[i]); } - if (strcmp(dent->d_name, filenamebuf[i])) + if (!fastcmp(dent->d_name, filenamebuf[i])) continue; if (cv_addons_md5.value && !checkfilemd5(menupath, wadfiles[i]->md5sum)) @@ -598,11 +598,11 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) } else if (ext == EXT_TXT) { - if (!strncmp(dent->d_name, "log-", 4) || !strcmp(dent->d_name, "errorlog.txt")) + if (!strncmp(dent->d_name, "log-", 4) || fastcmp(dent->d_name, "errorlog.txt")) ext |= EXT_LOADED; } - if (!strcmp(dent->d_name, configfile)) + if (fastcmp(dent->d_name, configfile)) ext |= EXT_LOADED; } diff --git a/src/g_game.c b/src/g_game.c index 796c154d5..05615df78 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -3463,7 +3463,8 @@ void G_LoadGameData(void) if (READUINT32(save.p) != 0xFCAFE211) { const char *gdfolder = "the SRB2Kart folder"; - if (strcmp(srb2home,".")) + + if (!fastcmp(srb2home,".")) gdfolder = srb2home; Z_Free(save.buffer); @@ -3547,7 +3548,8 @@ void G_LoadGameData(void) datacorrupt: { const char *gdfolder = "the SRB2Kart folder"; - if (strcmp(srb2home,".")) + + if (!fastcmp(srb2home,".")) gdfolder = srb2home; Z_Free(save.buffer); @@ -3758,7 +3760,8 @@ void G_LoadGame(UINT32 slot, INT16 mapoverride) memset(vcheck, 0, sizeof (vcheck)); sprintf(vcheck, "version %d", VERSION); - if (strcmp((const char *)save.p, (const char *)vcheck)) + + if (!fastcmp((const char *)save.p, (const char *)vcheck)) { #ifdef SAVEGAME_OTHERVERSIONS M_StartMessage(M_GetText("Save game from different version.\nYou can load this savegame, but\nsaving afterwards will be disabled.\n\nDo you want to continue anyway?\n\n(Press 'Y' to confirm)\n"), @@ -4036,7 +4039,7 @@ char *G_BuildMapTitle(INT32 mapnum) if (!mapheaderinfo[mapnum-1]) P_AllocMapHeader(mapnum-1); - if (strcmp(mapheaderinfo[mapnum-1]->lvlttl, "")) + if (!fastcmp(mapheaderinfo[mapnum-1]->lvlttl, "")) { size_t len = 1; const char *zonetext = NULL; diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 45f25c2a6..be96fc901 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -5840,7 +5840,7 @@ static void COM_HWR_glinfo(void) { argv = COM_Argv(i); - if (strcmp(argv, "--list-extensions") == 0 || strcmp(argv, "-l") == 0) + if (fastcmp(argv, "--list-extensions")|| fastcmp(argv, "-l")) { list_extensions = 1; } diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 6a9825402..77a995ed0 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -163,22 +163,22 @@ model_t *LoadModel(const char *filename, int ztag) return NULL; } - if (!strcmp(extension, ".md3")) + if (fastcmp(extension, ".md3")) { if (!(model = MD3_LoadModel(filename, ztag, false))) return NULL; } - else if (!strcmp(extension, ".md3s")) // MD3 that will be converted in memory to use full floats + else if (fastcmp(extension, ".md3s")) // MD3 that will be converted in memory to use full floats { if (!(model = MD3_LoadModel(filename, ztag, true))) return NULL; } - else if (!strcmp(extension, ".md2")) + else if (fastcmp(extension, ".md2")) { if (!(model = MD2_LoadModel(filename, ztag, false))) return NULL; } - else if (!strcmp(extension, ".md2s")) + else if (fastcmp(extension, ".md2s")) { if (!(model = MD2_LoadModel(filename, ztag, true))) return NULL; diff --git a/src/lua_hooklib.c b/src/lua_hooklib.c index 6d04b6154..50dd46c61 100644 --- a/src/lua_hooklib.c +++ b/src/lua_hooklib.c @@ -83,7 +83,7 @@ FUNCINLINE static ATTRINLINE unsigned hook_in_list for (type = 0; list[type] != NULL; ++type) { - if (strcmp(name, list[type]) == 0) + if (fastcmp(name, list[type])) break; } @@ -240,7 +240,7 @@ static int lib_addHook(lua_State *L) { add_hook(&hookIds[type]); } - /*else if (strcmp(name, "HUD") == 0) // ehh this is cool and all, but i dont want modders potentially breaking vanilla clients lol + /*else if (fastcmp(name, "HUD")) // ehh this is cool and all, but i dont want modders potentially breaking vanilla clients lol { add_hud_hook(L, 3); }*/ @@ -818,7 +818,7 @@ typedef struct { FUNCINLINE static ATTRINLINE boolean checkbotkey(const char *field) { - return lua_toboolean(gL, -1) && strcmp(lua_tostring(gL, -2), field) == 0; + return lua_toboolean(gL, -1) && fastcmp(lua_tostring(gL, -2), field); } static void res_botai(Hook_State *hook) diff --git a/src/m_aatree.c b/src/m_aatree.c index 34e8e1d87..f78355eaf 100644 --- a/src/m_aatree.c +++ b/src/m_aatree.c @@ -183,7 +183,7 @@ static aatree_node_t *M_AATreeSetString_Node(aatree_node_t *node, UINT32 flags, else { aatree_entry_t *entry = node->value; - if (entry != NULL && strcmp(entry->key, key) != 0) + if (entry != NULL && !fastcmp(entry->key, key)) entry = entry->next; if (entry != NULL) { @@ -252,7 +252,7 @@ void *M_AATreeGetString(aatree_t *aatree, const char *key) I_Assert((aatree->flags & AATREE_STRING) == AATREE_STRING); UINT32 hash = FNV1a_HashString(key); aatree_entry_t *entry = M_AATreeGet_Node(aatree->root, hash); - while (entry != NULL && strcmp(entry->key, key) != 0) + while (entry != NULL && !fastcmp(entry->key, key)) entry = entry->next; return entry != NULL ? entry->value : NULL; } diff --git a/src/m_menu.c b/src/m_menu.c index 49398df34..bd79ec80c 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -3719,10 +3719,10 @@ static void M_HandleAddons(INT32 choice) break; case EXT_TXT: case EXT_CFG: - if ((strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, CONFIGFILENAME) == 0) - || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, AUTOLOADCONFIGFILENAME) == 0) - || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartserv.cfg") == 0) - || (strcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartexec.cfg") == 0)) + if (fastcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, CONFIGFILENAME) + || fastcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, AUTOLOADCONFIGFILENAME) + || fastcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartserv.cfg") + || fastcmp(dirmenu[dir_on[menudepthleft]]+DIR_STRING, "kartexec.cfg")) { M_StartMessage(va("%c%s\x80\nYou can't autoload this builds' base console scripts, silly!\n They're already autoloaded on startup! \n\n(Press a key)\n", ('\x80' + (highlightflags>>V_CHARCOLORSHIFT)), dirmenu[dir_on[menudepthleft]]+DIR_STRING),NULL,MM_NOTHING); S_StartSound(NULL, sfx_s26d); @@ -3830,7 +3830,7 @@ static void ReplayNamesLoadThread(void* userdata) Lock_search_state(); - if (strcmp(menupath, replaydirpath) == 0) + if (fastcmp(menupath, replaydirpath)) { memcpy(demolist_all, demolist_all_local, sizeof(menudemo_t)*sizedirmenu); replaynamesloaded = true; @@ -6799,7 +6799,7 @@ static int ServerListEntryComparator_##key(const void *entry1, const void *entry const serverelem_t *sa = (const serverelem_t*)entry1, *sb = (const serverelem_t*)entry2; \ if (sa->info.key != sb->info.key) \ return sa->info.key - sb->info.key; \ - return strcmp(sa->info.servername, sb->info.servername); \ + return !fastcmp(sa->info.servername, sb->info.servername); \ } // This does descending instead of ascending. @@ -6809,7 +6809,7 @@ static int ServerListEntryComparator_##key##_reverse(const void *entry1, const v const serverelem_t *sa = (const serverelem_t*)entry1, *sb = (const serverelem_t*)entry2; \ if (sb->info.key != sa->info.key) \ return sb->info.key - sa->info.key; \ - return strcmp(sb->info.servername, sa->info.servername); \ + return !fastcmp(sb->info.servername, sa->info.servername); \ } SERVER_LIST_ENTRY_COMPARATOR(time) @@ -6830,8 +6830,8 @@ static int ServerListEntryComparator_modified(const void *entry1, const void *en if (modstate_a != modstate_b) return modstate_a - modstate_b; - // Default to strcmp. - return strcmp(sa->info.servername, sb->info.servername); + // Default to !fastcmp. + return !fastcmp(sa->info.servername, sb->info.servername); } void M_SortServerList(void) @@ -8808,7 +8808,7 @@ static boolean M_QuitMultiPlayerMenu(void) size_t l; // send name if changed - if (strcmp(setupm_name, setupm_cvname->string)) + if (!fastcmp(setupm_name, setupm_cvname->string)) { // remove trailing whitespaces for (l= strlen(setupm_name)-1; @@ -9469,7 +9469,7 @@ static void M_VideoModeMenu(INT32 choice) // VESA mode, which is always a higher modenum for (j = 0; j < vidm_nummodes; j++) { - if (!strcmp(modedescs[j].desc, desc)) + if (fastcmp(modedescs[j].desc, desc)) { // mode(0): 320x200 is always standard VGA, not vesa if (modedescs[j].modenum) diff --git a/src/m_perfstats.c b/src/m_perfstats.c index 7384a6086..75aad72e2 100644 --- a/src/m_perfstats.c +++ b/src/m_perfstats.c @@ -916,7 +916,7 @@ static void draw_think_frame_stats(int hook_length, ps_hookinfo_t *hook) int len = (int)strlen(str); char* str_ptr; - if (strcmp(".lua", str + len - 4) == 0) + if (fastcmp(".lua", str + len - 4)) { str[len-4] = '\0'; // remove .lua at end } diff --git a/src/p_saveg.c b/src/p_saveg.c index d3a162e2d..570e8e1f0 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -3391,7 +3391,7 @@ FUNCINLINE static ATTRINLINE void P_UnArchiveSPGame(savebuffer_t *save, INT16 ma READSTRINGN(save->p, testname, sizeof(testname)); - if (strcmp(testname, timeattackfolder)) + if (!fastcmp(testname, timeattackfolder)) { if (modifiedgame) I_Error("Save game not for this modification."); diff --git a/src/r_data.c b/src/r_data.c index 93ad621fa..893252571 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -867,7 +867,7 @@ static texpatch_t *R_ParsePatch(boolean actuallyLoadPatch) I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after \"%s\"'s patch name should be",patchName); } - if (strcmp(texturesToken,",")!=0) + if (!fastcmp(texturesToken,",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after %s's patch name, got \"%s\"",patchName,texturesToken); } @@ -907,7 +907,7 @@ static texpatch_t *R_ParsePatch(boolean actuallyLoadPatch) I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after patch \"%s\"'s x coordinate should be",patchName); } - if (strcmp(texturesToken,",")!=0) + if (!fastcmp(texturesToken,",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after patch \"%s\"'s x coordinate, got \"%s\"",patchName,texturesToken); } @@ -996,7 +996,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after texture \"%s\"'s name should be",newTextureName); } - else if (strcmp(texturesToken,",")!=0) + else if (!fastcmp(texturesToken,",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after texture \"%s\"'s name, got \"%s\"",newTextureName,texturesToken); } @@ -1030,7 +1030,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after texture \"%s\"'s width should be",newTextureName); } - if (strcmp(texturesToken,",")!=0) + if (!fastcmp(texturesToken,",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after texture \"%s\"'s width, got \"%s\"",newTextureName,texturesToken); } @@ -1066,7 +1066,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) I_Error("Error parsing TEXTURES lump: Unexpected end of file where open curly brace for texture \"%s\" should be",newTextureName); } - if (strcmp(texturesToken,"{")==0) + if (fastcmp(texturesToken,"{")) { if (actuallyLoadTexture) { @@ -1084,7 +1084,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where patch definition for texture \"%s\" should be",newTextureName); } - while (strcmp(texturesToken,"}")!=0) + while (!fastcmp(texturesToken,"}")) { if (stricmp(texturesToken, "PATCH")==0) { @@ -1334,8 +1334,9 @@ lumpnum_t R_GetFlatNumForName(const char *name) if (lump == LUMPERROR) { - if (strcmp(name, SKYFLATNAME)) + if (!fastcmp(name, SKYFLATNAME)) CONS_Debug(DBG_SETUP, "R_GetFlatNumForName: Could not find flat %.8s\n", name); + lump = W_CheckNumForName("REDFLR"); } diff --git a/src/r_patch.cpp b/src/r_patch.cpp index 09aca078a..1e09ae7bb 100644 --- a/src/r_patch.cpp +++ b/src/r_patch.cpp @@ -63,7 +63,7 @@ static void R_ParseSpriteInfoFrame(spriteinfo_t *info) I_Error("Error parsing SPRTINFO lump: Missing sprite info"); else { - if (strcmp(sprinfoToken,"{")==0) + if (fastcmp(sprinfoToken,"{")) { Z_Free(sprinfoToken); sprinfoToken = M_GetToken(NULL); @@ -71,7 +71,7 @@ static void R_ParseSpriteInfoFrame(spriteinfo_t *info) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite info should be"); } - while (strcmp(sprinfoToken,"}")!=0) + while (!fastcmp(sprinfoToken,"}")) { if (stricmp(sprinfoToken, "XPIVOT")==0) { @@ -175,7 +175,7 @@ static void R_ParseSpriteInfo(boolean spr2) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where open curly brace for sprite \"%s\" should be",newSpriteName); } - if (strcmp(sprinfoToken,"{")==0) + if (fastcmp(sprinfoToken,"{")) { Z_Free(sprinfoToken); sprinfoToken = M_GetToken(NULL); @@ -183,7 +183,7 @@ static void R_ParseSpriteInfo(boolean spr2) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where definition for sprite \"%s\" should be",newSpriteName); } - while (strcmp(sprinfoToken,"}")!=0) + while (!fastcmp(sprinfoToken,"}")) { if (stricmp(sprinfoToken, "SKIN")==0) { diff --git a/src/sdl/hwsym_sdl.c b/src/sdl/hwsym_sdl.c index a528796eb..edd685327 100644 --- a/src/sdl/hwsym_sdl.c +++ b/src/sdl/hwsym_sdl.c @@ -35,9 +35,6 @@ #define _CREATE_DLL_ // necessary for Unix AND Windows -#define GETFUNC(func) \ - else if (0 == strcmp(#func, funcName)) \ - funcPointer = &func \ // // /** \brief The *hwSym function diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 4e9e54d72..5281a7f01 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -2288,8 +2288,9 @@ char *I_GetUserName(void) } - if (strcmp(username, "") != 0) + if (!fastcmp(username, "")) return username; + return NULL; // dummy for platform independent version } diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 7393d8e4b..5bccceaff 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -905,7 +905,7 @@ static void Impl_HandleControllerAddedEvent(SDL_Event evt) for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - if (!strcmp(cv_usejoystick[i].string, "0") || !cv_usejoystick[i].value) + if (fastcmp(cv_usejoystick[i].string, "0") || !cv_usejoystick[i].value) 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 @@ -977,7 +977,7 @@ static void Impl_HandleControllerRemovedEvent(void) for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) { - if (!strcmp(cv_usejoystick[i].string, "0")) + if (fastcmp(cv_usejoystick[i].string, "0")) { cv_usejoystick[i].value = 0; } diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index 4e60801b3..1b8d54fef 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -170,8 +170,8 @@ boolean OglSdlSurface(INT32 w, INT32 h) } } - if (strcmp((const char*)gl_renderer, "GDI Generic") == 0 && - strcmp((const char*)gl_version, "1.1.0") == 0) + if (fastcmp((const char*)gl_renderer, "GDI Generic") && + fastcmp((const char*)gl_version, "1.1.0")) { // Oh no... Windows gave us the GDI Generic rasterizer, so something is wrong... // The game will crash later on when unsupported OpenGL commands are encountered. diff --git a/src/v_video.c b/src/v_video.c index e7d9a87ca..893a39b20 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -23,7 +23,6 @@ #include "r_main.h" #include "r_fps.h" #include "console.h" - #include "i_video.h" // rendermode #include "z_zone.h" #include "m_misc.h" @@ -134,7 +133,7 @@ static boolean InitCube(void) if (!loaded_config) return false; -#define diffcons(cv) (strcmp(cv.string, cv.defaultvalue)) +#define diffcons(cv) (!fastcmp(cv.string, cv.defaultvalue)) #define diffconsgamma(cv) (cv.value != 0) #define diffconssat(cv) (cv.value != 10) @@ -596,7 +595,7 @@ void V_ResetPaletteCVars(void) if (!loaded_config) return; -#define diffcons(cv) (strcmp(cv.string, cv.defaultvalue)) +#define diffcons(cv) (!fastcmp(cv.string, cv.defaultvalue)) if diffcons(cv_palette) CV_StealthSetValue(&cv_palette, atoi(cv_palette.defaultvalue)); if diffcons(cv_palettenum) -- 2.54.0 From dc6bf05f351aca99bb3bf082dca82927c9d29e0f Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 24 Oct 2025 21:50:12 +0200 Subject: [PATCH 077/116] experiment: replace every strcasecmp with fasticmp same as before, tho this is not twice as fast but atleast 1/3 faster --- src/command.c | 2 +- src/d_main.c | 5 +++- src/d_netcmd.c | 66 +++++++++++++++++++++++------------------------ src/doomtype.h | 2 +- src/filesrch.c | 14 +++++----- src/m_argv.c | 2 +- src/s_sound.c | 10 +++---- src/sdl/i_video.c | 8 +++--- 8 files changed, 56 insertions(+), 53 deletions(-) diff --git a/src/command.c b/src/command.c index 676212703..d5cbf8041 100644 --- a/src/command.c +++ b/src/command.c @@ -359,7 +359,7 @@ size_t COM_CheckParm(const char *check) size_t i; for (i = 1; i < com_argc; i++) - if (!strcasecmp(check, com_argv[i])) + if (fasticmp(check, com_argv[i])) return i; return 0; } diff --git a/src/d_main.c b/src/d_main.c index fd643213c..ef1855d05 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -2156,11 +2156,14 @@ void D_SRB2Main(void) const char *sskill = M_GetNextParm(); for (j = 0; kartspeed_cons_t[j].strvalue; j++) - if (!strcasecmp(kartspeed_cons_t[j].strvalue, sskill)) + { + if (fasticmp(kartspeed_cons_t[j].strvalue, sskill)) { newskill = (INT16)kartspeed_cons_t[j].value; break; } + } + if (!kartspeed_cons_t[j].strvalue) // reached end of the list with no match { j = atoi(sskill); // assume they gave us a skill number, which is okay too diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 3a5e0ca7e..4998069c1 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -1219,7 +1219,7 @@ static boolean EnsurePlayerNameIsGood(char *name, INT32 playernum) for (ix = 0; ix < MAXPLAYERS; ix++) { if (ix != playernum && playeringame[ix] - && strcasecmp(name, player_names[ix]) == 0) + && fasticmp(name, player_names[ix])) { // We shouldn't kick people out just because // they joined the game with the same name @@ -1336,7 +1336,7 @@ static void CleanupPlayerName(INT32 playernum, const char *newname) for (i = 0; i < MAXPLAYERS; i++) { if (i != playernum && playeringame[i] - && strcasecmp(tmpname, player_names[i]) == 0) + && fasticmp(tmpname, player_names[i])) { break; } @@ -1386,7 +1386,7 @@ static void SetPlayerName(INT32 playernum, char *newname) { if (EnsurePlayerNameIsGood(newname, playernum)) { - if (strcasecmp(newname, player_names[playernum]) != 0) + if (fasticmp(newname, player_names[playernum])) { if (netgame) HU_AddChatText(va("\x82*%s renamed to %s", player_names[playernum], newname), false); @@ -1945,7 +1945,7 @@ static void Got_NameAndColor(UINT8 **cp, INT32 playernum) // set name if (player_name_changes[playernum] < MAXNAMECHANGES) { - if (strcasecmp(player_names[playernum], name) != 0) + if (!fasticmp(player_names[playernum], name)) SetPlayerName(playernum, name); } @@ -3194,20 +3194,20 @@ static void Command_Teamchange_f(void) if (G_GametypeHasTeams()) { - if (!strcasecmp(COM_Argv(1), "red") || !strcasecmp(COM_Argv(1), "1")) + if (fasticmp(COM_Argv(1), "red") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(1), "blue") || !strcasecmp(COM_Argv(1), "2")) + else if (fasticmp(COM_Argv(1), "blue") || fasticmp(COM_Argv(1), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + else if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasSpectators()) { - if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; - else if (!strcasecmp(COM_Argv(1), "playing") || !strcasecmp(COM_Argv(1), "1")) + else if (fasticmp(COM_Argv(1), "playing") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 3; else error = true; @@ -3284,20 +3284,20 @@ static void Command_Teamchange2_f(void) if (G_GametypeHasTeams()) { - if (!strcasecmp(COM_Argv(1), "red") || !strcasecmp(COM_Argv(1), "1")) + if (fasticmp(COM_Argv(1), "red") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(1), "blue") || !strcasecmp(COM_Argv(1), "2")) + else if (fasticmp(COM_Argv(1), "blue") || fasticmp(COM_Argv(1), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + else if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasSpectators()) { - if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; - else if (!strcasecmp(COM_Argv(1), "playing") || !strcasecmp(COM_Argv(1), "1")) + else if (fasticmp(COM_Argv(1), "playing") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 3; else error = true; @@ -3375,20 +3375,20 @@ static void Command_Teamchange3_f(void) if (G_GametypeHasTeams()) { - if (!strcasecmp(COM_Argv(1), "red") || !strcasecmp(COM_Argv(1), "1")) + if (fasticmp(COM_Argv(1), "red") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(1), "blue") || !strcasecmp(COM_Argv(1), "2")) + else if (fasticmp(COM_Argv(1), "blue") || fasticmp(COM_Argv(1), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + else if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasSpectators()) { - if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; - else if (!strcasecmp(COM_Argv(1), "playing") || !strcasecmp(COM_Argv(1), "1")) + else if (fasticmp(COM_Argv(1), "playing") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 3; else error = true; @@ -3466,20 +3466,20 @@ static void Command_Teamchange4_f(void) if (G_GametypeHasTeams()) { - if (!strcasecmp(COM_Argv(1), "red") || !strcasecmp(COM_Argv(1), "1")) + if (fasticmp(COM_Argv(1), "red") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(1), "blue") || !strcasecmp(COM_Argv(1), "2")) + else if (fasticmp(COM_Argv(1), "blue") || fasticmp(COM_Argv(1), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + else if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasSpectators()) { - if (!strcasecmp(COM_Argv(1), "spectator") || !strcasecmp(COM_Argv(1), "0")) + if (fasticmp(COM_Argv(1), "spectator") || fasticmp(COM_Argv(1), "0")) NetPacket.packet.newteam = 0; - else if (!strcasecmp(COM_Argv(1), "playing") || !strcasecmp(COM_Argv(1), "1")) + else if (fasticmp(COM_Argv(1), "playing") || fasticmp(COM_Argv(1), "1")) NetPacket.packet.newteam = 3; else error = true; @@ -3565,33 +3565,33 @@ static void Command_ServerTeamChange_f(void) if (G_TagGametype()) { - if (!strcasecmp(COM_Argv(2), "it") || !strcasecmp(COM_Argv(2), "1")) + if (fasticmp(COM_Argv(2), "it") || fasticmp(COM_Argv(2), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(2), "notit") || !strcasecmp(COM_Argv(2), "2")) + else if (fasticmp(COM_Argv(2), "notit") || fasticmp(COM_Argv(2), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(2), "playing") || !strcasecmp(COM_Argv(2), "3")) + else if (fasticmp(COM_Argv(2), "playing") || fasticmp(COM_Argv(2), "3")) NetPacket.packet.newteam = 3; - else if (!strcasecmp(COM_Argv(2), "spectator") || !strcasecmp(COM_Argv(2), "0")) + else if (fasticmp(COM_Argv(2), "spectator") || fasticmp(COM_Argv(2), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasTeams()) { - if (!strcasecmp(COM_Argv(2), "red") || !strcasecmp(COM_Argv(2), "1")) + if (fasticmp(COM_Argv(2), "red") || fasticmp(COM_Argv(2), "1")) NetPacket.packet.newteam = 1; - else if (!strcasecmp(COM_Argv(2), "blue") || !strcasecmp(COM_Argv(2), "2")) + else if (fasticmp(COM_Argv(2), "blue") || fasticmp(COM_Argv(2), "2")) NetPacket.packet.newteam = 2; - else if (!strcasecmp(COM_Argv(2), "spectator") || !strcasecmp(COM_Argv(2), "0")) + else if (fasticmp(COM_Argv(2), "spectator") || fasticmp(COM_Argv(2), "0")) NetPacket.packet.newteam = 0; else error = true; } else if (G_GametypeHasSpectators()) { - if (!strcasecmp(COM_Argv(2), "spectator") || !strcasecmp(COM_Argv(2), "0")) + if (fasticmp(COM_Argv(2), "spectator") || fasticmp(COM_Argv(2), "0")) NetPacket.packet.newteam = 0; - else if (!strcasecmp(COM_Argv(2), "playing") || !strcasecmp(COM_Argv(2), "1")) + else if (fasticmp(COM_Argv(2), "playing") || fasticmp(COM_Argv(2), "1")) NetPacket.packet.newteam = 3; else error = true; diff --git a/src/doomtype.h b/src/doomtype.h index 78867ed69..7b0df4841 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -63,7 +63,7 @@ extern "C" { #endif #if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) #undef stricmp - #define stricmp(x,y) strcasecmp(x,y) + #define stricmp(x,y) !fasticmp(x,y) #undef strnicmp #define strnicmp(x,y,n) strncasecmp(x,y,n) #endif diff --git a/src/filesrch.c b/src/filesrch.c index b9821d368..eb68222e2 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -198,7 +198,7 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want for (; *path != NULL; path++) { - if (strcasecmp(*path, dent->d_name) == 0) + if (fasticmp(*path, dent->d_name)) { skipfolder = true; break; @@ -212,7 +212,7 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want } } - if (strcasecmp(".git", dent->d_name) // sanity if you're weird like me + if (!fasticmp(".git", dent->d_name) // sanity if you're weird like me && (dirhandle[depthleft-1] = opendir(searchpath)) != NULL) { // Got read permissions! @@ -227,7 +227,7 @@ filestatus_t filesearch(char *filename, const char *startpath, const UINT8 *want // I am a file! - if (strcasecmp(searchname, dent->d_name)) + if (!fasticmp(searchname, dent->d_name)) continue; // Not what we're looking for! switch (checkfilemd5(searchpath, wantedmd5sum)) @@ -478,14 +478,14 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) if (replayhut) { - if (strcasecmp(".lmp", dent->d_name+len-5)) + if (!fasticmp(".lmp", dent->d_name+len-5)) continue; // Not a replay } else if (!cv_addons_showall.value) { UINT8 ext; for (ext = 0; ext < NUM_EXT_TABLE; ext++) - if (!strcasecmp(exttable[ext]+1, dent->d_name+len-(exttable[ext][0]))) + if (fasticmp(exttable[ext]+1, dent->d_name+len-(exttable[ext][0]))) break; // extension comparison if (ext == NUM_EXT_TABLE) @@ -559,7 +559,7 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) if (replayhut) { - if (strcasecmp(".lmp", dent->d_name+len-5)) + if (!fasticmp(".lmp", dent->d_name+len-5)) continue; // Not a replay ext = EXT_TXT; // This isn't used anywhere but better safe than sorry for messing with this... @@ -567,7 +567,7 @@ boolean preparefilemenu(boolean samedepth, boolean replayhut) else { for (; ext < NUM_EXT_TABLE; ext++) - if (!strcasecmp(exttable[ext]+1, dent->d_name+len-(exttable[ext][0]))) + if (fasticmp(exttable[ext]+1, dent->d_name+len-(exttable[ext][0]))) break; // extension comparison if (ext == NUM_EXT_TABLE && !cv_addons_showall.value) diff --git a/src/m_argv.c b/src/m_argv.c index 2ec1b188a..b62d390d9 100644 --- a/src/m_argv.c +++ b/src/m_argv.c @@ -49,7 +49,7 @@ INT32 M_CheckParm(const char *check) for (i = 1; i < myargc; i++) { - if (!strcasecmp(check, myargv[i])) + if (fasticmp(check, myargv[i])) { found = i; return i; diff --git a/src/s_sound.c b/src/s_sound.c index 1bac40a46..e3e86c5b0 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -1828,7 +1828,7 @@ void S_StopMusic(void) || demo.title) // SRB2Kart: Demos don't interrupt title screen music return; - mapmusic.resume = (cv_birdmusic.value && (strcasecmp(music.name, mapmusic.name) == 0)) ? I_GetSongPosition() : 0; + mapmusic.resume = (cv_birdmusic.value && fasticmp(music.name, mapmusic.name)) ? I_GetSongPosition() : 0; S_SetKeepMusResume(); @@ -1964,7 +1964,7 @@ static void S_SetKeepMusResume(void) { keepmusic.resume = 0; - if (strcasecmp(music.name, mapmusic.name) == 0) + if (fasticmp(music.name, mapmusic.name)) { keepmusic.resume = I_GetSongPosition(); } @@ -2148,19 +2148,19 @@ static void Command_Tunes_f(void) tunenum = (UINT16)atoi(tunearg); track = 0; - if (!strcasecmp(tunearg, "-show")) + if (fasticmp(tunearg, "-show")) { CONS_Printf(M_GetText("The current tune is: %s [track %d]\n"), mapmusic.name, (mapmusic.flags & MUSIC_TRACKMASK)); return; } - if (!strcasecmp(tunearg, "-none")) + if (fasticmp(tunearg, "-none")) { S_StopMusic(); return; } - else if (!strcasecmp(tunearg, "-default")) + else if (fasticmp(tunearg, "-default")) { tunearg = mapheaderinfo[gamemap-1]->musname; track = mapheaderinfo[gamemap-1]->mustrack; diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 5bccceaff..2ea66dbc2 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -1785,11 +1785,11 @@ void I_StartupGraphics(void) if (rendermode == render_none) { - if (strcasecmp(word, "software") == 0) + if (fasticmp(word, "software")) { rendermode = render_soft; } - else if (strcasecmp(word, "opengl") == 0) + else if (fasticmp(word, "opengl")) { rendermode = render_opengl; } @@ -1802,7 +1802,7 @@ void I_StartupGraphics(void) if (!msaa_set) { - if (strcasecmp(word, "msaa") == 0) + if (fasticmp(word, "msaa")) { const char *nextword = strtok(NULL, " \n"); @@ -1819,7 +1819,7 @@ void I_StartupGraphics(void) if (!a2c_set) { - if (strcasecmp(word, "a2c") == 0) + if (fasticmp(word, "a2c")) { a2c = true; CONS_Printf("Using a2c because it was specified to be used earlier\n"); -- 2.54.0 From df1085548399eb2c1e6e023b45cae671a632b953 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 25 Oct 2025 14:25:30 +0200 Subject: [PATCH 078/116] fix oopsie that broke name change --- src/d_netcmd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 4998069c1..f0601d9fa 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -1386,7 +1386,7 @@ static void SetPlayerName(INT32 playernum, char *newname) { if (EnsurePlayerNameIsGood(newname, playernum)) { - if (fasticmp(newname, player_names[playernum])) + if (!fasticmp(newname, player_names[playernum])) { if (netgame) HU_AddChatText(va("\x82*%s renamed to %s", player_names[playernum], newname), false); -- 2.54.0 From 30cea37248b10c96f0e73392bba40f2ea92f6c61 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 18 Oct 2025 16:52:31 +0200 Subject: [PATCH 079/116] use npow2 screen textures if GL_ARB_texture_non_power_of_two is supported apparently some gl drivers may use a slower path for streamed textures that only get partly updated, this tricks them into thinking this did a "full update" and resulting in using a faster renderpath --- src/hardware/r_opengl/r_opengl.c | 23 +++++++++++++++-------- src/hardware/r_opengl/r_opengl.h | 1 + src/sdl/ogl_sdl.c | 3 +++ 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 23c2a8da0..3a5fd059a 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -110,6 +110,7 @@ GLint screen_texsizew = 512; // Power-of-two screen texture render resolution GLint screen_texsizeh = 512; // Power-of-two screen texture render resolution GLbyte screen_depth = 0; GLint maximumAnisotropy = 0; +boolean supportNPO2tex = false; static GLboolean MipMap = GL_FALSE; static GLint min_filter = GL_LINEAR; static GLint mag_filter = GL_LINEAR; @@ -1176,12 +1177,20 @@ void GL_SetModelView(GLint w, GLint h) screen_texsizew = screen_texsizeh = 512; - // look for power of two that is large enough for the screen - while (screen_texsizew < w) - screen_texsizew <<= 1; + if (supportNPO2tex) + { + screen_texsizew = screen_width; + screen_texsizeh = screen_height; + } + else + { + // look for power of two that is large enough for the screen + while (screen_texsizew < w) + screen_texsizew <<= 1; - while (screen_texsizeh < h) - screen_texsizeh <<= 1; + while (screen_texsizeh < h) + screen_texsizeh <<= 1; + } pglGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxtexsize); // Get the maximum supported texture size if ((screen_texsizew > maxtexsize || screen_texsizeh > maxtexsize) && maxtexsize > 0) @@ -3692,7 +3701,6 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh float xfix, yfix; float origaspect, newaspect; float xoff = 1, yoff = 1; // xoffset and yoffset for the polygon to have black bars around the screen - FRGBAFloat clearColour; static float off[12]; static float fix[8]; @@ -3743,8 +3751,7 @@ void GL_DrawScreenFinalTexture(int tex, INT32 width, INT32 height, boolean usesh pglViewport(0, 0, width, height); - clearColour.red = clearColour.green = clearColour.blue = 0; - clearColour.alpha = 1; + FRGBAFloat clearColour = {0, 0, 0, 1}; GL_ClearBuffer(true, false, false, &clearColour); GL_SetBlend(PF_NoDepthTest); diff --git a/src/hardware/r_opengl/r_opengl.h b/src/hardware/r_opengl/r_opengl.h index 4cf2b2e46..34d4b9da3 100644 --- a/src/hardware/r_opengl/r_opengl.h +++ b/src/hardware/r_opengl/r_opengl.h @@ -124,6 +124,7 @@ extern GLint screen_width; extern GLint screen_height; extern GLbyte screen_depth; extern GLint maximumAnisotropy; +extern boolean supportNPO2tex; extern boolean supportMipMap; /** \brief OpenGL flags for video driver diff --git a/src/sdl/ogl_sdl.c b/src/sdl/ogl_sdl.c index 4e60801b3..0816ecfec 100644 --- a/src/sdl/ogl_sdl.c +++ b/src/sdl/ogl_sdl.c @@ -197,6 +197,9 @@ boolean OglSdlSurface(INT32 w, INT32 h) else maximumAnisotropy = 1; + if (GL_isExtAvailable("GL_ARB_texture_non_power_of_two", gl_extensions)) + supportNPO2tex = true; + glanisotropicmode_cons_t[1].value = maximumAnisotropy; #if defined (__unix__) -- 2.54.0 From 467688552184e38c2935a9e7ab3a93ea00d4238d Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 23:15:52 +0100 Subject: [PATCH 080/116] fixup: replace stricmp with fasticmp actually replace everything correctly my dumbass forgor about the fast both strcmp and stricmp matter in sort stuff so we cannot use the fastcmp stuff there, which means we should not redifine stricmp as fasticmp in case something relies on that behaviour ugh --- src/blua/lauxlib.c | 2 +- src/blua/lfastcmp.h | 32 ------------ src/blua/liolib.c | 8 +-- src/command.c | 72 +++++++++++++------------- src/d_clisrv.c | 7 +-- src/d_main.c | 14 ++--- src/d_netfil.c | 5 +- src/doomtype.h | 2 +- src/g_demo.c | 20 ++++---- src/g_game.c | 2 +- src/g_input.c | 7 +-- src/hardware/hw_md2.c | 12 +++-- src/hardware/hw_model.c | 2 +- src/hardware/hw_shaders.c | 8 +-- src/k_kart.c | 5 +- src/lua_consolelib.c | 2 +- src/lua_mobjlib.c | 6 +-- src/m_emotes.cpp | 4 +- src/m_menu.c | 8 +-- src/m_misc.c | 2 +- src/p_spec.c | 52 ++++++++++++++----- src/r_data.c | 36 +++++++++---- src/r_patch.cpp | 104 +++++++++++++++++++++----------------- src/r_skins.c | 46 ++++++++--------- src/s_sound.c | 31 +++++++----- src/w_wad.c | 10 ++-- 26 files changed, 267 insertions(+), 232 deletions(-) delete mode 100644 src/blua/lfastcmp.h diff --git a/src/blua/lauxlib.c b/src/blua/lauxlib.c index eacce9b44..e91faa182 100644 --- a/src/blua/lauxlib.c +++ b/src/blua/lauxlib.c @@ -24,7 +24,7 @@ #include "lauxlib.h" -#include "lfastcmp.h" +#include "../doomdef.h" #define FREELIST_REF 0 /* free list of references */ diff --git a/src/blua/lfastcmp.h b/src/blua/lfastcmp.h deleted file mode 100644 index f25c59896..000000000 --- a/src/blua/lfastcmp.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __FASTCMP_H__ -#define __FASTCMP_H__ - -#include -#include - -// same as fastcmp but we cant use our fancy macros - -// returns false if s != c -// returns true if s == c -__attribute__((always_inline)) static inline bool fasticmp(const char *s, const char *c) -{ - for (; *s && toupper(*s) == toupper(*c); s++, c++) ; - return (*s == *c); // make sure both strings ended -} - -// case-sensitive of the above -__attribute__((always_inline)) static inline bool fastcmp(const char *s, const char *c) -{ - for (; *s && *s == *c; s++, c++) ; - return (*s == *c); // make sure both strings ended -} - -// length-limited of the above -// only true if both strings are at least l characters long AND match, case-sensitively! -__attribute__((always_inline)) static inline bool fastncmp(const char *s, const char *c, uint16_t l) -{ - for (; *s && *s == *c && --l; s++, c++) ; - return !l; // make sure you reached the end -} - -#endif diff --git a/src/blua/liolib.c b/src/blua/liolib.c index 40e3e4582..929937e2e 100644 --- a/src/blua/liolib.c +++ b/src/blua/liolib.c @@ -161,12 +161,13 @@ static int io_tostring (lua_State *L) { static int StartsWith(const char *a, const char *b) // this is wolfs being lazy yet again { - if(strncmp(a, b, strlen(b)) == 0) return 1; + if (strncmp(a, b, strlen(b)) == 0) return 1; return 0; } -static int io_open (lua_State *L) { +static int io_open(lua_State *L) +{ FILE **pf; const char *filename = luaL_checkstring(L, 1); int pass = 0; @@ -178,12 +179,13 @@ static int io_open (lua_State *L) { for (i = 0; i < (sizeof (whitelist) / sizeof(const char *)); i++) { - if (!stricmp(&filename[length - strlen(whitelist[i])], whitelist[i])) + if (fasticmp(&filename[length - strlen(whitelist[i])], whitelist[i])) { pass = 1; break; } } + if (l_unlikely(strstr(filename, "..") || strchr(filename, ':') || StartsWith(filename, "\\") || StartsWith(filename, "/") || !pass)) { diff --git a/src/command.c b/src/command.c index d5cbf8041..9f9b39500 100644 --- a/src/command.c +++ b/src/command.c @@ -456,7 +456,7 @@ void COM_AddCommand(const char *name, com_func_t func) // fail if the command already exists for (cmd = com_commands; cmd; cmd = cmd->next) { - if (!stricmp(name, cmd->name)) //case insensitive now that we have lower and uppercase! + if (fasticmp(name, cmd->name)) //case insensitive now that we have lower and uppercase! { // don't I_Error for Lua commands // Lua commands can replace game commands, and they have priority. @@ -492,7 +492,7 @@ int COM_AddLuaCommand(const char *name) // command already exists for (cmd = com_commands; cmd; cmd = cmd->next) { - if (!stricmp(name, cmd->name)) //case insensitive now that we have lower and uppercase! + if (fasticmp(name, cmd->name)) //case insensitive now that we have lower and uppercase! { // replace the built in command. cmd->function = COM_Lua_f; @@ -519,7 +519,7 @@ static boolean COM_Exists(const char *com_name) xcommand_t *cmd; for (cmd = com_commands; cmd; cmd = cmd->next) - if (!stricmp(com_name, cmd->name)) + if (fasticmp(com_name, cmd->name)) return true; return false; @@ -571,7 +571,7 @@ static void COM_ExecuteString(char *ptext) // check functions for (cmd = com_commands; cmd; cmd = cmd->next) { - if (!stricmp(com_argv[0], cmd->name)) //case insensitive now that we have lower and uppercase! + if (fasticmp(com_argv[0], cmd->name)) //case insensitive now that we have lower and uppercase! { cmd->function(); return; @@ -581,7 +581,7 @@ static void COM_ExecuteString(char *ptext) // check aliases for (a = com_alias; a; a = a->next) { - if (!stricmp(com_argv[0], a->name)) + if (fasticmp(com_argv[0], a->name)) { if (recursion > MAX_ALIAS_RECURSION) CONS_Alert(CONS_WARNING, M_GetText("Alias recursion cycle detected!\n")); @@ -836,7 +836,7 @@ static void COM_Help_f(void) if (cvar->PossibleValue) { { - if (!stricmp(cvar->PossibleValue[0].strvalue, "MIN") && !stricmp(cvar->PossibleValue[1].strvalue, "MAX")) + if (fasticmp(cvar->PossibleValue[0].strvalue, "MIN") && fasticmp(cvar->PossibleValue[1].strvalue, "MAX")) { if (floatmode) { @@ -1176,7 +1176,7 @@ consvar_t *CV_FindVar(const char *name) consvar_t *cvar; for (cvar = consvar_vars; cvar; cvar = cvar->next) - if (!stricmp(name,cvar->name)) + if (fasticmp(name,cvar->name)) return cvar; return NULL; @@ -1366,7 +1366,7 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) v = INT32_MIN; // Invalid integer trigger } - if (var->PossibleValue[0].strvalue && !stricmp(var->PossibleValue[0].strvalue, "MIN")) // bounded cvar + if (var->PossibleValue[0].strvalue && fasticmp(var->PossibleValue[0].strvalue, "MIN")) // bounded cvar { #define MINVAL 0 #define MAXVAL 1 @@ -1379,21 +1379,21 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) // search for other for (i = MAXVAL+1; var->PossibleValue[i].strvalue; i++) - if (v == var->PossibleValue[i].value || !stricmp(var->PossibleValue[i].strvalue, valstr)) + if (v == var->PossibleValue[i].value || fasticmp(var->PossibleValue[i].strvalue, valstr)) { var->value = var->PossibleValue[i].value; var->string = var->PossibleValue[i].strvalue; goto finish; } - if ((v != INT32_MIN && v < var->PossibleValue[MINVAL].value) || !stricmp(valstr, "MIN")) + if ((v != INT32_MIN && v < var->PossibleValue[MINVAL].value) || fasticmp(valstr, "MIN")) { v = var->PossibleValue[MINVAL].value; valstr = var->PossibleValue[MINVAL].strvalue; override = true; overrideval = v; } - else if ((v != INT32_MIN && v > var->PossibleValue[MAXVAL].value) || !stricmp(valstr, "MAX")) + else if ((v != INT32_MIN && v > var->PossibleValue[MAXVAL].value) || fasticmp(valstr, "MAX")) { v = var->PossibleValue[MAXVAL].value; valstr = var->PossibleValue[MAXVAL].strvalue; @@ -1411,7 +1411,7 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) // check first strings for (i = 0; var->PossibleValue[i].strvalue; i++) - if (!stricmp(var->PossibleValue[i].strvalue, valstr)) + if (fasticmp(var->PossibleValue[i].strvalue, valstr)) goto found; if (v != INT32_MIN) { @@ -1424,9 +1424,9 @@ static void Setvalue(consvar_t *var, const char *valstr, boolean stealth) if (var->PossibleValue == CV_OnOff || var->PossibleValue == CV_YesNo) { overrideval = -1; - if (!stricmp(valstr, "on") || !stricmp(valstr, "yes")) + if (fasticmp(valstr, "on") || fasticmp(valstr, "yes")) overrideval = 1; - else if (!stricmp(valstr, "off") || !stricmp(valstr, "no")) + else if (fasticmp(valstr, "off") || fasticmp(valstr, "no")) overrideval = 0; if (overrideval != -1) @@ -1643,7 +1643,7 @@ static void CV_SetCVar(consvar_t *var, const char *value, boolean stealth) if (!var->string) I_Error("CV_Set: %s no string set!\n", var->name); #endif - if (!var || !var->string || !value || !stricmp(var->string, value)) + if (!var || !var->string || !value || fasticmp(var->string, value)) return; // no changes if (var->flags & CV_NETVAR) @@ -1665,7 +1665,7 @@ static void CV_SetCVar(consvar_t *var, const char *value, boolean stealth) if (var == &cv_kartspeed && !M_SecretUnlocked(SECRET_HARDSPEED)) { - if (!stricmp(value, "Hard") || atoi(value) == 2) + if (fasticmp(value, "Hard") || atoi(value) == 2) { CONS_Alert(CONS_NOTICE, "You haven't unlocked this yet!\n"); return; @@ -1971,12 +1971,12 @@ static boolean CV_FilterJoyAxisVars(consvar_t *v, const char *valstr) { if (joyaxis_default[i]) { - if (!stricmp(v->name, "joyaxis_fire")) + if (fasticmp(v->name, "joyaxis_fire")) { if (joyaxis_count[i] > 7) return false; else if (joyaxis_count[i] == 7) return true; - if (!stricmp(valstr, "None")) joyaxis_count[i]++; + if (fasticmp(valstr, "None")) joyaxis_count[i]++; else joyaxis_default[i] = false; } // reset all axis settings to defaults @@ -2008,37 +2008,37 @@ static boolean CV_FilterJoyAxisVars(consvar_t *v, const char *valstr) // Block the Xbox DInput default axes and reset to the current defaults static boolean CV_FilterJoyAxisVars2(consvar_t *v, const char *valstr) { - if (!stricmp(v->name, "joyaxis_turn") && !stricmp(valstr, "X-Axis")) + if (fasticmp(v->name, "joyaxis_turn") && fasticmp(valstr, "X-Axis")) return false; - if (!stricmp(v->name, "joyaxis2_turn") && !stricmp(valstr, "X-Axis")) + if (fasticmp(v->name, "joyaxis2_turn") && fasticmp(valstr, "X-Axis")) return false; - if (!stricmp(v->name, "joyaxis3_turn") && !stricmp(valstr, "X-Axis")) + if (fasticmp(v->name, "joyaxis3_turn") && fasticmp(valstr, "X-Axis")) return false; - if (!stricmp(v->name, "joyaxis4_turn") && !stricmp(valstr, "X-Axis")) + if (fasticmp(v->name, "joyaxis4_turn") && fasticmp(valstr, "X-Axis")) return false; - if (!stricmp(v->name, "joyaxis_aim") && !stricmp(valstr, "Y-Axis")) + if (fasticmp(v->name, "joyaxis_aim") && fasticmp(valstr, "Y-Axis")) return false; - if (!stricmp(v->name, "joyaxis2_aim") && !stricmp(valstr, "Y-Axis")) + if (fasticmp(v->name, "joyaxis2_aim") && fasticmp(valstr, "Y-Axis")) return false; - if (!stricmp(v->name, "joyaxis3_aim") && !stricmp(valstr, "Y-Axis")) + if (fasticmp(v->name, "joyaxis3_aim") && fasticmp(valstr, "Y-Axis")) return false; - if (!stricmp(v->name, "joyaxis4_aim") && !stricmp(valstr, "Y-Axis")) + if (fasticmp(v->name, "joyaxis4_aim") && fasticmp(valstr, "Y-Axis")) return false; - if (!stricmp(v->name, "joyaxis_fire") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis_fire") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis2_fire") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis2_fire") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis3_fire") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis3_fire") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis4_fire") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis4_fire") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis_drift") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis_drift") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis2_drift") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis2_drift") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis3_drift") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis3_drift") && fasticmp(valstr, "None")) return false; - if (!stricmp(v->name, "joyaxis4_drift") && !stricmp(valstr, "None")) + if (fasticmp(v->name, "joyaxis4_drift") && fasticmp(valstr, "None")) return false; return true; @@ -2055,8 +2055,8 @@ static boolean CV_FilterVarByVersion(consvar_t *v, const char *valstr) if (GETMAJOREXECVERSION(cv_execversion.value) < 8) // 8 = 1.4 { - if (!stricmp(v->name, "masterserver") // Replaces a hack in MasterServer_OnChange for the original SRB2 MS. - || !stricmp(v->name, "gamma")) // Too easy to accidentially change in prior versions. + if (fasticmp(v->name, "masterserver") // Replaces a hack in MasterServer_OnChange for the original SRB2 MS. + || fasticmp(v->name, "gamma")) // Too easy to accidentially change in prior versions. return false; } diff --git a/src/d_clisrv.c b/src/d_clisrv.c index 2ca42df65..255e7ce8e 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -3215,7 +3215,7 @@ static void Command_connect(void) server = false; - if (!stricmp(COM_Argv(1), "self")) + if (fasticmp(COM_Argv(1), "self")) { servernode = 0; server = true; @@ -3225,7 +3225,7 @@ static void Command_connect(void) else { // used in menu to connect to a server in the list - if (netgame && !stricmp(COM_Argv(1), "node")) + if (netgame && fasticmp(COM_Argv(1), "node")) { servernode = (SINT8)atoi(COM_Argv(2)); } @@ -3240,7 +3240,7 @@ static void Command_connect(void) netgame = true; multiplayer = true; - if (!stricmp(COM_Argv(1), "any")) + if (fasticmp(COM_Argv(1), "any")) servernode = BROADCASTADDR; else if (I_NetMakeNodewPort && COM_Argc() >= 3) servernode = I_NetMakeNodewPort(COM_Argv(1), COM_Argv(2)); @@ -3264,6 +3264,7 @@ static void Command_connect(void) splitscreen = cv_splitplayers.value-1; SplitScreen_OnChange(); } + botingame = false; botskin = 0; CL_ConnectToServer(); diff --git a/src/d_main.c b/src/d_main.c index ef1855d05..bafc110e1 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -1078,19 +1078,19 @@ static INT32 D_DetectFileType(const char* filename) const size_t len = strlen(filename); - if (!stricmp(&filename[len - 4], ".wad")) + if (fasticmp(&filename[len - 4], ".wad")) return 2; - else if (!stricmp(&filename[len - 4], ".pk3")) + else if (fasticmp(&filename[len - 4], ".pk3")) return 3; - else if (!stricmp(&filename[len - 5], ".kart")) + else if (fasticmp(&filename[len - 5], ".kart")) return 4; - else if (!stricmp(&filename[len - 4], ".lua")) + else if (fasticmp(&filename[len - 4], ".lua")) return 5; - else if (!stricmp(&filename[len - 4], ".soc")) + else if (fasticmp(&filename[len - 4], ".soc")) return 6; - else if (!stricmp(&filename[len - 4], ".cfg")) + else if (fasticmp(&filename[len - 4], ".cfg")) return 7; - else if (!stricmp(&filename[len - 4], ".txt")) + else if (fasticmp(&filename[len - 4], ".txt")) return 8; return 0; diff --git a/src/d_netfil.c b/src/d_netfil.c index f279eaee0..c82165788 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -550,7 +550,8 @@ INT32 CL_CheckFiles(void) for (j = mainwads+1; j < numwadfiles; j++) { nameonly(strcpy(wadfilename, wadfiles[j]->filename)); - if (!stricmp(wadfilename, fileneeded[i].filename) && + + if (fasticmp(wadfilename, fileneeded[i].filename) && !memcmp(wadfiles[j]->md5sum, fileneeded[i].md5sum, 16)) { CONS_Debug(DBG_NETPLAY, "already loaded\n"); @@ -665,7 +666,7 @@ static boolean SV_SendFile(INT32 node, const char *filename, UINT8 fileid) strlcpy(wadfilename, wadfiles[wadnum]->filename, MAX_WADPATH); nameonly(wadfilename); - if (!stricmp(wadfilename, p->id.filename)) + if (fasticmp(wadfilename, p->id.filename)) { // Copy file name with full path strlcpy(p->id.filename, wadfiles[wadnum]->filename, MAX_WADPATH); diff --git a/src/doomtype.h b/src/doomtype.h index 7b0df4841..78867ed69 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -63,7 +63,7 @@ extern "C" { #endif #if defined (__unix__) || defined (__APPLE__) || defined (UNIXCOMMON) #undef stricmp - #define stricmp(x,y) !fasticmp(x,y) + #define stricmp(x,y) strcasecmp(x,y) #undef strnicmp #define strnicmp(x,y,n) strncasecmp(x,y,n) #endif diff --git a/src/g_demo.c b/src/g_demo.c index bd3905160..7ee773b1f 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -264,7 +264,7 @@ void G_ReadDemoExtraData(void) kartspeed = READUINT8(demobuf.p); kartweight = READUINT8(demobuf.p); - if (stricmp(skins[players[p].skin].name, name) != 0) + if (!fasticmp(skins[players[p].skin].name, name)) FindClosestSkinForStats(p, kartspeed, kartweight); players[p].kartspeed = kartspeed; @@ -277,7 +277,7 @@ void G_ReadDemoExtraData(void) M_Memcpy(name, demobuf.p, 16); demobuf.p += 16; for (i = 0; i < MAXSKINCOLORS; i++) - if (!stricmp(KartColor_Names[i], name)) // SRB2kart + if (fasticmp(KartColor_Names[i], name)) // SRB2kart { players[p].skincolor = i; if (players[p].mo) @@ -2289,7 +2289,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { for (UINT8 j = 0; kartspeed_cons_t[j].strvalue; j++) { - if (!stricmp(kartspeed_cons_t[j].strvalue, svalue)) + if (fasticmp(kartspeed_cons_t[j].strvalue, svalue)) pdemo->kartspeed = kartspeed_cons_t[j].value; } } @@ -2321,7 +2321,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) for (i = 0; i < numskins; i++) { - if (stricmp(skins[i].name, temp) == 0) + if (fasticmp(skins[i].name, temp)) { pdemo->standings[count].skin = i; break; @@ -2334,7 +2334,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) for (i = 0; i < MAXSKINCOLORS; i++) { - if (!stricmp(KartColor_Names[i],temp)) // SRB2kart + if (fasticmp(KartColor_Names[i],temp)) // SRB2kart { pdemo->standings[count].color = i; break; @@ -2807,7 +2807,7 @@ void G_DoPlayDemo(char *defdemoname) // Set color for (i = 0; i < MAXSKINCOLORS; i++) { - if (!stricmp(KartColor_Names[i],color)) // SRB2kart + if (fasticmp(KartColor_Names[i],color)) // SRB2kart { players[0].skincolor = i; break; @@ -2947,7 +2947,7 @@ void G_DoPlayDemo(char *defdemoname) for (i = 0; i < MAXSKINCOLORS; i++) { - if (!stricmp(KartColor_Names[i],color)) // SRB2kart + if (fasticmp(KartColor_Names[i],color)) // SRB2kart { players[p].skincolor = i; break; @@ -2961,7 +2961,7 @@ void G_DoPlayDemo(char *defdemoname) kartspeed[p] = READUINT8(demobuf.p); kartweight[p] = READUINT8(demobuf.p); - if (stricmp(skins[players[p].skin].name, skin) != 0) + if (!fasticmp(skins[players[p].skin].name, skin)) FindClosestSkinForStats(p, kartspeed[p], kartweight[p]); // Look for the next player @@ -3242,7 +3242,7 @@ void G_AddGhost(char *defdemoname) for (i = 0; i < numskins; i++) { - if (!stricmp(skins[i].name,skin)) + if (fasticmp(skins[i].name, skin)) { ghskin = &skins[i]; break; @@ -3317,7 +3317,7 @@ void G_AddGhost(char *defdemoname) for (i = 0; i < MAXSKINCOLORS; i++) { - if (!stricmp(KartColor_Names[i],color)) // SRB2kart + if (fasticmp(KartColor_Names[i],color)) // SRB2kart { gh->mo->color = (UINT8)i; break; diff --git a/src/g_game.c b/src/g_game.c index 05615df78..125c88067 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -2768,7 +2768,7 @@ INT32 G_GetGametypeByName(const char *gametypestr) INT32 i; for (i = 0; i < NUMGAMETYPES; i++) - if (!stricmp(gametypestr, Gametype_Names[i])) + if (fasticmp(gametypestr, Gametype_Names[i])) return i; return -1; // unknown gametype diff --git a/src/g_input.c b/src/g_input.c index e8bc8223e..e5cd04668 100644 --- a/src/g_input.c +++ b/src/g_input.c @@ -1033,7 +1033,7 @@ INT32 G_KeyStringtoNum(const char *keystr) return atoi(&keystr[3]); for (j = 0; j < NUMKEYNAMES; j++) - if (!stricmp(keynames[j].name, keystr)) + if (fasticmp(keynames[j].name, keystr)) return keynames[j].keynum; return 0; @@ -1333,14 +1333,15 @@ static void setcontrol(INT32 (*gc)[2]) player = 0; namectrl = COM_Argv(1); - for (numctrl = 0; numctrl < num_gamecontrols && stricmp(namectrl, gamecontrolname[numctrl]); - numctrl++) + for (numctrl = 0; numctrl < num_gamecontrols && !fasticmp(namectrl, gamecontrolname[numctrl]); numctrl++) ; + if (numctrl == num_gamecontrols) { CONS_Printf(M_GetText("Control '%s' unknown\n"), namectrl); return; } + keynum1 = G_KeyStringtoNum(COM_Argv(2)); keynum2 = G_KeyStringtoNum(COM_Argv(3)); keynum = G_FilterKeyByVersion(numctrl, 0, player, &keynum1, &keynum2, &nestedoverride); diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index f3db532e9..10e5e4e1b 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -549,7 +549,7 @@ void HWR_InitMD2(void) { for (i = 0; i < NUMSPRITES; i++) { - if (stricmp(name, sprnames[i]) == 0) + if (fasticmp(name, sprnames[i])) { md2_models[i].scale = scale; md2_models[i].offset = offset; @@ -561,7 +561,7 @@ void HWR_InitMD2(void) for (s = 0; s < MAXSKINS; s++) { - if (stricmp(name, skins[s].name) == 0) + if (fasticmp(name, skins[s].name)) { md2_playermodels[s].skin = s; md2_playermodels[s].scale = scale; @@ -607,11 +607,12 @@ void HWR_AddPlayerMD2(int skin, boolean local) // For MD2's that were added afte } } - md2s = ( (local) ? md2_localplayermodels : md2_playermodels ); + md2s = (local ? md2_localplayermodels : md2_playermodels); + // Check for any MD2s that match the names of player skins! while (fscanf(f, "%19s %31s %f %f", name, filename, &scale, &offset) == 4) { - if (stricmp(name, K_GetSkinArray(local)[skin].name) == 0) + if (fasticmp(name, K_GetSkinArray(local)[skin].name)) { md2s[skin].skin = skin; md2s[skin].scale = scale; @@ -650,6 +651,7 @@ void HWR_AddSpriteMD2(size_t spritenum) // For MD2s that were added after startu if (!f) { f = fopen(va("%s"PATHSEP"%s", srb2path, "mdls.dat"), "rt"); + if (!f) { CONS_Printf("%s %s\n", M_GetText("Error while loading mdls.dat:"), strerror(errno)); @@ -661,7 +663,7 @@ void HWR_AddSpriteMD2(size_t spritenum) // For MD2s that were added after startu // Check for any MD2s that match the names of sprite names! while (fscanf(f, "%19s %31s %f %f", name, filename, &scale, &offset) == 4) { - if (stricmp(name, sprnames[spritenum]) == 0) + if (fasticmp(name, sprnames[spritenum])) { md2_models[spritenum].scale = scale; md2_models[spritenum].offset = offset; diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 77a995ed0..811ac3b67 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -126,7 +126,7 @@ tag_t *GetTagByName(model_t *model, char *name, int frame) int i; for (i = 0; i < model->numTags; i++) { - if (!stricmp(iterator[i].name, name)) + if (fasticmp(iterator[i].name, name)) return &iterator[i]; } } diff --git a/src/hardware/hw_shaders.c b/src/hardware/hw_shaders.c index 9724378fe..19aea915e 100644 --- a/src/hardware/hw_shaders.c +++ b/src/hardware/hw_shaders.c @@ -586,7 +586,7 @@ void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3) goto skip_field; } - if (!stricmp(stoken, "GLSL")) + if (fasticmp(stoken, "GLSL")) { value = strtok(NULL, "\r\n "); if (!value) @@ -596,9 +596,9 @@ void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3) goto skip_lump; } - if (!stricmp(value, "VERTEX")) + if (fasticmp(value, "VERTEX")) shadertype = 1; - else if (!stricmp(value, "FRAGMENT")) + else if (fasticmp(value, "FRAGMENT")) shadertype = 2; skip_lump: @@ -624,7 +624,7 @@ skip_lump: for (i = 0; shaderxlat[i].type; i++) { - if (!stricmp(shaderxlat[i].type, stoken)) + if (fasticmp(shaderxlat[i].type, stoken)) { size_t shader_string_length; char *shader_source; diff --git a/src/k_kart.c b/src/k_kart.c index 7f755e235..3f335a5bb 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -637,11 +637,14 @@ void K_GenerateKartColormap(UINT8 *dest_colormap, INT32 skinnum, UINT8 color, bo UINT8 K_GetKartColorByName(const char *name) { UINT8 color = (UINT8)atoi(name); + if (color > 0 && color < MAXSKINCOLORS) return color; + for (color = 1; color < MAXSKINCOLORS; color++) - if (!stricmp(KartColor_Names[color], name)) + if (fasticmp(KartColor_Names[color], name)) return color; + return 0; } diff --git a/src/lua_consolelib.c b/src/lua_consolelib.c index 36c3a6c45..df45e3e07 100644 --- a/src/lua_consolelib.c +++ b/src/lua_consolelib.c @@ -453,7 +453,7 @@ static int lib_cvRegisterVar(lua_State *L) if (cvar->flags & CV_MODIFIED) return luaL_error(L, "failed to register cvar (probable conflict with internal variable/command names)"); - if (!(((cvar->flags & CV_HIDEN)) || (cvar->flags & CV_NOSHOWHELP)) && (cvar->PossibleValue || !(cvar->value == 0 && stricmp(cvar->string, "0")))) + if (!(((cvar->flags & CV_HIDEN)) || (cvar->flags & CV_NOSHOWHELP)) && (cvar->PossibleValue || !(cvar->value == 0 && !fasticmp(cvar->string, "0")))) { if (!category) { diff --git a/src/lua_mobjlib.c b/src/lua_mobjlib.c index 5ffbcb34e..fef27f563 100644 --- a/src/lua_mobjlib.c +++ b/src/lua_mobjlib.c @@ -455,12 +455,12 @@ int mobj_localskin_setter(lua_State *L) strlcpy(skin, luaL_optstring(L, 2, "none"), sizeof skin); strlwr(skin); // all skin names are lowercase - if (stricmp(skin, "none")) + if (!fasticmp(skin, "none")) { // Try localskins for (i = 0; i < numlocalskins; i++) { - if (stricmp(localskins[i].name, skin) == 0) + if (fasticmp(localskins[i].name, skin)) { mo->localskin = &localskins[i]; mo->skinlocal = true; @@ -471,7 +471,7 @@ int mobj_localskin_setter(lua_State *L) // Try other skins for (i = 0; i < numskins; i++) { - if (stricmp(skins[i].name, skin) == 0) + if (fasticmp(skins[i].name, skin)) { mo->localskin = &skins[i]; mo->skinlocal = false; diff --git a/src/m_emotes.cpp b/src/m_emotes.cpp index 57058ef23..45fd78804 100644 --- a/src/m_emotes.cpp +++ b/src/m_emotes.cpp @@ -112,7 +112,7 @@ void M_LoadEmotes(UINT16 wadnum) trim(field); trim(value); - if (stricmp(field.c_str(), "frames") == 0) + if (fasticmp(field.c_str(), "frames")) { UINT8 numframes = 0; @@ -158,7 +158,7 @@ void M_LoadEmotes(UINT16 wadnum) emote->numframes = numframes; } - else if (stricmp(field.c_str(), "timeperframe") == 0) + else if (fasticmp(field.c_str(), "timeperframe")) { emote->timeperframe = std::stoi(value); diff --git a/src/m_menu.c b/src/m_menu.c index bd79ec80c..09a0c6350 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -6799,7 +6799,7 @@ static int ServerListEntryComparator_##key(const void *entry1, const void *entry const serverelem_t *sa = (const serverelem_t*)entry1, *sb = (const serverelem_t*)entry2; \ if (sa->info.key != sb->info.key) \ return sa->info.key - sb->info.key; \ - return !fastcmp(sa->info.servername, sb->info.servername); \ + return strcmp(sa->info.servername, sb->info.servername); \ } // This does descending instead of ascending. @@ -6809,7 +6809,7 @@ static int ServerListEntryComparator_##key##_reverse(const void *entry1, const v const serverelem_t *sa = (const serverelem_t*)entry1, *sb = (const serverelem_t*)entry2; \ if (sb->info.key != sa->info.key) \ return sb->info.key - sa->info.key; \ - return !fastcmp(sb->info.servername, sa->info.servername); \ + return strcmp(sb->info.servername, sa->info.servername); \ } SERVER_LIST_ENTRY_COMPARATOR(time) @@ -6830,8 +6830,8 @@ static int ServerListEntryComparator_modified(const void *entry1, const void *en if (modstate_a != modstate_b) return modstate_a - modstate_b; - // Default to !fastcmp. - return !fastcmp(sa->info.servername, sb->info.servername); + // Default to strcmp. + return strcmp(sa->info.servername, sb->info.servername); } void M_SortServerList(void) diff --git a/src/m_misc.c b/src/m_misc.c index 4a0a163aa..58e4b191e 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -423,7 +423,7 @@ void Command_SaveConfig_f(void) FIL_ForceExtension(tmpstr, ".cfg"); M_SaveConfig(tmpstr); - if (stricmp(COM_Argv(2), "-silent")) + if (!fasticmp(COM_Argv(2), "-silent")) CONS_Printf(M_GetText("config saved as %s\n"), configfile); } diff --git a/src/p_spec.c b/src/p_spec.c index e7b032131..e08030e9e 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -324,6 +324,7 @@ void P_InitPicAnims(void) lastanim->speed = LONG(animdefs[i].speed); lastanim++; } + lastanim->istexture = -1; R_ClearTextureNumCache(false); @@ -331,6 +332,7 @@ void P_InitPicAnims(void) // We'll only be using anims from now on. if (animdefs != harddefs) Z_Free(animdefs); + animdefs = NULL; } @@ -361,20 +363,21 @@ void P_ParseANIMDEFSLump(INT32 wadNum, UINT16 lumpnum) // Now, let's start parsing this thing p = animdefsText; + animdefsToken = M_GetToken(p); while (animdefsToken != NULL) { - if (stricmp(animdefsToken, "TEXTURE") == 0) + if (fasticmp(animdefsToken, "TEXTURE")) { Z_Free(animdefsToken); P_ParseAnimationDefintion(1); } - else if (stricmp(animdefsToken, "FLAT") == 0) + else if (fasticmp(animdefsToken, "FLAT")) { Z_Free(animdefsToken); P_ParseAnimationDefintion(0); } - else if (stricmp(animdefsToken, "OSCILLATE") == 0) + else if (fasticmp(animdefsToken, "OSCILLATE")) { // This probably came off the tail of an earlier definition. It's technically legal syntax, but we don't support it. I_Error("Error parsing ANIMDEFS lump: Animation definitions utilizing \"OSCILLATE\" (the animation plays in reverse when it reaches the end) are not supported by SRB2"); @@ -383,11 +386,17 @@ void P_ParseANIMDEFSLump(INT32 wadNum, UINT16 lumpnum) { I_Error("Error parsing ANIMDEFS lump: Expected \"TEXTURE\" or \"FLAT\", got \"%s\"",animdefsToken); } + // parse next line - while (*p != '\0' && *p != '\n') ++p; - if (*p == '\n') ++p; + while (*p != '\0' && *p != '\n') + ++p; + + if (*p == '\n') + ++p; + animdefsToken = M_GetToken(p); } + Z_Free(animdefsToken); Z_Free((void *)animdefsText); } @@ -406,7 +415,8 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where start texture/flat name should be"); } - if (stricmp(animdefsToken, "OPTIONAL") == 0) + + if (fasticmp(animdefsToken, "OPTIONAL")) { // This is meaningful to ZDoom - it tells the program NOT to bomb out // if the textures can't be found - but it's useless in SRB2, so we'll @@ -418,7 +428,7 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where start texture/flat name should be"); } - else if (stricmp(animdefsToken, "RANGE") == 0) + else if (fasticmp(animdefsToken, "RANGE")) { // Oh. Um. Apparently "OPTIONAL" is a texture name. Naughty. // I should probably handle this more gracefully, but right now @@ -427,15 +437,17 @@ void P_ParseAnimationDefintion(SINT8 istexture) I_Error("Error parsing ANIMDEFS lump: \"OPTIONAL\" is a keyword; you cannot use it as the startname of an animation"); } } + animdefsTokenLength = strlen(animdefsToken); - if (animdefsTokenLength>8) + if (animdefsTokenLength > 8) { I_Error("Error parsing ANIMDEFS lump: lump name \"%s\" exceeds 8 characters", animdefsToken); } // Search for existing animdef for (i = 0; i < maxanims; i++) - if (stricmp(animdefsToken, animdefs[i].startname) == 0) + { + if (fasticmp(animdefsToken, animdefs[i].startname)) { //CONS_Alert(CONS_NOTICE, "Duplicate animation: %s\n", animdefsToken); @@ -444,6 +456,7 @@ void P_ParseAnimationDefintion(SINT8 istexture) Z_Free(animdefsToken); return; } + } // Not found if (i == maxanims) @@ -467,21 +480,25 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where \"RANGE\" after \"%s\"'s startname should be", animdefs[i].startname); } - if (stricmp(animdefsToken, "ALLOWDECALS") == 0) + + if (fasticmp(animdefsToken, "ALLOWDECALS")) { // Another ZDoom keyword, ho-hum. Skip it, move on to the next token. Z_Free(animdefsToken); animdefsToken = M_GetToken(NULL); } - if (stricmp(animdefsToken, "PIC") == 0) + + if (fasticmp(animdefsToken, "PIC")) { // This is technically legitimate ANIMDEFS syntax, but SRB2 doesn't support it. I_Error("Error parsing ANIMDEFS lump: Animation definitions utilizing \"PIC\" (specific frames instead of a consecutive range) are not supported by SRB2"); } - if (stricmp(animdefsToken, "RANGE") != 0) + + if (!fasticmp(animdefsToken, "RANGE")) { I_Error("Error parsing ANIMDEFS lump: Expected \"RANGE\" after \"%s\"'s startname, got \"%s\"", animdefs[i].startname, animdefsToken); } + Z_Free(animdefsToken); // Endname @@ -490,11 +507,13 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where \"%s\"'s end texture/flat name should be", animdefs[i].startname); } + animdefsTokenLength = strlen(animdefsToken); if (animdefsTokenLength>8) { I_Error("Error parsing ANIMDEFS lump: lump name \"%s\" exceeds 8 characters", animdefsToken); } + strncpy(animdefs[i].endname, animdefsToken, 9); Z_Free(animdefsToken); @@ -504,15 +523,18 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where \"%s\"'s \"TICS\" should be", animdefs[i].startname); } - if (stricmp(animdefsToken, "RAND") == 0) + + if (fasticmp(animdefsToken, "RAND")) { // This is technically legitimate ANIMDEFS syntax, but SRB2 doesn't support it. I_Error("Error parsing ANIMDEFS lump: Animation definitions utilizing \"RAND\" (random duration per frame) are not supported by SRB2"); } - if (stricmp(animdefsToken, "TICS") != 0) + + if (!fasticmp(animdefsToken, "TICS")) { I_Error("Error parsing ANIMDEFS lump: Expected \"TICS\" in animation definition for \"%s\", got \"%s\"", animdefs[i].startname, animdefsToken); } + Z_Free(animdefsToken); // Speed @@ -521,6 +543,7 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Unexpected end of file where \"%s\"'s animation speed should be", animdefs[i].startname); } + endPos = NULL; #ifndef AVOID_ERRNO errno = 0; @@ -535,6 +558,7 @@ void P_ParseAnimationDefintion(SINT8 istexture) { I_Error("Error parsing ANIMDEFS lump: Expected a positive integer for \"%s\"'s animation speed, got \"%s\"", animdefs[i].startname, animdefsToken); } + animdefs[i].speed = animSpeed; Z_Free(animdefsToken); } diff --git a/src/r_data.c b/src/r_data.c index 893252571..3077326ad 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -976,8 +976,9 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where texture name should be"); } + texturesTokenLength = strlen(texturesToken); - if (texturesTokenLength>8) + if (texturesTokenLength > 8) { I_Error("Error parsing TEXTURES lump: Texture name \"%s\" exceeds 8 characters",texturesToken); } @@ -988,6 +989,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) // ^^ we've confirmed that the token is <= 8 characters so it will never overflow a 9 byte char buffer strupr(newTextureName); // Just do this now so we don't have to worry about it } + Z_Free(texturesToken); // Comma 1 @@ -996,10 +998,11 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after texture \"%s\"'s name should be",newTextureName); } - else if (!fastcmp(texturesToken,",")) + else if (!fastcmp(texturesToken, ",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after texture \"%s\"'s name, got \"%s\"",newTextureName,texturesToken); } + Z_Free(texturesToken); // Width @@ -1030,10 +1033,12 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where comma after texture \"%s\"'s width should be",newTextureName); } - if (!fastcmp(texturesToken,",")) + + if (!fastcmp(texturesToken, ",")) { I_Error("Error parsing TEXTURES lump: Expected \",\" after texture \"%s\"'s width, got \"%s\"",newTextureName,texturesToken); } + Z_Free(texturesToken); // Height @@ -1066,7 +1071,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) I_Error("Error parsing TEXTURES lump: Unexpected end of file where open curly brace for texture \"%s\" should be",newTextureName); } - if (fastcmp(texturesToken,"{")) + if (fastcmp(texturesToken, "{")) { if (actuallyLoadTexture) { @@ -1078,15 +1083,18 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) resultTexture->height = newTextureHeight; resultTexture->type = TEXTURETYPE_COMPOSITE; } + Z_Free(texturesToken); + texturesToken = M_GetToken(NULL); if (texturesToken == NULL) { I_Error("Error parsing TEXTURES lump: Unexpected end of file where patch definition for texture \"%s\" should be",newTextureName); } - while (!fastcmp(texturesToken,"}")) + + while (!fastcmp(texturesToken, "}")) { - if (stricmp(texturesToken, "PATCH")==0) + if (fasticmp(texturesToken, "PATCH")) { Z_Free(texturesToken); if (resultTexture) @@ -1118,6 +1126,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) I_Error("Error parsing TEXTURES lump: Unexpected end of file where patch declaration or right curly brace for texture \"%s\" should be",newTextureName); } } + if (resultTexture && resultTexture->patchcount == 0) { I_Error("Error parsing TEXTURES lump: Texture \"%s\" must have at least one patch",newTextureName); @@ -1127,10 +1136,13 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { I_Error("Error parsing TEXTURES lump: Expected \"{\" for texture \"%s\", got \"%s\"",newTextureName,texturesToken); } + Z_Free(texturesToken); - if (actuallyLoadTexture) return resultTexture; - else return NULL; + if (actuallyLoadTexture) + return resultTexture; + + return NULL; } // Parses the TEXTURES lump... but just to count the number of textures. @@ -1162,7 +1174,7 @@ int R_CountTexturesInTEXTURESLump(UINT16 wadNum, UINT16 lumpNum) texturesToken = M_GetToken(texturesText); while (texturesToken != NULL) { - if (stricmp(texturesToken, "WALLTEXTURE")==0) + if (fasticmp(texturesToken, "WALLTEXTURE")) { numTexturesInLump++; Z_Free(texturesToken); @@ -1172,8 +1184,10 @@ int R_CountTexturesInTEXTURESLump(UINT16 wadNum, UINT16 lumpNum) { I_Error("Error parsing TEXTURES lump: Expected \"WALLTEXTURE\", got \"%s\"",texturesToken); } + texturesToken = M_GetToken(NULL); } + Z_Free(texturesToken); Z_Free((void *)texturesText); @@ -1211,7 +1225,7 @@ void R_ParseTEXTURESLump(UINT16 wadNum, UINT16 lumpNum, INT32 *texindex) texturesToken = M_GetToken(texturesText); while (texturesToken != NULL) { - if (stricmp(texturesToken, "WALLTEXTURE")==0) + if (fasticmp(texturesToken, "WALLTEXTURE")) { Z_Free(texturesToken); // Get the new texture @@ -1227,8 +1241,10 @@ void R_ParseTEXTURESLump(UINT16 wadNum, UINT16 lumpNum, INT32 *texindex) { I_Error("Error parsing TEXTURES lump: Expected \"WALLTEXTURE\", got \"%s\"",texturesToken); } + texturesToken = M_GetToken(NULL); } + Z_Free(texturesToken); Z_Free((void *)texturesText); } diff --git a/src/r_patch.cpp b/src/r_patch.cpp index 1e09ae7bb..7510520dd 100644 --- a/src/r_patch.cpp +++ b/src/r_patch.cpp @@ -46,13 +46,14 @@ static void R_ParseSpriteInfoFrame(spriteinfo_t *info) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite frame should be"); } + sprinfoTokenLength = strlen(sprinfoToken); if (sprinfoTokenLength != 1) { I_Error("Error parsing SPRTINFO lump: Invalid frame \"%s\"",sprinfoToken); } - else - frameChar = sprinfoToken; + + frameChar = sprinfoToken; frameFrame = R_Char2Frame(frameChar[0]); Z_Free(sprinfoToken); @@ -61,53 +62,53 @@ static void R_ParseSpriteInfoFrame(spriteinfo_t *info) sprinfoToken = M_GetToken(NULL); if (sprinfoToken == NULL) I_Error("Error parsing SPRTINFO lump: Missing sprite info"); - else + + if (fastcmp(sprinfoToken, "{")) { - if (fastcmp(sprinfoToken,"{")) + Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); + if (sprinfoToken == NULL) { + I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite info should be"); + } + while (!fastcmp(sprinfoToken, "}")) + { + if (fasticmp(sprinfoToken, "XPIVOT")) + { + Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); + frameXPivot = atoi(sprinfoToken); + } + else if (fasticmp(sprinfoToken, "YPIVOT")) + { + Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); + frameYPivot = atoi(sprinfoToken); + } + else if (fasticmp(sprinfoToken, "ROTAXIS")) + { + Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); + if (fasticmp(sprinfoToken, "X") || fasticmp(sprinfoToken, "XAXIS") || fasticmp(sprinfoToken, "ROLL")) + frameRotAxis = ROTAXIS_X; + else if (fasticmp(sprinfoToken, "Y") || fasticmp(sprinfoToken, "YAXIS") || fasticmp(sprinfoToken, "PITCH")) + frameRotAxis = ROTAXIS_Y; + else if (fasticmp(sprinfoToken, "Z") || fasticmp(sprinfoToken, "ZAXIS") || fasticmp(sprinfoToken, "YAW")) + frameRotAxis = ROTAXIS_Z; + } + Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); if (sprinfoToken == NULL) { - I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite info should be"); - } - while (!fastcmp(sprinfoToken,"}")) - { - if (stricmp(sprinfoToken, "XPIVOT")==0) - { - Z_Free(sprinfoToken); - sprinfoToken = M_GetToken(NULL); - frameXPivot = atoi(sprinfoToken); - } - else if (stricmp(sprinfoToken, "YPIVOT")==0) - { - Z_Free(sprinfoToken); - sprinfoToken = M_GetToken(NULL); - frameYPivot = atoi(sprinfoToken); - } - else if (stricmp(sprinfoToken, "ROTAXIS")==0) - { - Z_Free(sprinfoToken); - sprinfoToken = M_GetToken(NULL); - if ((stricmp(sprinfoToken, "X")==0) || (stricmp(sprinfoToken, "XAXIS")==0) || (stricmp(sprinfoToken, "ROLL")==0)) - frameRotAxis = ROTAXIS_X; - else if ((stricmp(sprinfoToken, "Y")==0) || (stricmp(sprinfoToken, "YAXIS")==0) || (stricmp(sprinfoToken, "PITCH")==0)) - frameRotAxis = ROTAXIS_Y; - else if ((stricmp(sprinfoToken, "Z")==0) || (stricmp(sprinfoToken, "ZAXIS")==0) || (stricmp(sprinfoToken, "YAW")==0)) - frameRotAxis = ROTAXIS_Z; - } - Z_Free(sprinfoToken); - - sprinfoToken = M_GetToken(NULL); - if (sprinfoToken == NULL) - { - I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite info or right curly brace should be"); - } + I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite info or right curly brace should be"); } } - Z_Free(sprinfoToken); } + Z_Free(sprinfoToken); + // set fields info->pivot[frameFrame].x = frameXPivot; info->pivot[frameFrame].y = frameYPivot; @@ -137,6 +138,7 @@ static void R_ParseSpriteInfo(boolean spr2) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where sprite name should be"); } + sprinfoTokenLength = strlen(sprinfoToken); if (sprinfoTokenLength != 4) { @@ -149,6 +151,7 @@ static void R_ParseSpriteInfo(boolean spr2) // ^^ we've confirmed that the token is == 4 characters so it will never overflow a 5 byte char buffer strupr(newSpriteName); // Just do this now so we don't have to worry about it } + Z_Free(sprinfoToken); if (!spr2) @@ -157,7 +160,8 @@ static void R_ParseSpriteInfo(boolean spr2) { if (i == NUMSPRITES) I_Error("Error parsing SPRTINFO lump: Unknown sprite name \"%s\"", newSpriteName); - if (!memcmp(newSpriteName,sprnames[i],4)) + + if (!memcmp(newSpriteName,sprnames[i], 4)) { sprnum = static_cast(i); break; @@ -175,17 +179,20 @@ static void R_ParseSpriteInfo(boolean spr2) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where open curly brace for sprite \"%s\" should be",newSpriteName); } - if (fastcmp(sprinfoToken,"{")) + + if (fastcmp(sprinfoToken, "{")) { Z_Free(sprinfoToken); + sprinfoToken = M_GetToken(NULL); if (sprinfoToken == NULL) { I_Error("Error parsing SPRTINFO lump: Unexpected end of file where definition for sprite \"%s\" should be",newSpriteName); } - while (!fastcmp(sprinfoToken,"}")) + + while (!fastcmp(sprinfoToken, "}")) { - if (stricmp(sprinfoToken, "SKIN")==0) + if (fasticmp(sprinfoToken, "SKIN")) { INT32 skinnum; char *skinName = NULL; @@ -216,10 +223,11 @@ static void R_ParseSpriteInfo(boolean spr2) skinnumbers[foundskins] = skinnum; foundskins++; } - else if (stricmp(sprinfoToken, "FRAME")==0) + else if (fasticmp(sprinfoToken, "FRAME")) { R_ParseSpriteInfoFrame(info); Z_Free(sprinfoToken); + if (spr2) { if (!foundskins) @@ -254,6 +262,7 @@ static void R_ParseSpriteInfo(boolean spr2) { I_Error("Error parsing SPRTINFO lump: Expected \"{\" for sprite \"%s\", got \"%s\"",newSpriteName,sprinfoToken); } + Z_Free(sprinfoToken); Z_Free(info); } @@ -291,15 +300,18 @@ void R_ParseSPRTINFOLump(UINT16 wadNum, UINT16 lumpNum) while (sprinfoToken != NULL) { CONS_Printf("Attempting to parse le SPRTINFO lump for ya..\n"); - if (!stricmp(sprinfoToken, "SPRITE")) + + if (fasticmp(sprinfoToken, "SPRITE")) R_ParseSpriteInfo(false); - else if (!stricmp(sprinfoToken, "SPRITE2")) + else if (fasticmp(sprinfoToken, "SPRITE2")) R_ParseSpriteInfo(true); else I_Error("Error parsing SPRTINFO lump: Unknown keyword \"%s\"", sprinfoToken); + Z_Free(sprinfoToken); sprinfoToken = M_GetToken(NULL); } + Z_Free((void *)sprinfoText); } diff --git a/src/r_skins.c b/src/r_skins.c index bf731f708..53765e269 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -72,7 +72,7 @@ static void Sk_SetDefaultValue(skin_t *skin, boolean local) // // set default skin values // - memset(skin, 0, sizeof (skin_t)); + memset(skin, 0, sizeof(skin_t)); snprintf(skin->name, sizeof skin->name, "skin %u", K_GetMobjSkinNum(skin, local)); skin->name[sizeof skin->name - 1] = '\0'; @@ -188,7 +188,7 @@ INT32 R_SkinAvailable(const char *name) for (i = 0; i < numskins; i++) { - if (stricmp(skins[i].name, name) == 0) + if (fasticmp(skins[i].name, name)) return i; } @@ -203,7 +203,7 @@ INT32 R_AnySkinAvailable(const char *name) for (i = 0; i < numallskins; i++) { - if (stricmp(allskins[i].name, name) == 0) + if (fasticmp(allskins[i].name, name)) return i; } @@ -218,7 +218,7 @@ INT32 R_LocalSkinAvailable(const char *name, boolean local) { for (i = 0; i < numlocalskins; i++) { - if (stricmp(localskins[i].name, name) == 0) + if (fasticmp(localskins[i].name, name)) return i; } @@ -236,7 +236,7 @@ boolean SetPlayerSkin(INT32 playernum, const char *skinname) for (i = 0; i < numskins; i++) { // search in the skin list - if (stricmp(skins[i].name, skinname) == 0) + if (fasticmp(skins[i].name, skinname)) { SetPlayerSkinByNum(playernum, i); return true; @@ -257,12 +257,12 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) INT32 i; player_t *player = &players[playernum]; - if (stricmp(skinname, "none")) + if (!fasticmp(skinname, "none")) { for (i = 0; i < numlocalskins; i++) { // search in the localskin list - if (stricmp(localskins[i].name, skinname) == 0) + if (fasticmp(localskins[i].name, skinname)) { player->localskin = 1 + i; player->skinlocal = true; @@ -280,7 +280,7 @@ void SetLocalPlayerSkin(INT32 playernum, const char *skinname, consvar_t *cvar) for (i = 0; i < numskins; i++) { // search in the skin list - if (stricmp(skins[i].name, skinname) == 0) + if (fasticmp(skins[i].name, skinname)) { player->localskin = 1 + i; player->skinlocal = false; @@ -530,7 +530,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) hudname = realname = false; // parse - stoken = strtok (buf2, "\r\n= "); + stoken = strtok(buf2, "\r\n= "); while (stoken) { if ((stoken[0] == '/' && stoken[1] == '/') @@ -546,7 +546,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) if (!value) I_Error("R_AddSkins: syntax error in S_SKIN lump# %d(%s) in WAD %s\n", lump, W_CheckNameForNumPwad(wadnum,lump), wadfiles[wadnum]->filename); - if (!stricmp(stoken, "name")) + if (fasticmp(stoken, "name")) { // the skin name must uniquely identify a single skin // I'm lazy so if name is already used I leave the 'skin x' @@ -592,7 +592,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) if (*value == '_') *value = ' '; // turn _ into spaces. } } - else if (!stricmp(stoken, "realname")) + else if (fasticmp(stoken, "realname")) { // Display name (eg. "Knuckles") realname = true; STRBUFCPY(skin->realname, value); @@ -603,7 +603,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) if (!hudname) STRBUFCPY(skin->hudname, skin->realname); } - else if (!stricmp(stoken, "hudname")) + else if (fasticmp(stoken, "hudname")) { // Life icon name (eg. "K.T.E") hudname = true; STRBUFCPY(skin->hudname, value); @@ -614,34 +614,34 @@ void R_AddSkins(UINT16 wadnum, boolean local) if (!realname) STRBUFCPY(skin->realname, skin->hudname); } - else if (!stricmp(stoken, "sprite")) + else if (fasticmp(stoken, "sprite")) { strupr(value); memcpy(skin->sprite, value, sizeof skin->sprite); } - else if (!stricmp(stoken, "facerank")) + else if (fasticmp(stoken, "facerank")) { strupr(value); memcpy(skin->facerank, value, sizeof(skin->facerank)-1); skin->facerank[sizeof(skin->facerank)-1] = '\0'; } - else if (!stricmp(stoken, "facewant")) + else if (fasticmp(stoken, "facewant")) { strupr(value); memcpy(skin->facewant, value, sizeof(skin->facewant)-1); skin->facewant[sizeof(skin->facewant)-1] = '\0'; } - else if (!stricmp(stoken, "facemmap")) + else if (fasticmp(stoken, "facemmap")) { strupr(value); strncpy(skin->facemmap, value, sizeof(skin->facemmap)-1); skin->facemmap[sizeof(skin->facemmap)-1] = '\0'; } - else if (!stricmp(stoken, "flags")) // character type identification + else if (fasticmp(stoken, "flags")) // character type identification { skin->flags = get_number(value); } - else if (!stricmp(stoken, "kartspeed")) + else if (fasticmp(stoken, "kartspeed")) { skin->kartspeed = atoi(value); @@ -650,7 +650,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) if (skin->kartspeed > 9) skin->kartspeed = 9; } - else if (!stricmp(stoken, "kartweight")) + else if (fasticmp(stoken, "kartweight")) { skin->kartweight = atoi(value); @@ -660,15 +660,15 @@ void R_AddSkins(UINT16 wadnum, boolean local) skin->kartweight = 9; } // custom translation table - else if (!stricmp(stoken, "startcolor")) + else if (fasticmp(stoken, "startcolor")) { skin->starttranscolor = atoi(value); } - else if (!stricmp(stoken, "prefcolor")) + else if (fasticmp(stoken, "prefcolor")) { skin->prefcolor = K_GetKartColorByName(value); } - else if (!stricmp(stoken, "highresscale")) + else if (fasticmp(stoken, "highresscale")) { skin->highresscale = FLOAT_TO_FIXED(atof(value)); } @@ -687,7 +687,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) continue; if (sfx->skinsound != -1 - && !stricmp(sfx->name, stoken + 2)) + && fasticmp(sfx->name, stoken + 2)) { skin->soundsid[sfx->skinsound] = S_AddSoundFx(value+2, sfx->singularity, sfx->pitch, true); found = true; diff --git a/src/s_sound.c b/src/s_sound.c index e3e86c5b0..1e3f8bf7a 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -1095,9 +1095,12 @@ void S_StartSoundName(void *mo, const char *soundname) // Search existing sounds... for (i = sfx_None + 1; i < NUMSFX; i++) { - if (!S_sfx[i].name) + const sfxinfo_t *sfx = &S_sfx[i]; + + if (!sfx->name) continue; - if (!stricmp(S_sfx[i].name, soundname)) + + if (fasticmp(sfx->name, soundname)) { soundnum = i; break; @@ -1110,6 +1113,7 @@ void S_StartSoundName(void *mo, const char *soundname) { if (newsounds[i] == 0) break; + if (!S_IdPlaying(newsounds[i])) { S_RemoveSoundFx(newsounds[i]); @@ -1266,7 +1270,7 @@ ReadMusicDefFields (UINT16 wadnum, int line, char *stoken, musicdef_t **defp) char *value; char *textline; - if (!stricmp(stoken, "lump")) + if (fasticmp(stoken, "lump")) { value = strtok(NULL, " "); @@ -1341,24 +1345,24 @@ skip_lump: for (textline = def->field; *textline; textline++)\ if (*textline == '_') *textline = ' '; - if (!stricmp(stoken, "usage")) + if (fasticmp(stoken, "usage")) { ADDDEF(usage); } - else if (!stricmp(stoken, "source")) + else if (fasticmp(stoken, "source")) { ADDDEF(source); } - else if (!stricmp(stoken, "title")) + else if (fasticmp(stoken, "title")) { def->use_info = true; ADDDEF(title); } - else if (!stricmp(stoken, "alttitle")) + else if (fasticmp(stoken, "alttitle")) { ADDDEF(alttitle); } - else if (!stricmp(stoken, "authors")) + else if (fasticmp(stoken, "authors")) { ADDDEF(authors); } @@ -1479,7 +1483,8 @@ musicdef_t *S_FindMusicCredit(const char *musname) if (hash != def->hash) continue; - if (stricmp(def->name, musname)) + + if (!fasticmp(def->name, musname)) continue; return def; @@ -1934,7 +1939,7 @@ static const char *musicexception_list[] = { // check if the current music is smth we dont want to keep (vote music, etc) static boolean S_CheckMusicException(void) { - if (stricmp(music.name, mapmusic.name)) + if (!fasticmp(music.name, mapmusic.name)) return true; // dumb hack but dont keepmusic music that is supposed to reset @@ -1944,7 +1949,7 @@ static boolean S_CheckMusicException(void) // in case somehow the mapmusic was replaced with smth we dont want to keep for (size_t i = 0; i < sizeof(musicexception_list)/sizeof(musicexception_list[0]); i++) { - if (!stricmp(music.name, musicexception_list[i]) || !stricmp(checkmusic, musicexception_list[i])) + if (fasticmp(music.name, musicexception_list[i]) || fasticmp(checkmusic, musicexception_list[i])) { return true; } @@ -2030,12 +2035,12 @@ static boolean S_SkipIntroMusic(void) return false; // check if menu music is playing, otherwise it may continue playing - if (!stricmp(music.name, "titles")) + if (fasticmp(music.name, "titles")) return false; char *maptitle = G_BuildMapTitle(gamemap); // Zzz... - if (maptitle && !stricmp(maptitle, "Wandering Falls")) // wandering balls changes its song when the race starts Zzz... + if (maptitle && fasticmp(maptitle, "Wandering Falls")) // wandering balls changes its song when the race starts Zzz... { Z_Free(maptitle); return false; diff --git a/src/w_wad.c b/src/w_wad.c index f9eb9b361..96fe56303 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -375,11 +375,11 @@ static restype_t ResourceFileDetect(const char* filename) { size_t len = strlen(filename) - 4; - if (!stricmp(&filename[len], ".pk3")) + if (fasticmp(&filename[len], ".pk3")) return RET_PK3; - if (!stricmp(&filename[len], ".soc")) + if (fasticmp(&filename[len], ".soc")) return RET_SOC; - if (!stricmp(&filename[len], ".lua")) + if (fasticmp(&filename[len], ".lua")) return RET_LUA; return RET_WAD; @@ -1130,7 +1130,7 @@ UINT16 W_CheckNumForLongNamePwad(const char *name, UINT16 wad, UINT16 startlump) { if (lump_p->longnamelength == namelen && lump_p->hash.longname == hash - && !stricmp(lump_p->longname, name)) + && fasticmp(lump_p->longname, name)) return i; } } @@ -1230,7 +1230,7 @@ static lumpnum_t CheckLumpInCache(const char *name, boolean longname) for (INT32 i = lumpnumcacheindex + LUMPNUMCACHESIZE; i > lumpnumcacheindex; i--) { if (lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].hash == hash - && stricmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name) == 0) + && fasticmp(lumpnumcache[i & (LUMPNUMCACHESIZE - 1)].lumpname, name)) { lumpnumcacheindex = i & (LUMPNUMCACHESIZE - 1); return lumpnumcache[lumpnumcacheindex].lumpnum; -- 2.54.0 From 3095303a4ba65f9fe13d187b711860d56554b5da Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 2 Nov 2025 14:35:28 +0100 Subject: [PATCH 081/116] Revert "simplify vhs effect interpolation" This reverts commit e26fb91350230a906e18d773d0ad4a91c75b81f1. --- src/v_video.c | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/v_video.c b/src/v_video.c index 893a39b20..3b9880942 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -1738,7 +1738,8 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch) void V_DrawVhsEffect(boolean rewind) { - static fixed_t upbary = 100, downbary = 150; + fixed_t uby, dby; + static fixed_t upbary = 100*FRACUNIT, downbary = 150*FRACUNIT; UINT8 barsize, updistort, downdistort; @@ -1759,19 +1760,21 @@ void V_DrawVhsEffect(boolean rewind) if (rewind) V_DrawVhsEffect(false); // experimentation - upbary -= FixedMul(vid.dup * (rewind ? 3 : 1.8f), renderdeltatics); - downbary += FixedMul(vid.dup * (rewind ? 2 : 1), renderdeltatics); + upbary -= renderdeltatics * (vid.dup * (rewind ? 3 : 1.8f)); + downbary += renderdeltatics * (vid.dup * (rewind ? 2 : 1)); - if (upbary < -barsize) - upbary = vid.height; + if (upbary < -barsize*FRACUNIT) + upbary = vid.height << FRACBITS; + if (downbary > vid.height << FRACBITS) + downbary = -barsize*FRACUNIT; - if (downbary > vid.height) - downbary = -barsize; + uby = upbary >> FRACBITS; + dby = downbary >> FRACBITS; #ifdef HWRENDER if (rendermode == render_opengl) { - HWR_RenderVhsEffect(upbary, downbary, updistort, downdistort, barsize); + HWR_RenderVhsEffect(uby, dby, updistort, downdistort, barsize); return; } #endif @@ -1791,16 +1794,16 @@ void V_DrawVhsEffect(boolean rewind) thismapstart = normalmapstart; offs = 0; - if (y >= upbary && y < upbary+barsize) + if (y >= uby && y < uby+barsize) { thismapstart -= (2<= downbary && y < downbary+barsize) + if (y >= dby && y < dby+barsize) { thismapstart -= (2< Date: Fri, 31 Oct 2025 13:07:37 +0000 Subject: [PATCH 082/116] Optimise padding algorithm --- src/hardware/r_opengl/r_opengl.c | 99 ++++++++++++++++++++------------ 1 file changed, 62 insertions(+), 37 deletions(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 3a5fd059a..650e39e13 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -1823,47 +1823,72 @@ static void GL_AllocTextureBuffer(GLMipmap_t *pTexInfo) } } -#define PADDING_CHECK(offset, alphaCheck) { from = to + (offset); if ((alphaCheck)) from = NULL; else goto foundFrom; } - -static void PadRGBABitmap(RGBA_t *tex, UINT16 w, UINT16 h) +static void PadRGBABitmap(RGBA_t *tex, UINT16 w, UINT16 h, UINT32 flags) { - INT32 i; - boolean notLeft, notRight, notTop, notBottom; - RGBA_t *to = tex - 1, *from; + INT32 i, c1, c2, idxAdd; + UINT16 c1size, c2size; + RGBA_t *current, *prev, *next, *first; + boolean ignorePrev, wrap; - for (i = 0; i < w * h; i++) + for (i = 1; i >= 0; i--) { - to++; - if (to->rgba != 0) - continue; - from = NULL; + c1size = i ? w : h; + c2size = i ? h : w; + idxAdd = i ? w : 1; + wrap = i ? flags & TF_WRAPY : flags & TF_WRAPX; - notLeft = i % w != 0; - notRight = i % w != w - 1; - notTop = i / w != 0; - notBottom = i / w != h - 1; - - if (notRight) PADDING_CHECK(1, from->s.alpha == 0) // Check +X - if (notBottom) PADDING_CHECK(w, from->s.alpha == 0) // Check +Y - if (notLeft) PADDING_CHECK(-1, from->s.alpha == 0) // Check -X - if (notTop) PADDING_CHECK(-w, from->s.alpha == 0) // Check -Y - if (notRight && notBottom) PADDING_CHECK(1 + w, from->s.alpha == 0) // Check +X+Y - if (notLeft && notBottom) PADDING_CHECK(-1 + w, from->s.alpha == 0) // Check -X+Y - if (notLeft && notTop) PADDING_CHECK(-1 - w, from->s.alpha == 0) // Check -X-Y - if (notRight && notTop) PADDING_CHECK(1 - w, from->s.alpha == 0) // Check +X-Y - -foundFrom: - if (from != NULL) + for (c1 = 0; c1 < c1size; c1++) { - *to = *from; - to->s.alpha = 0; + if (i) + { + first = current = tex + c1; + prev = wrap ? tex + (c1 + (h - 1) * w) : current; + next = tex + (c1 + w); + } + else + { + first = current = tex + (c1 * w); + prev = wrap ? tex + (w - 1 + c1 * w) : current; + next = tex + (1 + c1 * w); + } + + ignorePrev = false; + + for (c2 = 0; c2 < c2size; c2++) + { + if (c2 == c2size - 1) + next = wrap ? first : current; + + if (current->rgba) + { + ignorePrev = false; + } + else if (prev->rgba && !ignorePrev) + { + *current = *prev; + current->s.alpha = 0; + ignorePrev = true; + } + else if (next->rgba) + { + *current = *next; + current->s.alpha = 0; + ignorePrev = false; + } + else + { + ignorePrev = false; + } + + prev = current; + current = next; + next += idxAdd; + } } } } -#undef PADDING_CHECK - -static void GenerateMipmaps(INT32 w, INT32 h, RGBA_t *tex, INT32 maxLOD) +static void GenerateMipmaps(INT32 w, INT32 h, RGBA_t *tex, INT32 maxLOD, UINT32 flags) { if (tex == NULL) { @@ -1925,7 +1950,7 @@ static void GenerateMipmaps(INT32 w, INT32 h, RGBA_t *tex, INT32 maxLOD) h /= 2; if (padTexture) - PadRGBABitmap(tex, w, h); + PadRGBABitmap(tex, w, h, flags); pglTexSubImage2D(GL_TEXTURE_2D, m + 1, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, tex); } @@ -1939,7 +1964,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) // Upload a texture GLuint num = pTexInfo->downloaded; boolean update = true; - const boolean applyPadding = mag_filter == GL_LINEAR || min_filter == GL_LINEAR; + const boolean applyPadding = mag_filter == GL_LINEAR || min_filter == GL_LINEAR || true; INT32 w = pTexInfo->width, h = pTexInfo->height; INT32 i, j; @@ -2000,7 +2025,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) } if (applyPadding) - PadRGBABitmap(tex, w, h); + PadRGBABitmap(tex, w, h, pTexInfo->flags); break; case GL_TEXFMT_RGBA: @@ -2016,7 +2041,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) ptex = tex; if (applyPadding) - PadRGBABitmap(tex, w, h); + PadRGBABitmap(tex, w, h, pTexInfo->flags); } break; @@ -2087,7 +2112,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) // Control the mipmap level of detail pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 5); - GenerateMipmaps(w, h, tex, 5); + GenerateMipmaps(w, h, tex, 5, pTexInfo->flags); } else { -- 2.54.0 From 326a28ec36ce9aa88afa04856a42980d9633b3ac Mon Sep 17 00:00:00 2001 From: Blue Staggo Date: Fri, 31 Oct 2025 13:10:15 +0000 Subject: [PATCH 083/116] Oops, forgot to disable padding for nearest texture mode --- src/hardware/r_opengl/r_opengl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 650e39e13..7601de06d 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -1964,7 +1964,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) // Upload a texture GLuint num = pTexInfo->downloaded; boolean update = true; - const boolean applyPadding = mag_filter == GL_LINEAR || min_filter == GL_LINEAR || true; + const boolean applyPadding = mag_filter == GL_LINEAR || min_filter == GL_LINEAR; INT32 w = pTexInfo->width, h = pTexInfo->height; INT32 i, j; -- 2.54.0 From 23ba82772622bacebf2a53a139fd5b18d1c8f4ad Mon Sep 17 00:00:00 2001 From: Blue Staggo Date: Fri, 31 Oct 2025 14:04:49 +0000 Subject: [PATCH 084/116] Give midtextures filtering without ugly borders + Clean up padding code Couldn't do proper translucent blending on midtextures because of wrapping. --- src/hardware/hw_main.cpp | 2 +- src/hardware/r_opengl/r_opengl.c | 39 ++++++++++++-------------------- 2 files changed, 15 insertions(+), 26 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index be96fc901..dcefdaec2 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -1237,7 +1237,7 @@ static void HWR_DrawSkyWall(FOutVector *wallVerts, FSurfaceInfo *Surf) // Returns true if the midtexture is visible, and false if... it isn't... static inline boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) { - FUINT blendmode = PF_Masked; + FUINT blendmode = PF_Masked | PF_Translucent; pSurf->PolyColor.s.alpha = 0xFF; diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 7601de06d..d481b56db 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -1830,27 +1830,27 @@ static void PadRGBABitmap(RGBA_t *tex, UINT16 w, UINT16 h, UINT32 flags) RGBA_t *current, *prev, *next, *first; boolean ignorePrev, wrap; - for (i = 1; i >= 0; i--) + for (i = 0; i < 2; i++) { - c1size = i ? w : h; - c2size = i ? h : w; - idxAdd = i ? w : 1; - wrap = i ? flags & TF_WRAPY : flags & TF_WRAPX; + c1size = i ? h : w; + c2size = i ? w : h; + idxAdd = i ? 1 : w; + wrap = i ? flags & TF_WRAPX : flags & TF_WRAPY; for (c1 = 0; c1 < c1size; c1++) { if (i) - { - first = current = tex + c1; - prev = wrap ? tex + (c1 + (h - 1) * w) : current; - next = tex + (c1 + w); - } - else { first = current = tex + (c1 * w); prev = wrap ? tex + (w - 1 + c1 * w) : current; next = tex + (1 + c1 * w); } + else + { + first = current = tex + c1; + prev = wrap ? tex + (c1 + (h - 1) * w) : current; + next = tex + (c1 + w); + } ignorePrev = false; @@ -2086,21 +2086,10 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) pglBindTexture(GL_TEXTURE_2D, num); tex_downloaded = num; - const int transparent = (pTexInfo->flags & TF_TRANSPARENT); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter); + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); - // disable texture filtering on any texture that has holes so there's no dumb borders or blending issues - if (transparent) - { - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - } - else - { - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); - } - - if (MipMap && !transparent) // No mipmaps on transparent stuff + if (MipMap && !(pTexInfo->flags & TF_TRANSPARENT)) // No mipmaps on transparent stuff { pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); -- 2.54.0 From 2b7f2da5ee252e52e521a59a926167e70b32a630 Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 1 Nov 2025 15:33:13 +0100 Subject: [PATCH 085/116] Mipmaps: fix translucent textures turning black i.e. since we allow texture filtering on translucent textures now, the min filter may specifcy one of the mipmap filters, this means we NEED to call GL_GENERATE_MIPMAP and set the LODs for them, otherwise no texture will be generated alternatively we could do a bunch of special cases for the mipmap filters, but this is simpler --- src/hardware/hw_main.cpp | 4 ---- src/hardware/r_opengl/r_opengl.c | 14 +++++++++++--- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index dcefdaec2..c45404159 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -1259,8 +1259,6 @@ static inline boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) case 256: if (gl_linedef->blendmode) blendmode = HWR_SurfaceBlend(gl_linedef->blendmode, R_GetLinedefTransTable(gl_linedef->alpha), pSurf); - else - blendmode = PF_Translucent; break; default: if (gl_linedef->blendmode) @@ -1272,8 +1270,6 @@ static inline boolean HWR_BlendMidtextureSurface(FSurfaceInfo *pSurf) } else if (gl_linedef->alpha >= 0 && gl_linedef->alpha < FRACUNIT) blendmode = HWR_TranstableToAlpha(R_GetLinedefTransTable(gl_linedef->alpha), pSurf); - else - blendmode = PF_Masked; break; } } diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index d481b56db..09f460c34 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -2089,7 +2089,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter); pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter); - if (MipMap && !(pTexInfo->flags & TF_TRANSPARENT)) // No mipmaps on transparent stuff + if (MipMap) { pglTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); @@ -2100,8 +2100,16 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) // Control the mipmap level of detail pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_LOD, 0); - pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 5); - GenerateMipmaps(w, h, tex, 5, pTexInfo->flags); + + if (pTexInfo->flags & TF_TRANSPARENT) + { + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 0); // No mipmaps on transparent stuff + } + else + { + pglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LOD, 4); + GenerateMipmaps(w, h, tex, 4, pTexInfo->flags); + } } else { -- 2.54.0 From bbbd42e6536099a787415c0202d47dd1a653099e Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 21:27:35 +0100 Subject: [PATCH 086/116] use "offsetof" for skydome vbo offsets silences UBSAN complaining about accessing struct members through null ptr --- src/hardware/r_opengl/r_opengl.c | 38 ++++++++++++-------------------- 1 file changed, 14 insertions(+), 24 deletions(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 09f460c34..566d2458c 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -2490,12 +2490,10 @@ void GL_DrawIndexedTriangles(FSurfaceInfo *pSurf, FOutVector *pOutVerts, FUINT i // the DrawPolygon variant of this has some code about polyflags and wrapping here but havent noticed any problems from omitting it? } -static const boolean gl_ext_arb_vertex_buffer_object = true; - -#define NULL_VBO_VERTEX ((gl_skyvertex_t*)NULL) -#define sky_vbo_x (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->x : &sky->data[0].x) -#define sky_vbo_u (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->u : &sky->data[0].u) -#define sky_vbo_r (gl_ext_arb_vertex_buffer_object ? &NULL_VBO_VERTEX->r : &sky->data[0].r) +//#define NULL_VBO_VERTEX ((gl_skyvertex_t*)NULL) +#define sky_vbo_x ((void*)offsetof(gl_skyvertex_t, x)) +#define sky_vbo_u ((void*)offsetof(gl_skyvertex_t, u)) +#define sky_vbo_r ((void*)offsetof(gl_skyvertex_t, r)) void GL_RenderSkyDome(gl_sky_t *sky) { @@ -2507,30 +2505,23 @@ void GL_RenderSkyDome(gl_sky_t *sky) if (sky->rebuild) { // delete VBO when already exists - if (gl_ext_arb_vertex_buffer_object) - { - if (sky->vbo) - pglDeleteBuffers(1, &sky->vbo); - } + if (sky->vbo) + pglDeleteBuffers(1, &sky->vbo); - if (gl_ext_arb_vertex_buffer_object) - { - // generate a new VBO and get the associated ID - pglGenBuffers(1, &sky->vbo); + // generate a new VBO and get the associated ID + pglGenBuffers(1, &sky->vbo); - // bind VBO in order to use - pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); + // bind VBO in order to use + pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); - // upload data to VBO - pglBufferData(GL_ARRAY_BUFFER, sky->vertex_count * sizeof(sky->data[0]), sky->data, GL_STATIC_DRAW); - } + // upload data to VBO + pglBufferData(GL_ARRAY_BUFFER, sky->vertex_count * sizeof(sky->data[0]), sky->data, GL_STATIC_DRAW); sky->rebuild = false; } // bind VBO in order to use - if (gl_ext_arb_vertex_buffer_object) - pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); + pglBindBuffer(GL_ARRAY_BUFFER, sky->vbo); // activate and specify pointers to arrays pglVertexPointer(3, GL_FLOAT, sizeof(sky->data[0]), sky_vbo_x); @@ -2574,8 +2565,7 @@ void GL_RenderSkyDome(gl_sky_t *sky) pglColor4ubv(white); // bind with 0, so, switch back to normal pointer operation - if (gl_ext_arb_vertex_buffer_object) - pglBindBuffer(GL_ARRAY_BUFFER, 0); + pglBindBuffer(GL_ARRAY_BUFFER, 0); // deactivate color array pglDisableClientState(GL_COLOR_ARRAY); -- 2.54.0 From 9dd1a479696662761b2d12d0276e2b9bab9ae54b Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 21:28:24 +0100 Subject: [PATCH 087/116] fix SINT8 write macro, fix big endian READUINT32 macro --- src/byteptr.h | 4 ++-- src/g_demo.c | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/byteptr.h b/src/byteptr.h index 85141c21c..0c82e6f40 100644 --- a/src/byteptr.h +++ b/src/byteptr.h @@ -27,7 +27,7 @@ extern "C" { // #define WRITEUINT8(p,b) do { UINT8 *p_tmp = ( UINT8 *)p; const UINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) -#define WRITESINT8(p,b) do { SINT8 *p_tmp = ( SINT8 *)p; const SINT8 tv = ( UINT8)(b); memcpy(p, &tv, sizeof( UINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) +#define WRITESINT8(p,b) do { SINT8 *p_tmp = ( SINT8 *)p; const SINT8 tv = ( SINT8)(b); memcpy(p, &tv, sizeof( SINT8)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) #define WRITEINT16(p,b) do { INT16 *p_tmp = ( INT16 *)p; const INT16 tv = ( INT16)(b); memcpy(p, &tv, sizeof( INT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) #define WRITEUINT16(p,b) do { UINT16 *p_tmp = ( UINT16 *)p; const UINT16 tv = ( UINT16)(b); memcpy(p, &tv, sizeof( UINT16)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) #define WRITEINT32(p,b) do { INT32 *p_tmp = ( INT32 *)p; const INT32 tv = ( INT32)(b); memcpy(p, &tv, sizeof( INT32)); p_tmp++; *(void**)(&(p)) = (void *)p_tmp; } while (0) @@ -124,7 +124,7 @@ FUNCINLINE static ATTRINLINE UINT32 readulong(void *ptr) #define READINT16(p) readshort(&((const INT16*)(p = (const void*)&((const INT16*)p)[1]))[-1]) #define READUINT16(p) readushort(&((const UINT16*)(p = (const void*)&((const UINT16*)p)[1]))[-1]) #define READINT32(p) readlong(&((const INT32*)(p = (const void*)&((const INT32*)p)[1]))[-1]) -#define READUINT32(p) readulong(&((const UINT32*)(p = (const void*)&((const UINT32*)p)[1])) +#define READUINT32(p) readulong(&((const UINT32*)(p = (const void*)&((const UINT32*)p)[1]))[-1]) #define READCHAR(p) ((const char*)(p = (const void*)&((const char*)p)[1]))[-1] #define READFIXED(p) readlong(&((const fixed_t*)(p = (const void*)&((const fixed_t*)p)[1]))[-1]) #define READANGLE(p) readulong(&((const angle_t*)(p = (const void*)&((const angle_t*)p)[1]))[-1]) diff --git a/src/g_demo.c b/src/g_demo.c index 8c3bbe1c6..3b1f5fce3 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -395,7 +395,7 @@ void G_WriteDemoExtraData(void) // Skin memset(name, 0, 16); strncpy(name, skins[players[i].skin].name, 16); - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; WRITEUINT8(demobuf.p, skins[players[i].skin].kartspeed); @@ -407,7 +407,7 @@ void G_WriteDemoExtraData(void) // Color memset(name, 0, 16); strncpy(name, KartColor_Names[players[i].skincolor], 16); - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; } @@ -416,7 +416,7 @@ void G_WriteDemoExtraData(void) // Name memset(name, 0, 16); memcpy(name, player_names[i], 15); // Keeping 1 null byte for safety, sorry players with name containing more than 15 characters - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; } @@ -1763,19 +1763,19 @@ void G_BeginRecording(void) // Name memset(name, 0, 16); memcpy(name, player_names[p], 15); - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; // Skin memset(name, 0, 16); strncpy(name, skins[player->skin].name, 16); - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; // Color memset(name, 0, 16); strncpy(name, KartColor_Names[player->skincolor], 16); - M_Memcpy(demobuf.p,name,16); + M_Memcpy(demobuf.p, name, 16); demobuf.p += 16; // Score, since Kart uses this to determine where you start on the map -- 2.54.0 From a7c5254a32b84b7278e1ac2f5e394d754c630c8d Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 21:29:01 +0100 Subject: [PATCH 088/116] set "-Wno-cast-qual" for clang see comment --- src/Makefile.d/versions.mk | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Makefile.d/versions.mk b/src/Makefile.d/versions.mk index 83600d735..451ff72e7 100644 --- a/src/Makefile.d/versions.mk +++ b/src/Makefile.d/versions.mk @@ -144,8 +144,10 @@ ifdef GCC81 WFLAGS+=-Wno-error=multistatement-macros endif -ifeq ($(CC),clang) - WFLAGS+= -Wno-unknown-pragmas -Wno-cast-align +ifneq (,$(filter $(CC) $(CXX),clang clang++)) + WFLAGS+= -Wno-unknown-pragmas + WFLAGS+= -Wno-cast-align + WFLAGS+= -Wno-cast-qual # not a fan, but clang really hates our read macros endif ifdef NONX86 -- 2.54.0 From b017a7202660a1e015868b7fb54fa990f585c05c Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 22:04:56 +0100 Subject: [PATCH 089/116] R_DrawPlanes: dont increment garbage ptr does not need to be there at all eitherways --- src/r_plane.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/r_plane.cpp b/src/r_plane.cpp index 8ef47f722..b2d30185d 100644 --- a/src/r_plane.cpp +++ b/src/r_plane.cpp @@ -720,7 +720,7 @@ void R_DrawPlanes(void) srb2::ThreadPool::Sema tp_sema; srb2::g_main_threadpool->begin_sema(); #endif - for (i = 0; i < MAXVISPLANES; i++, pl++) + for (i = 0; i < MAXVISPLANES; i++) { for (pl = visplanes[i]; pl; pl = pl->next) { @@ -755,7 +755,7 @@ void R_DrawSkyPlanes(void) srb2::ThreadPool::Sema tp_sema; srb2::g_main_threadpool->begin_sema(); #endif - for (i = 0; i < MAXVISPLANES; i++, pl++) + for (i = 0; i < MAXVISPLANES; i++) { for (pl = visplanes[i]; pl; pl = pl->next) { -- 2.54.0 From 80613a8a49a87084c7fe173aa7aa34cdd824b6de Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 22:53:10 +0100 Subject: [PATCH 090/116] R_AllocClippingTables & R_AllocTextureColumnTables: fix nullptr arithmetic --- src/r_segs.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/r_segs.cpp b/src/r_segs.cpp index d1cbbf9c2..414221686 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -1718,7 +1718,7 @@ static void R_AllocClippingTables(size_t range) { // Check if it's in range of the openings #define CHECK(which) \ - if (which + drawseg->x1 >= oldopenings && which + drawseg->x1 <= oldlast) \ + if (which != NULL && which + drawseg->x1 >= oldopenings && which + drawseg->x1 <= oldlast) \ which = (which - oldopenings) + openings CHECK(drawseg->sprtopclip); CHECK(drawseg->sprbottomclip); @@ -1752,7 +1752,7 @@ static void R_AllocTextureColumnTables(size_t range) { // Check if it's in range of the tables #define CHECK(which) \ - if (which + drawseg->x1 >= oldtable && which + drawseg->x1 <= oldlast) \ + if (which != NULL && which + drawseg->x1 >= oldtable && which + drawseg->x1 <= oldlast) \ which = (which - oldtable) + texturecolumntable CHECK(drawseg->maskedtexturecol); CHECK(drawseg->thicksidecol); -- 2.54.0 From 67e1793f49951f69d2e88fe143d785e0c26d81fa Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 5 Nov 2025 23:03:25 +0100 Subject: [PATCH 091/116] software renderer: handle some float type related issues with slope drawers there were a bunch of cases where inf and nan float results were casted and used with integer things, which is undefined in c yes i did use ceepeepee for that crap, cause this wouldve been really annoying without templating if someone really wants that crap to use outside ceepeepee, feel free to make a bunch of wrappers cause im too lazy for that stuff --- src/cxxutil.hpp | 67 +++++++++++++++++++++++++++++++++++++++++++++ src/r_draw_span.cpp | 22 ++++++++------- src/r_segs.cpp | 10 ++++--- 3 files changed, 85 insertions(+), 14 deletions(-) diff --git a/src/cxxutil.hpp b/src/cxxutil.hpp index 591d7aa4d..91c1a8641 100644 --- a/src/cxxutil.hpp +++ b/src/cxxutil.hpp @@ -147,6 +147,73 @@ public: template NotNull(T) -> NotNull; +// does a super safe cast from floating point to interger types +// this prob could be better since i suck at ceepeepee +// but atleast we can just template shit to our desired types +template +static inline IntT floattoint(FloatT val) +{ + // :chaosleep: + static_assert(std::is_floating_point_v, "Input must be a floating-point type"); + static_assert(std::is_integral_v, "Output must be a integer type"); + + if (std::fpclassify(val) == FP_NAN) + return 0; // if stuffs not a number we sure screwed up lmao + + // treat inifinity as "int min/max" + if (std::fpclassify(val) == FP_INFINITE) + { + // yes infinity can be signed kek + if (std::signbit(val)) + return std::numeric_limits::min(); // negative infinity, so return min + else + return std::numeric_limits::max(); + } + + // make sure we fit into our targettype uwu + if (val > static_cast(std::numeric_limits::max())) + return std::numeric_limits::max(); + else if (val < static_cast(std::numeric_limits::min())) + return std::numeric_limits::min(); + + return static_cast(val); +} + +// safe float to fixed +// which handles nan and inf +// pretty much the same stuff as the above, but uh, idk how id use the above with this +template // can use both float and doubles yay +static inline int32_t floattofixed(FloatT val) +{ + // :chaosleep: + static_assert(std::is_floating_point_v, "Input must be a floating-point type"); + + // fixed_t is just an int32_t, i dont wanna include doomtype here if it can be avoided + + if (std::fpclassify(val) == FP_NAN) + return 0; // if stuffs not a number we sure screwed up lmao + + // treat inifinity as "int min/max" + if (std::fpclassify(val) == FP_INFINITE) + { + // yes infinity can be signed kek + if (std::signbit(val)) + return std::numeric_limits::min(); // negative infinity, so return min + else + return std::numeric_limits::max(); + } + + const FloatT ret = (val * 65536.0); + + // make sure we fit into our targettype uwu + if (ret > static_cast(std::numeric_limits::max())) + return std::numeric_limits::max(); + else if (ret < static_cast(std::numeric_limits::min())) + return std::numeric_limits::min(); + + return static_cast(ret); +} + } // namespace srb2 #endif // __SRB2_CXXUTIL_HPP__ diff --git a/src/r_draw_span.cpp b/src/r_draw_span.cpp index 11415d2d5..e5ee15463 100644 --- a/src/r_draw_span.cpp +++ b/src/r_draw_span.cpp @@ -28,6 +28,8 @@ #include #include +#include "cxxutil.hpp" + // ========================================================================== // SPANS // ========================================================================== @@ -315,10 +317,10 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) endz = 1.f/iz; endu = uz*endz; endv = vz*endz; - stepu = (INT64)((endu - startu) * INVSPAN); - stepv = (INT64)((endv - startv) * INVSPAN); - u = (INT64)(startu); - v = (INT64)(startv); + stepu = srb2::floattoint((endu - startu) * INVSPAN); + stepv = srb2::floattoint((endv - startv) * INVSPAN); + u = srb2::floattoint(startu); + v = srb2::floattoint(startv); const INT32 x1 = ds->x1; @@ -345,8 +347,8 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) { if (width == 1) { - u = (INT64)(startu); - v = (INT64)(startv); + u = srb2::floattoint(startu); + v = srb2::floattoint(startv); bit = ((v >> nflatyshift) & nflatmask) | (u >> nflatxshift); colormap = planezlight[tiltlight[ds->x1]] + colormap_diff; if constexpr (Type & DS_RIPPLE) @@ -366,10 +368,10 @@ static void R_DrawTiltedSpanTemplate(drawspandata_t* ds) endu = uz*endz; endv = vz*endz; left = 1.f/left; - stepu = (INT64)((endu - startu) * left); - stepv = (INT64)((endv - startv) * left); - u = (INT64)(startu); - v = (INT64)(startv); + stepu = srb2::floattoint((endu - startu) * left); + stepv = srb2::floattoint((endv - startv) * left); + u = srb2::floattoint(startu); + v = srb2::floattoint(startv); for (; width != 0; width--) { diff --git a/src/r_segs.cpp b/src/r_segs.cpp index 414221686..121920a69 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -30,6 +30,8 @@ #include "core/memory.h" +#include "cxxutil.hpp" + #define HEIGHTBITS 12 #define HEIGHTUNIT (1<leftpos.x = segleft.x = DoubleToFixed((b2*c1 - b1*c2)/det); - ds_p->leftpos.y = segleft.y = DoubleToFixed((a1*c2 - a2*c1)/det); + ds_p->leftpos.x = segleft.x = srb2::floattofixed((b2*c1 - b1*c2)/det); + ds_p->leftpos.y = segleft.y = srb2::floattofixed((a1*c2 - a2*c1)/det); // right temp = xtoviewangle[stop]+viewangle; @@ -1902,8 +1904,8 @@ void R_StoreWallRange(INT32 start, INT32 stop) det = a1*b2 - a2*b1; - ds_p->rightpos.x = segright.x = DoubleToFixed((b2*c1 - b1*c2)/det); - ds_p->rightpos.y = segright.y = DoubleToFixed((a1*c2 - a2*c1)/det); + ds_p->rightpos.x = segright.x = srb2::floattofixed((b2*c1 - b1*c2)/det); + ds_p->rightpos.y = segright.y = srb2::floattofixed((a1*c2 - a2*c1)/det); } #define SLOPEPARAMS(slope, end1, end2, normalheight) \ -- 2.54.0 From e9c2b982c6678c95318b86afb84ce896eb77069a Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 17:37:04 +0100 Subject: [PATCH 092/116] smol cleanup JoyAxis stuff & g_game --- src/g_game.c | 163 +++++++++++++++++++++++++++------------------------ 1 file changed, 86 insertions(+), 77 deletions(-) diff --git a/src/g_game.c b/src/g_game.c index 125c88067..10c7af4e3 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -570,6 +570,7 @@ static void G_SetSaveGameModified(void) { if (!unlockables[i].conditionset) continue; + if (!unlockables[i].unlocked) { unlockables[i].unlocked = true; @@ -595,7 +596,7 @@ void G_SetGameModified(boolean silent, boolean major) G_SetSaveGameModified(); if (!silent) - CONS_Alert(CONS_NOTICE, M_GetText("Record Attack data will be saved to a seperate save file.\n")); + CONS_Alert(CONS_NOTICE, "Record Attack data will be saved to a seperate save file.\n"); // If in record attack recording, cancel it. if (modeattacking) @@ -634,6 +635,7 @@ const char *G_BuildMapName(INT32 map) map = gamemap-1; else map = prevmap; + map = G_RandMap(G_TOLFlag(cv_newgametype.value), map, false, 0, false, NULL)+1; } @@ -687,11 +689,12 @@ INT32 JoyAxis(axis_input_e axissel, UINT8 player) { INT32 retaxis; INT32 axisval; + INT32 deadzone; boolean flp = false; UINT8 pnum = player-1; - //find what axis to get + // find what axis to get switch (axissel) { case AXISTURN: @@ -750,45 +753,33 @@ INT32 JoyAxis(axis_input_e axissel, UINT8 player) { axisval /= 2; retaxis = joyxmove[pnum][axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick[pnum].bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_xdeadzone[pnum].value) >> FRACBITS; - if (abs(retaxis) <= jdeadzone) - return 0; - } - - if (flp) - retaxis = -retaxis; // flip it around - - return retaxis; + deadzone = cv_xdeadzone[pnum].value; } else { axisval--; axisval /= 2; retaxis = joyymove[pnum][axisval]; - - if (retaxis < (-JOYAXISRANGE)) - retaxis = -JOYAXISRANGE; - if (retaxis > (+JOYAXISRANGE)) - retaxis = +JOYAXISRANGE; - if (!Joystick[pnum].bGamepadStyle && axissel < AXISDEAD) - { - const INT32 jdeadzone = ((JOYAXISRANGE-1) * cv_ydeadzone[pnum].value) >> FRACBITS; - if (abs(retaxis) <= jdeadzone) - return 0; - } - - if (flp) - retaxis = -retaxis; // flip it around - - return retaxis; + deadzone = cv_ydeadzone[pnum].value; } + + if (retaxis < (-JOYAXISRANGE)) + retaxis = -JOYAXISRANGE; + if (retaxis > (+JOYAXISRANGE)) + retaxis = +JOYAXISRANGE; + + if (!Joystick[pnum].bGamepadStyle && axissel < AXISDEAD) + { + const INT32 jdeadzone = ((JOYAXISRANGE-1) * deadzone) >> FRACBITS; + + if (abs(retaxis) <= jdeadzone) + return 0; + } + + if (flp) + retaxis = -retaxis; // flip it around + + return retaxis; } boolean InputDown(INT32 gc, UINT8 p) @@ -806,9 +797,9 @@ boolean InputDown(INT32 gc, UINT8 p) } } -INT32 localaiming[MAXSPLITSCREENPLAYERS]; -angle_t localangle[MAXSPLITSCREENPLAYERS]; -boolean camspin[MAXSPLITSCREENPLAYERS]; +INT32 localaiming[MAXSPLITSCREENPLAYERS] = {0}; +angle_t localangle[MAXSPLITSCREENPLAYERS] = {0}; +boolean camspin[MAXSPLITSCREENPLAYERS] = {0}; static fixed_t forwardmove[2] = {25<>16, 50<>16}; static fixed_t sidemove[2] = {2<>16, 4<>16}; @@ -1210,7 +1201,7 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) if (gamestate == GS_LEVEL) LUA_HookTiccmd(player, cmd, HOOK(PlayerCmd)); - //Reset away view if a command is given. + // Reset away view if a command is given. if (displayplayers[0] != consoleplayer && ssplayer == 1 && (cmd->forwardmove || cmd->sidemove || cmd->buttons)) { @@ -1261,7 +1252,7 @@ static void G_DoLoadLevel(boolean resetplayer) if (gamestate == GS_INTERMISSION) Y_EndIntermission(); - if (gamestate == GS_VOTING) + else if (gamestate == GS_VOTING) Y_EndVote(); G_SetGamestate(GS_LEVEL); @@ -2329,12 +2320,6 @@ void G_PlayerReborn(INT32 player) if (gametype == GT_COOP) P_FindEmerald(); // scan for emeralds to hunt for - - // Reset Nights score and max link to 0 on death - p->maxlink = 0; - - // If NiGHTS, find lowest mare to start with. - p->mare = 0; } // @@ -2353,22 +2338,25 @@ static boolean G_CheckSpot(INT32 playernum, mapthing_t *mthing) if (!mthing) return false; + x = mthing->x << FRACBITS; + y = mthing->y << FRACBITS; + if (!players[playernum].mo) { // first spawn of level for (i = 0; i < playernum; i++) + { if (playeringame[i] && players[i].mo - && players[i].mo->x == mthing->x << FRACBITS - && players[i].mo->y == mthing->y << FRACBITS) + && players[i].mo->x == x + && players[i].mo->y == y) { return false; } + } + return true; } - x = mthing->x << FRACBITS; - y = mthing->y << FRACBITS; - if (!K_CheckPlayersRespawnColliding(playernum, x, y)) return false; @@ -2870,17 +2858,23 @@ UINT8 G_GetGametypeColor(INT16 gt) */ INT16 G_TOLFlag(INT32 pgametype) { - if (!multiplayer) return TOL_SP; - if (pgametype == GT_COOP) return TOL_RACE; // SRB2kart - if (pgametype == GT_COMPETITION) return TOL_COMPETITION; - if (pgametype == GT_RACE) return TOL_RACE; - if (pgametype == GT_MATCH) return TOL_MATCH; - if (pgametype == GT_TEAMMATCH) return TOL_MATCH; - if (pgametype == GT_TAG) return TOL_TAG; - if (pgametype == GT_HIDEANDSEEK) return TOL_TAG; - if (pgametype == GT_CTF) return TOL_CTF; + if (!multiplayer) return TOL_SP; + + switch (pgametype) + { + case GT_COOP: return TOL_RACE; // SRB2kart + case GT_COMPETITION: return TOL_COMPETITION; + case GT_RACE: return TOL_RACE; + case GT_MATCH: return TOL_MATCH; + case GT_TEAMMATCH: return TOL_MATCH; + case GT_TAG: return TOL_TAG; + case GT_HIDEANDSEEK: return TOL_TAG; + case GT_CTF: return TOL_CTF; + default: + CONS_Alert(CONS_ERROR, "Unknown gametype! %d\n", pgametype); + break; + } - CONS_Alert(CONS_ERROR, M_GetText("Unknown gametype! %d\n"), pgametype); return INT16_MAX; } @@ -3063,6 +3057,7 @@ static void G_DoCompleted(void) K_StatRound(); for (i = 0; i < MAXPLAYERS; i++) + { if (playeringame[i]) { // SRB2Kart: exitlevel shouldn't get you the points @@ -3072,8 +3067,10 @@ static void G_DoCompleted(void) if (P_IsLocalPlayer(&players[i])) j++; } + G_PlayerFinishLevel(i); // take away cards and stuff } + } // play some generic music if there's no win/cool/lose music going on (for exitlevel commands) if (G_RaceGametype() && ((multiplayer && demo.playback) || j == splitscreen+1) && (cv_inttime.value > 0)) @@ -3217,10 +3214,14 @@ void G_AfterIntermission(void) return; } - else if (demo.recording && (modeattacking || demo.savemode != DSM_NOTSAVING)) - G_SaveDemo(); - else if (demo.recording) - G_ResetDemoRecording(); + + if (demo.recording) + { + if (modeattacking || demo.savemode != DSM_NOTSAVING) + G_SaveDemo(); + else + G_ResetDemoRecording(); + } if (modeattacking) // End the run. { @@ -3229,7 +3230,9 @@ void G_AfterIntermission(void) } if (mapheaderinfo[gamemap-1]->cutscenenum) // Start a custom cutscene. + { F_StartCustomCutscene(mapheaderinfo[gamemap-1]->cutscenenum-1, false, false); + } else { if (nextmap < 1100-1) @@ -3366,10 +3369,13 @@ static void G_DoContinued(void) // when something new is added. void G_EndGame(void) { - if (demo.recording && (modeattacking || demo.savemode != DSM_NOTSAVING)) - G_SaveDemo(); - else if (demo.recording) - G_ResetDemoRecording(); + if (demo.recording) + { + if (modeattacking || demo.savemode != DSM_NOTSAVING) + G_SaveDemo(); + else + G_ResetDemoRecording(); + } // Only do evaluation and credits in coop games. if (gametype == GT_COOP) @@ -3379,6 +3385,7 @@ void G_EndGame(void) F_StartCredits(); return; } + if (nextmap == 1101-1) // end game with evaluation { F_StartGameEvaluation(); @@ -3478,9 +3485,8 @@ void G_LoadGameData(void) modded = READUINT8(save.p); // Aha! Someone's been screwing with the save file! - if ((modded && !savemoddata)) - goto datacorrupt; - else if (modded != true && modded != false) + if ((modded && !savemoddata) || + (modded != true && modded != false)) goto datacorrupt; // TODO put another cipher on these things? meh, I don't care... @@ -3545,7 +3551,7 @@ void G_LoadGameData(void) return; // Landing point for corrupt gamedata - datacorrupt: +datacorrupt: { const char *gdfolder = "the SRB2Kart folder"; @@ -4266,18 +4272,21 @@ INT32 G_FindMapByNameOrCode(const char *mapname, char **realmapnamep) { if (mapname[0] == '*') // current map return gamemap; - else if (mapname[0] == '?' && mapheaderinfo[gamemap-1]) + + if (mapname[0] == '?' && mapheaderinfo[gamemap-1]) return G_RandMap(G_TOLFlag(gametype), gamemap-1, false, 0, false, NULL)+1; - else if (mapname[0] == '+' && mapheaderinfo[gamemap-1]) // next map + + if (mapname[0] == '+' && mapheaderinfo[gamemap-1]) // next map { newmapnum = mapheaderinfo[gamemap-1]->nextlevel; + if (newmapnum < 1 || newmapnum > NUMMAPS) { - CONS_Alert(CONS_ERROR, M_GetText("NextLevel (%d) is not a valid map.\n"), newmapnum); + CONS_Alert(CONS_ERROR, "NextLevel (%d) is not a valid map.\n", newmapnum); return 0; } - else - return newmapnum; + + return newmapnum; } } else if (mapnamelen == 2)/* maybe two digit code */ -- 2.54.0 From bce18e3d614538caceff0d71569bfe912bc1493f Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 17:35:07 +0100 Subject: [PATCH 093/116] delet M_Memcpy was just a wrapper for memcpy eitherway so should make no difference other than avoid any confusion figured i could just use "sed" command lel --- src/command.c | 10 +++--- src/console.c | 4 +-- src/d_clisrv.c | 18 +++++----- src/d_net.c | 10 +++--- src/d_netfil.c | 4 +-- src/doomdef.h | 5 --- src/f_wipe.c | 4 +-- src/g_demo.c | 76 +++++++++++++++++++-------------------- src/g_game.c | 6 ++-- src/hardware/hw_bsp.c | 2 +- src/hardware/hw_cache.c | 8 ++--- src/hardware/hw_main.cpp | 4 +-- src/hardware/hw_md2.c | 4 +-- src/hardware/hw_model.c | 10 +++--- src/hardware/hw_shaders.c | 8 ++--- src/i_tcp.c | 4 +-- src/k_kart.c | 4 +-- src/lua_baselib.c | 2 +- src/m_fixed.c | 6 ++-- src/m_misc.c | 2 +- src/p_enemy.c | 12 +++---- src/p_mobj.c | 16 ++++----- src/p_setup.c | 36 +++++++++---------- src/p_spec.c | 8 ++--- src/r_data.c | 14 ++++---- src/r_draw.cpp | 2 +- src/r_patch.cpp | 10 +++--- src/r_patchrotation.cpp | 2 +- src/r_segs.cpp | 4 +-- src/r_skins.c | 2 +- src/r_things.cpp | 6 ++-- src/s_sound.c | 2 +- src/sdl/i_net.c | 6 ++-- src/sdl/sdl_sound.c | 10 +++--- src/v_video.c | 16 ++++----- src/w_wad.c | 4 +-- src/z_zone.cpp | 3 +- 37 files changed, 170 insertions(+), 174 deletions(-) diff --git a/src/command.c b/src/command.c index ab1b94433..459938aa8 100644 --- a/src/command.c +++ b/src/command.c @@ -142,7 +142,7 @@ void COM_BufInsertText(const char *ptext) templen = com_text.cursize; if (templen) { - temp = M_Memcpy(ZZ_Alloc(templen), com_text.data, templen); + temp = memcpy(ZZ_Alloc(templen), com_text.data, templen); VS_Clear(&com_text); } @@ -199,7 +199,7 @@ void COM_BufExecute(void) break; } - M_Memcpy(line, ptext, i); + memcpy(line, ptext, i); line[i] = 0; // flush the command text from the command buffer, _BEFORE_ @@ -1129,7 +1129,7 @@ void *VS_GetSpace(vsbuf_t *buf, size_t length) */ void VS_Write(vsbuf_t *buf, const void *data, size_t length) { - M_Memcpy(VS_GetSpace(buf, length), data, length); + memcpy(VS_GetSpace(buf, length), data, length); } /** Prints text in a variable buffer. Like VS_Write() plus a @@ -1146,9 +1146,9 @@ void VS_Print(vsbuf_t *buf, const char *data) len = strlen(data) + 1; if (buf->data[buf->cursize-1]) - M_Memcpy((UINT8 *)VS_GetSpace(buf, len), data, len); // no trailing 0 + memcpy((UINT8 *)VS_GetSpace(buf, len), data, len); // no trailing 0 else - M_Memcpy((UINT8 *)VS_GetSpace(buf, len-1) - 1, data, len); // write over trailing 0 + memcpy((UINT8 *)VS_GetSpace(buf, len-1) - 1, data, len); // write over trailing 0 } // ========================================================================= diff --git a/src/console.c b/src/console.c index 062e6ebf3..3172b9f20 100644 --- a/src/console.c +++ b/src/console.c @@ -521,7 +521,7 @@ static void CON_RecalcSize(void) oldcon_width = con_width; oldnumlines = con_totallines; oldcon_cy = con_cy; - M_Memcpy(tmp_buffer, con_buffer, CON_BUFFERSIZE); + memcpy(tmp_buffer, con_buffer, CON_BUFFERSIZE); if (conw < 1) con_width = (BASEVIDWIDTH>>3) - 2; @@ -547,7 +547,7 @@ static void CON_RecalcSize(void) { if (tmp_buffer[(i%oldnumlines)*oldcon_width]) { - M_Memcpy(string, &tmp_buffer[(i%oldnumlines)*oldcon_width], oldcon_width); + memcpy(string, &tmp_buffer[(i%oldnumlines)*oldcon_width], oldcon_width); conw = oldcon_width - 1; while (string[conw] == ' ' && conw) conw--; diff --git a/src/d_clisrv.c b/src/d_clisrv.c index db5b6b534..eb39f34f7 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -331,7 +331,7 @@ static void WriteNetXCmd(UINT8 *cmd, netxcmd_t id, const void *param, size_t npa cmd[cmd[0]] = (UINT8)id; if (param && nparam) { - M_Memcpy(&cmd[cmd[0]+1], param, nparam); + memcpy(&cmd[cmd[0]+1], param, nparam); cmd[0] = (UINT8)(cmd[0] + (UINT8)nparam); } } @@ -1585,7 +1585,7 @@ static void SV_SendServerInfo(INT32 node, tic_t servertime) MAXSERVERNAME); strncpy(netbuffer->u.serverinfo.mapname, G_BuildMapName(gamemap), sizeof(netbuffer->u.serverinfo.mapname)-1); - M_Memcpy(netbuffer->u.serverinfo.mapmd5, mapmd5, sizeof(netbuffer->u.serverinfo.mapmd5)); + memcpy(netbuffer->u.serverinfo.mapmd5, mapmd5, sizeof(netbuffer->u.serverinfo.mapmd5)); netbuffer->u.serverinfo.iszone = 0; @@ -4648,7 +4648,7 @@ void SV_StopServer(void) if (gamestate == GS_INTERMISSION) Y_EndIntermission(); - if (gamestate == GS_VOTING) + else if (gamestate == GS_VOTING) Y_EndVote(); G_SetGamestate(GS_NULL); @@ -4664,6 +4664,8 @@ void SV_StopServer(void) textcmdbuf[i] = textcmdbuf[i]->next; Z_Free(buf); } + + textcmdbuf[i] = NULL; } for (i = firstticstosend; i < firstticstosend + BACKUPTICS; i++) @@ -5687,7 +5689,7 @@ static void PT_TextCmd(INT32 netconsole, SINT8 node) DEBFILE(va("textcmd put in tic %u at position %d (player %d) ftts %u mk %u\n", tic, textcmd[0]+1, netconsole, firstticstosend, maketic)); - M_Memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); + memcpy(&textcmd[textcmd[0]+1], netbuffer->u.textcmd+1, netbuffer->u.textcmd[0]); textcmd[0] += (UINT8)netbuffer->u.textcmd[0]; } } @@ -5794,7 +5796,7 @@ static void PT_ServerTics(SINT8 node) } if (i >= gametic) // Don't copy old net commands - M_Memcpy(D_GetTextcmd(i, playernum), txtpak, txtsize); + memcpy(D_GetTextcmd(i, playernum), txtpak, txtsize); txtpak += txtsize; } } @@ -6332,7 +6334,7 @@ static void CL_SendClientCmd(void) break; } - M_Memcpy(netbuffer->u.textcmd, localtextcmd[i], localtextcmd[i][0]+1); + memcpy(netbuffer->u.textcmd, localtextcmd[i], localtextcmd[i][0]+1); // All extra data have been sent if (HSendPacket(servernode, true, 0, localtextcmd[i][0]+1)) // Send can fail... @@ -6342,7 +6344,7 @@ static void CL_SendClientCmd(void) if (textcmdbuf[i] != NULL) { textcmdbuf_t *buf = textcmdbuf[i]; - M_Memcpy(localtextcmd[i], textcmdbuf[i]->cmd, textcmdbuf[i]->cmd[0]+1); + memcpy(localtextcmd[i], textcmdbuf[i]->cmd, textcmdbuf[i]->cmd[0]+1); textcmdbuf[i] = textcmdbuf[i]->next; Z_Free(buf); } @@ -6455,7 +6457,7 @@ static void SV_SendTics(void) { (*ntextcmd)++; WRITEUINT8(bufpos, j); - M_Memcpy(bufpos, textcmd, size + 1); + memcpy(bufpos, textcmd, size + 1); bufpos += size + 1; } } diff --git a/src/d_net.c b/src/d_net.c index 61492f2a8..d5b11f018 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -243,7 +243,7 @@ static boolean GetFreeAcknum(UINT8 *freeack) ackpak[i].length = doomcom->datalength; ackpak[i].senttime = I_GetTime(); ackpak[i].resentnum = 0; - M_Memcpy(ackpak[i].pak.raw, netbuffer, ackpak[i].length); + memcpy(ackpak[i].pak.raw, netbuffer, ackpak[i].length); *freeack = ackpak[i].acknum; @@ -412,7 +412,7 @@ void Net_SendAcks(INT32 node) { doomdata_t *netbuffer = DOOMCOM_DATA(doomcom); netbuffer->packettype = PT_NOTHING; - M_Memcpy(netbuffer->u.textcmd, nodes[node].acktosend, MAXACKTOSEND); + memcpy(netbuffer->u.textcmd, nodes[node].acktosend, MAXACKTOSEND); HSendPacket(node, false, 0, MAXACKTOSEND); } @@ -494,7 +494,7 @@ void Net_AckTicker(void) } DEBFILE(va("Resend ack %d, %u<%d at %u\n", ackpak[i].acknum, ackpak[i].senttime, NODETIMEOUT, I_GetTime())); - M_Memcpy(netbuffer, ackpak[i].pak.raw, ackpak[i].length); + memcpy(netbuffer, ackpak[i].pak.raw, ackpak[i].length); ackpak[i].senttime = I_GetTime(); ackpak[i].resentnum++; ackpak[i].nextacknum = node->nextacknum; @@ -1021,7 +1021,7 @@ boolean HSendPacket(INT32 node, boolean reliable, UINT8 acknum, size_t packetlen return false; } netbuffer->ack = netbuffer->ackreturn = 0; // don't hold over values from last packet sent/received - M_Memcpy(&reboundstore[rebound_head], netbuffer, + memcpy(&reboundstore[rebound_head], netbuffer, doomcom->datalength); reboundsize[rebound_head] = doomcom->datalength; rebound_head = (rebound_head+1) % MAXREBOUND; @@ -1107,7 +1107,7 @@ boolean HGetPacket(void) // Get a packet from self if (rebound_tail != rebound_head) { - M_Memcpy(netbuffer, &reboundstore[rebound_tail], reboundsize[rebound_tail]); + memcpy(netbuffer, &reboundstore[rebound_tail], reboundsize[rebound_tail]); doomcom->datalength = reboundsize[rebound_tail]; if (netbuffer->packettype == PT_NODETIMEOUT) doomcom->remotenode = netbuffer->u.textcmd[0]; diff --git a/src/d_netfil.c b/src/d_netfil.c index c82165788..6c9183eea 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -902,7 +902,7 @@ void SV_FileSendTicker(void) if (ram) { - M_Memcpy(p->data, &f->id.ram[transfer[i].position], size); + memcpy(p->data, &f->id.ram[transfer[i].position], size); } else if (fread(p->data, 1, size, transferFiles[f->fileid].file) != size) { @@ -1104,7 +1104,7 @@ void nameonly(char *s) ns = &(s[j+1]); len = strlen(ns); #if 0 - M_Memcpy(s, ns, len+1); + memcpy(s, ns, len+1); #else memmove(s, ns, len+1); #endif diff --git a/src/doomdef.h b/src/doomdef.h index 0329eb7f8..cf15d3fa8 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -453,11 +453,6 @@ extern char savegamename[256]; //TODO: delet this #define M_GetText(x) (x) -FUNCINLINE static ATTRINLINE void *M_Memcpy(void *dest, const void *src, size_t n) -{ - return memcpy(dest, src, n); -} - char *va(const char *format, ...) FUNCPRINTF; char *M_GetToken(const char *inputString); char *sizeu1(size_t num); diff --git a/src/f_wipe.c b/src/f_wipe.c index 4c3a067c6..7805957f5 100644 --- a/src/f_wipe.c +++ b/src/f_wipe.c @@ -257,7 +257,7 @@ static void F_DoWipe(fademask_t *fademask) // shortcut - memcpy source to work while (draw_linestogo--) { - M_Memcpy(w_base+relativepos, s_base+relativepos, draw_rowend-draw_rowstart); + memcpy(w_base+relativepos, s_base+relativepos, draw_rowend-draw_rowstart); relativepos += vid.width; } } @@ -266,7 +266,7 @@ static void F_DoWipe(fademask_t *fademask) // shortcut - memcpy target to work while (draw_linestogo--) { - M_Memcpy(w_base+relativepos, e_base+relativepos, draw_rowend-draw_rowstart); + memcpy(w_base+relativepos, e_base+relativepos, draw_rowend-draw_rowstart); relativepos += vid.width; } } diff --git a/src/g_demo.c b/src/g_demo.c index 3b1f5fce3..897238107 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -257,7 +257,7 @@ void G_ReadDemoExtraData(void) UINT8 kartspeed, kartweight; // Skin - M_Memcpy(name, demobuf.p, 16); + memcpy(name, demobuf.p, 16); demobuf.p += 16; SetPlayerSkin(p, name); @@ -274,7 +274,7 @@ void G_ReadDemoExtraData(void) if (extradata & DXD_COLOR) { // Color - M_Memcpy(name, demobuf.p, 16); + memcpy(name, demobuf.p, 16); demobuf.p += 16; for (i = 0; i < MAXSKINCOLORS; i++) if (fasticmp(KartColor_Names[i], name)) // SRB2kart @@ -289,7 +289,7 @@ void G_ReadDemoExtraData(void) if (extradata & DXD_NAME) { // Name - M_Memcpy(player_names[p],demobuf.p,16); + memcpy(player_names[p],demobuf.p,16); demobuf.p += 16; } @@ -395,7 +395,7 @@ void G_WriteDemoExtraData(void) // Skin memset(name, 0, 16); strncpy(name, skins[players[i].skin].name, 16); - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; WRITEUINT8(demobuf.p, skins[players[i].skin].kartspeed); @@ -407,7 +407,7 @@ void G_WriteDemoExtraData(void) // Color memset(name, 0, 16); strncpy(name, KartColor_Names[players[i].skincolor], 16); - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; } @@ -416,7 +416,7 @@ void G_WriteDemoExtraData(void) // Name memset(name, 0, 16); memcpy(name, player_names[i], 15); // Keeping 1 null byte for safety, sorry players with name containing more than 15 characters - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; } @@ -1670,7 +1670,7 @@ void G_BeginRecording(void) demoflags |= DF_LUAVARS; // Setup header. - M_Memcpy(demobuf.p, DEMOHEADER, 12); demobuf.p += 12; + memcpy(demobuf.p, DEMOHEADER, 12); demobuf.p += 12; WRITEUINT8(demobuf.p,VERSION); WRITEUINT8(demobuf.p,SUBVERSION); WRITEUINT16(demobuf.p,DEMOVERSION); @@ -1701,9 +1701,9 @@ void G_BeginRecording(void) demobuf.p += 16; // game data - M_Memcpy(demobuf.p, "PLAY", 4); demobuf.p += 4; + memcpy(demobuf.p, "PLAY", 4); demobuf.p += 4; WRITEINT16(demobuf.p,gamemap); - M_Memcpy(demobuf.p, mapmd5, 16); demobuf.p += 16; + memcpy(demobuf.p, mapmd5, 16); demobuf.p += 16; WRITEUINT8(demobuf.p, demoflags); WRITEUINT8(demobuf.p, gametype & 0xFF); @@ -1763,19 +1763,19 @@ void G_BeginRecording(void) // Name memset(name, 0, 16); memcpy(name, player_names[p], 15); - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; // Skin memset(name, 0, 16); strncpy(name, skins[player->skin].name, 16); - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; // Color memset(name, 0, 16); strncpy(name, KartColor_Names[player->skincolor], 16); - M_Memcpy(demobuf.p, name, 16); + memcpy(demobuf.p, name, 16); demobuf.p += 16; // Score, since Kart uses this to determine where you start on the map @@ -1834,19 +1834,19 @@ void G_WriteStanding(UINT8 ranking, char *name, INT32 skinnum, UINT8 color, UINT // Name memset(temp, 0, 16); strncpy(temp, name, 16); - M_Memcpy(demobuf.p,temp,16); + memcpy(demobuf.p,temp,16); demobuf.p += 16; // Skin memset(temp, 0, 16); strncpy(temp, skins[skinnum].name, 16); - M_Memcpy(demobuf.p,temp,16); + memcpy(demobuf.p,temp,16); demobuf.p += 16; // Color memset(temp, 0, 16); strncpy(temp, KartColor_Names[color], 16); - M_Memcpy(demobuf.p,temp,16); + memcpy(demobuf.p,temp,16); demobuf.p += 16; // Score/time/whatever @@ -2212,7 +2212,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) { case DEMOVERSION: // latest always supported // demo title - M_Memcpy(pdemo->title, info_p, 64); + memcpy(pdemo->title, info_p, 64); info_p += 64; break; #ifdef DEMO_COMPAT_100 @@ -2311,11 +2311,11 @@ void G_LoadDemoInfo(menudemo_t *pdemo) pdemo->standings[count].ranking = READUINT8(extrainfo_p); // Name - M_Memcpy(pdemo->standings[count].name, extrainfo_p, 16); + memcpy(pdemo->standings[count].name, extrainfo_p, 16); extrainfo_p += 16; // Skin - M_Memcpy(temp,extrainfo_p,16); + memcpy(temp,extrainfo_p,16); extrainfo_p += 16; pdemo->standings[count].skin = UINT8_MAX; @@ -2329,7 +2329,7 @@ void G_LoadDemoInfo(menudemo_t *pdemo) } // Color - M_Memcpy(temp,extrainfo_p,16); + memcpy(temp,extrainfo_p,16); extrainfo_p += 16; for (i = 0; i < MAXSKINCOLORS; i++) @@ -2494,7 +2494,7 @@ void G_LoadDemoTitle(menudemo_t *pdemo) { case DEMOVERSION: // latest always supported // demo title - M_Memcpy(pdemo->title, info_p, 64); + memcpy(pdemo->title, info_p, 64); // demo date char *demodate; @@ -2627,7 +2627,7 @@ void G_DoPlayDemo(char *defdemoname) { case DEMOVERSION: // latest always supported // demo title - M_Memcpy(demo.titlename, demobuf.p, 64); + memcpy(demo.titlename, demobuf.p, 64); demobuf.p += 64; break; #ifdef DEMO_COMPAT_100 @@ -2766,15 +2766,15 @@ void G_DoPlayDemo(char *defdemoname) if (demo.version == 0x0001) { // Player name - M_Memcpy(player_names[0],demobuf.p,16); + memcpy(player_names[0],demobuf.p,16); demobuf.p += 16; // Skin - M_Memcpy(skin,demobuf.p,16); + memcpy(skin,demobuf.p,16); demobuf.p += 16; // Color - M_Memcpy(color,demobuf.p,16); + memcpy(color,demobuf.p,16); demobuf.p += 16; demobuf.p += 5; // Backwards compat - some stats @@ -2933,16 +2933,16 @@ void G_DoPlayDemo(char *defdemoname) players[p].spectator = spectator; // Name - M_Memcpy(player_names[p],demobuf.p,16); + memcpy(player_names[p],demobuf.p,16); demobuf.p += 16; // Skin - M_Memcpy(skin,demobuf.p,16); + memcpy(skin,demobuf.p,16); demobuf.p += 16; SetPlayerSkin(p, skin); // Color - M_Memcpy(color,demobuf.p,16); + memcpy(color,demobuf.p,16); demobuf.p += 16; for (i = 0; i < MAXSKINCOLORS; i++) @@ -3101,7 +3101,7 @@ void G_AddGhost(char *defdemoname) return; } - M_Memcpy(md5, p, 16); p += 16; // demo checksum + memcpy(md5, p, 16); p += 16; // demo checksum for (gh = ghosts; gh; gh = gh->next) { @@ -3157,15 +3157,15 @@ void G_AddGhost(char *defdemoname) if (ghostversion == 0x0001) { // Player name (TODO: Display this somehow if it doesn't match cv_playername!) - M_Memcpy(name, p,16); + memcpy(name, p,16); p += 16; // Skin - M_Memcpy(skin, p,16); + memcpy(skin, p,16); p += 16; // Color - M_Memcpy(color, p,16); + memcpy(color, p,16); p += 16; // Ghosts do not have a player structure to put this in. @@ -3215,15 +3215,15 @@ void G_AddGhost(char *defdemoname) } // Player name (TODO: Display this somehow if it doesn't match cv_playername!) - M_Memcpy(name, p, 16); + memcpy(name, p, 16); p += 16; // Skin - M_Memcpy(skin, p, 16); + memcpy(skin, p, 16); p += 16; // Color - M_Memcpy(color, p, 16); + memcpy(color, p, 16); p += 16; p += 4; // score @@ -3260,7 +3260,7 @@ void G_AddGhost(char *defdemoname) gh = Z_Calloc(sizeof(demoghost), PU_LEVEL, NULL); gh->next = ghosts; gh->buffer = buffer; - M_Memcpy(gh->checksum, md5, 16); + memcpy(gh->checksum, md5, 16); gh->p = p; buffer = NULL; // buffer can't be freed now! @@ -3409,7 +3409,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) if (ghostversion == 0x0001) { // Player name - M_Memcpy(dummystaffname, p,16); + memcpy(dummystaffname, p,16); dummystaffname[16] = '\0'; return; // Not really a failure but whatever } @@ -3431,7 +3431,7 @@ void G_UpdateStaffGhostName(lumpnum_t l) if (READUINT8(p) != 0) return; - M_Memcpy(dummystaffname, p, 16); + memcpy(dummystaffname, p, 16); dummystaffname[16] = '\0'; // Ok, no longer any reason to care, bye @@ -3625,7 +3625,7 @@ void G_SaveDemo(void) } WRITEUINT8(demobuf.p, DW_END); // Mark end of demo extra data. - M_Memcpy(p, demo.titlename, 64); // Write demo title here + memcpy(p, demo.titlename, 64); // Write demo title here p += 64; if (multiplayer) diff --git a/src/g_game.c b/src/g_game.c index 10c7af4e3..aa03a0524 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -1210,12 +1210,12 @@ void G_BuildTiccmd(ticcmd_t *cmd, INT32 realtics, UINT8 ssplayer) } } -ticcmd_t *G_CopyTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n) +ticcmd_t *G_CopyTiccmd(ticcmd_t* restrict dest, const ticcmd_t* restrict src, const size_t n) { - return M_Memcpy(dest, src, n*sizeof(*src)); + return memcpy(dest, src, n*sizeof(*src)); } -ticcmd_t *G_MoveTiccmd(ticcmd_t* dest, const ticcmd_t* src, const size_t n) +ticcmd_t *G_MoveTiccmd(ticcmd_t* restrict dest, const ticcmd_t* restrict src, const size_t n) { size_t i; for (i = 0; i < n; i++) diff --git a/src/hardware/hw_bsp.c b/src/hardware/hw_bsp.c index 8cad91168..a3f85d095 100644 --- a/src/hardware/hw_bsp.c +++ b/src/hardware/hw_bsp.c @@ -637,7 +637,7 @@ static void WalkBSPNode(INT32 bspnum, poly_t *poly, UINT16 *leafnode, fixed_t *b WalkBSPNode(bsp->children[0], frontpoly, &bsp->children[0],bsp->bbox[0]); // copy child bbox - M_Memcpy(bbox, bsp->bbox[0], 4*sizeof (fixed_t)); + memcpy(bbox, bsp->bbox[0], 4*sizeof (fixed_t)); } else I_Error("WalkBSPNode: no front poly?"); diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index 4d9fdb54c..ccd6980f3 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -346,7 +346,7 @@ static void HWR_GenerateTexture(INT32 texnum, GLMapTexture_t *gltex, boolean noe gltex->mipmap.colormap = Z_Calloc(sizeof(*gltex->mipmap.colormap), PU_HWRPATCHCOLMIPMAP, NULL); gltex->mipmap.colormap->source = colormap; - M_Memcpy(gltex->mipmap.colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(gltex->mipmap.colormap->data, colormap, 256 * sizeof(UINT8)); blockwidth = texture->width; blockheight = texture->height; @@ -970,7 +970,7 @@ void HWR_GetFlat(lumpnum_t flatlumpnum, boolean noencoremap) #endif glMipmap->colormap = Z_Calloc(sizeof(*glMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL); glMipmap->colormap->source = colormap; - M_Memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); } if (!glMipmap->downloaded) @@ -1068,7 +1068,7 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) { if (memcmp(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8))) { - M_Memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); HWR_UpdatePatchMipmap(patch, glMipmap); } else @@ -1091,7 +1091,7 @@ void HWR_GetMappedPatch(patch_t *patch, const UINT8 *colormap) newMipmap->colormap = Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL); newMipmap->colormap->source = colormap; - M_Memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); HWR_LoadPatchMipmap(patch, newMipmap); } diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index c45404159..09a1686c0 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -4276,8 +4276,8 @@ static void HWR_AddTransparentWall(FOutVector *wallVerts, FSurfaceInfo *pSurf, I { wallinfo_t *wallinfo = static_cast(HWR_CreateDrawNode(DRAWNODE_WALL)); - M_Memcpy(wallinfo->wallVerts, wallVerts, sizeof (wallinfo->wallVerts)); - M_Memcpy(&wallinfo->Surf, pSurf, sizeof (FSurfaceInfo)); + memcpy(wallinfo->wallVerts, wallVerts, sizeof (wallinfo->wallVerts)); + memcpy(&wallinfo->Surf, pSurf, sizeof (FSurfaceInfo)); wallinfo->texnum = texnum; wallinfo->noencore = noencore; wallinfo->blend = blend; diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 10e5e4e1b..9f5fc2c2b 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -1058,7 +1058,7 @@ static void HWR_GetBlendedTexture(patch_t *patch, patch_t *blendgpatch, INT32 sk { if (memcmp(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8))) { - M_Memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(glMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); HWR_CreateBlendedTexture(patch, blendgpatch, glMipmap, skinnum, color); GL_UpdateTexture(glMipmap); } @@ -1085,7 +1085,7 @@ static void HWR_GetBlendedTexture(patch_t *patch, patch_t *blendgpatch, INT32 sk newMipmap->colormap = Z_Calloc(sizeof(*newMipmap->colormap), PU_HWRPATCHCOLMIPMAP, NULL); newMipmap->colormap->source = colormap; - M_Memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); + memcpy(newMipmap->colormap->data, colormap, 256 * sizeof(UINT8)); HWR_CreateBlendedTexture(patch, blendgpatch, newMipmap, skinnum, color); diff --git a/src/hardware/hw_model.c b/src/hardware/hw_model.c index 811ac3b67..8698365e4 100644 --- a/src/hardware/hw_model.c +++ b/src/hardware/hw_model.c @@ -242,7 +242,7 @@ void GenerateVertexNormals(model_t *model) float *vertPtr = frame->vertices; float *oldNormals; - M_Memcpy(newNormals, frame->normals, sizeof(float)*3*mesh->numTriangles*3); + memcpy(newNormals, frame->normals, sizeof(float)*3*mesh->numTriangles*3); for (k = 0; k < mesh->numVertices; k++) { @@ -402,7 +402,7 @@ void Optimize(model_t *model) char *destByte; char *srcByte; - M_Memcpy(&newMesh->uvs[uvCount], + memcpy(&newMesh->uvs[uvCount], curMesh->uvs, sizeof(float)*2*curMesh->numTriangles*3); @@ -410,13 +410,13 @@ void Optimize(model_t *model) dest = (float*)newMesh->frames[0].vertices; src = (float*)curMesh->frames[0].vertices; - M_Memcpy(&dest[vertCount], + memcpy(&dest[vertCount], src, sizeof(float)*3*curMesh->numTriangles*3); dest = (float*)newMesh->frames[0].normals; src = (float*)curMesh->frames[0].normals; - M_Memcpy(&dest[vertCount], + memcpy(&dest[vertCount], src, sizeof(float)*3*curMesh->numTriangles*3); @@ -427,7 +427,7 @@ void Optimize(model_t *model) if (srcByte) { - M_Memcpy(&destByte[colorCount], + memcpy(&destByte[colorCount], srcByte, sizeof(char)*4*curMesh->numTriangles*3); } diff --git a/src/hardware/hw_shaders.c b/src/hardware/hw_shaders.c index 19aea915e..28f8e46d7 100644 --- a/src/hardware/hw_shaders.c +++ b/src/hardware/hw_shaders.c @@ -201,7 +201,7 @@ static char *HWR_PreprocessShader(char *original) CONS_Alert(CONS_ERROR, "HWR_PreprocessShader: Syntax error in #version. Expected version with 3 digits, but got %d digits.\n", version_number_len); return NULL; } - M_Memcpy(shader_glsl_version, read_pos, 3); + memcpy(shader_glsl_version, read_pos, 3); ADVANCE(version_number_len) version_len = (read_pos - original) - version_pos; whitespace_len = strspn(read_pos, WHITESPACE_CHARS); @@ -304,7 +304,7 @@ static char *HWR_PreprocessShader(char *original) { strcpy(write_pos, VERSION_PART); write_pos += sizeof(VERSION_PART) - 1; - M_Memcpy(write_pos, shader_glsl_version, 3); + memcpy(write_pos, shader_glsl_version, 3); write_pos += 3; strcpy(write_pos, line_ending); write_pos += line_ending_len; @@ -344,7 +344,7 @@ static char *HWR_PreprocessShader(char *original) } // Copy the original shader. - M_Memcpy(write_pos, read_pos, original_len); + memcpy(write_pos, read_pos, original_len); // Erase the original #version directive, if it exists and was copied. if (new_len != original_len && version_pos != -1) @@ -573,7 +573,7 @@ void HWR_LoadCustomShadersFromFile(UINT16 wadnum, boolean PK3) size = W_LumpLengthPwad(wadnum, lump); line = Z_Malloc(size+1, PU_STATIC, NULL); - M_Memcpy(line, shaderdef, size); + memcpy(line, shaderdef, size); line[size] = '\0'; stoken = strtok(line, "\r\n "); diff --git a/src/i_tcp.c b/src/i_tcp.c index 531db4ab9..5b6a0bf08 100644 --- a/src/i_tcp.c +++ b/src/i_tcp.c @@ -670,7 +670,7 @@ static boolean SOCK_Get(void) { const time_t curTime = time(NULL); - M_Memcpy(&clientaddress[j], &fromaddress, fromlen); + memcpy(&clientaddress[j], &fromaddress, fromlen); nodesocket[j] = mysockets[n]; DEBFILE(va("New node detected: node:%d address:%s\n", j, SOCK_GetNodeAddress(j))); @@ -1485,7 +1485,7 @@ static boolean SOCK_Ban(INT32 node) ban = numbans; AddBannedIndex(); - M_Memcpy(&banned[ban].address, &clientaddress[node], sizeof (mysockaddr_t)); + memcpy(&banned[ban].address, &clientaddress[node], sizeof (mysockaddr_t)); if (banned[ban].address.any.sa_family == AF_INET) { diff --git a/src/k_kart.c b/src/k_kart.c index 3f335a5bb..1383e4f7c 100644 --- a/src/k_kart.c +++ b/src/k_kart.c @@ -2860,9 +2860,9 @@ void K_SpawnKartExplosion(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(rotangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(closestangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); finalx = x + v[0]; finaly = y + v[1]; diff --git a/src/lua_baselib.c b/src/lua_baselib.c index c6b87193c..1cac121b7 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -60,7 +60,7 @@ static int lib_concat(lua_State *L) return luaL_error(L, LUA_QL("tostring") " must return a string to " LUA_QL("__add")); r = Z_Realloc(r, rl+sl, PU_STATIC, NULL); - M_Memcpy(r+rl, s, sl); + memcpy(r+rl, s, sl); rl += sl; lua_pop(L, 1); /* pop result */ } diff --git a/src/m_fixed.c b/src/m_fixed.c index c1bb0cf05..d7aa13254 100644 --- a/src/m_fixed.c +++ b/src/m_fixed.c @@ -101,7 +101,7 @@ vector2_t *FV2_UnLoad(vector2_t *vec, fixed_t *x, fixed_t *y) vector2_t *FV2_Copy(vector2_t *a_o, const vector2_t *a_i) { - return M_Memcpy(a_o, a_i, sizeof(vector2_t)); + return memcpy(a_o, a_i, sizeof(vector2_t)); } vector2_t *FV2_AddEx(const vector2_t *a_i, const vector2_t *a_c, vector2_t *a_o) @@ -250,7 +250,7 @@ vector3_t *FV3_UnLoad(vector3_t *vec, fixed_t *x, fixed_t *y, fixed_t *z) vector3_t *FV3_Copy(vector3_t *a_o, const vector3_t *a_i) { - return M_Memcpy(a_o, a_i, sizeof(vector3_t)); + return memcpy(a_o, a_i, sizeof(vector3_t)); } vector3_t *FV3_AddEx(const vector3_t *a_i, const vector3_t *a_c, vector3_t *a_o) @@ -813,7 +813,7 @@ void FM_MultMatrix(matrix_t *dest, const matrix_t *multme) R(i, j) = FixedMul(D(i, 0), M(0, j)) + FixedMul(D(i, 1), M(1, j)) + FixedMul(D(i, 2), M(2, j)) + FixedMul(D(i, 3), M(3, j)); } - M_Memcpy(dest, &result, sizeof(matrix_t)); + memcpy(dest, &result, sizeof(matrix_t)); #undef R #undef D diff --git a/src/m_misc.c b/src/m_misc.c index 58e4b191e..655a28a24 100644 --- a/src/m_misc.c +++ b/src/m_misc.c @@ -1686,7 +1686,7 @@ char *M_GetToken(const char *inputString) // Assign the memory. Don't forget an extra byte for the end of the string! texturesToken = (char *)Z_Malloc((texturesTokenLength+1)*sizeof(char),PU_STATIC,NULL); // Copy the string. - M_Memcpy(texturesToken, stringToUse+startPos, (size_t)texturesTokenLength); + memcpy(texturesToken, stringToUse+startPos, (size_t)texturesTokenLength); // Make the final character NUL. texturesToken[texturesTokenLength] = '\0'; return texturesToken; diff --git a/src/p_enemy.c b/src/p_enemy.c index 6fd3f3844..a487eb328 100644 --- a/src/p_enemy.c +++ b/src/p_enemy.c @@ -945,9 +945,9 @@ void A_PointyThink(void *thing) v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(FixedAngle(actor->lastlook+i))); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(actor->angle+ANGLE_180)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); P_UnsetThingPosition(ball); ball->x = actor->x + v[0]; @@ -4929,9 +4929,9 @@ void A_MaceRotate(void *thing) // Calculate the angle matrixes for the link. res = VectorMatrixMultiply(v, *RotateXMatrix(FixedAngle(actor->threshold))); - M_Memcpy(&v, res, sizeof(v)); + memcpy(&v, res, sizeof(v)); res = VectorMatrixMultiply(v, *RotateZMatrix(actor->target->health << ANGLETOFINESHIFT)); - M_Memcpy(&v, res, sizeof(v)); + memcpy(&v, res, sizeof(v)); } // Rotating Chain. else @@ -4950,9 +4950,9 @@ void A_MaceRotate(void *thing) // Calculate the angle matrixes for the link. res = VectorMatrixMultiply(v, *RotateXMatrix(actor->target->threshold << ANGLETOFINESHIFT)); - M_Memcpy(&v, res, sizeof(v)); + memcpy(&v, res, sizeof(v)); res = VectorMatrixMultiply(v, *RotateZMatrix(actor->target->health << ANGLETOFINESHIFT)); - M_Memcpy(&v, res, sizeof(v)); + memcpy(&v, res, sizeof(v)); } // Add on the appropriate distances to the actor's co-ordinates. diff --git a/src/p_mobj.c b/src/p_mobj.c index 2bd58e8cf..86261a644 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -5459,9 +5459,9 @@ static void P_MoveHoop(mobj_t *mobj) v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(FixedAngle(mobj->target->movedir*FRACUNIT))); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(FixedAngle(mobj->target->movecount*FRACUNIT))); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); finalx = x + v[0]; finaly = y + v[1]; @@ -5527,9 +5527,9 @@ void P_SpawnHoopOfSomething(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(rotangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(closestangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); finalx = x + v[0]; finaly = y + v[1]; @@ -5566,9 +5566,9 @@ void P_SpawnParaloop(fixed_t x, fixed_t y, fixed_t z, fixed_t radius, INT32 numb v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(rotangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(closestangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); finalx = x + v[0]; finaly = y + v[1]; @@ -11815,9 +11815,9 @@ static void P_SpawnNiGHTSHoop(fixed_t x, fixed_t y, fixed_t z, fixed_t hoopsize, v[3] = FRACUNIT; res = VectorMatrixMultiply(v, *RotateXMatrix(FixedAngle(spewangle))); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); res = VectorMatrixMultiply(v, *RotateZMatrix(closestangle)); - M_Memcpy(&v, res, sizeof (v)); + memcpy(&v, res, sizeof (v)); mobj = P_SpawnMobj(x + v[0], y + v[1], z + v[2], type); diff --git a/src/p_setup.c b/src/p_setup.c index 73445b6b3..f331b9dee 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -806,7 +806,7 @@ static void P_LoadSectors(UINT8 *data) skyflatnum = P_AddLevelFlat(SKYFLATNAME, foundflats); // copy table for global usage - levelflats = M_Memcpy(Z_Calloc(numlevelflats * sizeof (*levelflats), PU_LEVEL, NULL), foundflats, numlevelflats * sizeof (levelflat_t)); + levelflats = memcpy(Z_Calloc(numlevelflats * sizeof (*levelflats), PU_LEVEL, NULL), foundflats, numlevelflats * sizeof (levelflat_t)); free(foundflats); // search for animated flats and set up @@ -1177,10 +1177,10 @@ static void P_LoadLineDefs2(void) len += strlen(sides[ld->sidenum[1]].text); ld->text = Z_Malloc(len, PU_LEVEL, NULL); - M_Memcpy(ld->text, sides[ld->sidenum[0]].text, strlen(sides[ld->sidenum[0]].text)+1); + memcpy(ld->text, sides[ld->sidenum[0]].text, strlen(sides[ld->sidenum[0]].text)+1); if (ld->sidenum[1] != 0xffff && sides[ld->sidenum[1]].text) - M_Memcpy(ld->text+strlen(ld->text)+1, sides[ld->sidenum[1]].text, strlen(sides[ld->sidenum[1]].text)+1); + memcpy(ld->text+strlen(ld->text)+1, sides[ld->sidenum[1]].text, strlen(sides[ld->sidenum[1]].text)+1); } break; @@ -1309,14 +1309,14 @@ static void P_LoadSideChangeMusic(boolean firstside, mapsidedef_t *msd, side_t * if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') { - M_Memcpy(process,msd->bottomtexture,8); + memcpy(process,msd->bottomtexture,8); process[8] = '\0'; sd->bottomtexture = get_number(process); } if (!(msd->midtexture[0] == '-' && msd->midtexture[1] == '\0') || msd->midtexture[1] != '\0') { - M_Memcpy(process,msd->midtexture,8); + memcpy(process,msd->midtexture,8); process[8] = '\0'; sd->midtexture = get_number(process); } @@ -1326,15 +1326,15 @@ static void P_LoadSideChangeMusic(boolean firstside, mapsidedef_t *msd, side_t * if (firstside || msd->toptexture[0] != '-' || msd->toptexture[1] != '\0') { - M_Memcpy(process,msd->toptexture,8); + memcpy(process,msd->toptexture,8); process[8] = '\0'; // If they type in O_ or D_ and their music name, just shrug, // then copy the rest instead. if ((process[0] == 'O' || process[0] == 'D') && process[7]) - M_Memcpy(sd->text, process+2, 6); + memcpy(sd->text, process+2, 6); else // Assume it's a proper music name. - M_Memcpy(sd->text, process, 6); + memcpy(sd->text, process, 6); sd->text[6] = 0; } else @@ -1382,7 +1382,7 @@ static void P_LoadSidedefs(void *data) if (msd->toptexture[0] != '-' || msd->toptexture[1] != '\0') { char process[8+1]; - M_Memcpy(process,msd->toptexture,8); + memcpy(process,msd->toptexture,8); process[8] = '\0'; sd->toptexture = get_number(process); } @@ -1401,11 +1401,11 @@ static void P_LoadSidedefs(void *data) if (msd->toptexture[0] == '-' && msd->toptexture[1] == '\0') break; else - M_Memcpy(process,msd->toptexture,8); + memcpy(process,msd->toptexture,8); if (msd->midtexture[0] != '-' || msd->midtexture[1] != '\0') - M_Memcpy(process+strlen(process), msd->midtexture, 8); + memcpy(process+strlen(process), msd->midtexture, 8); if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') - M_Memcpy(process+strlen(process), msd->bottomtexture, 8); + memcpy(process+strlen(process), msd->bottomtexture, 8); sd->toptexture = get_number(process); break; @@ -1418,13 +1418,13 @@ static void P_LoadSidedefs(void *data) if (msd->toptexture[0] == '-' && msd->toptexture[1] == '\0') break; else - M_Memcpy(process,msd->toptexture,8); + memcpy(process,msd->toptexture,8); if (msd->midtexture[0] != '-' || msd->midtexture[1] != '\0') - M_Memcpy(process+strlen(process), msd->midtexture, 8); + memcpy(process+strlen(process), msd->midtexture, 8); if (msd->bottomtexture[0] != '-' || msd->bottomtexture[1] != '\0') - M_Memcpy(process+strlen(process), msd->bottomtexture, 8); + memcpy(process+strlen(process), msd->bottomtexture, 8); sd->text = Z_Malloc(strlen(process)+1, PU_LEVEL, NULL); - M_Memcpy(sd->text, process, strlen(process)+1); + memcpy(sd->text, process, strlen(process)+1); break; } @@ -1887,7 +1887,7 @@ static void P_LoadReject(UINT8 *data, size_t count) else { rejectmatrix = Z_Malloc(count, PU_LEVEL, NULL); // allocate memory for the reject matrix - M_Memcpy(rejectmatrix, data, count); // copy the data into it + memcpy(rejectmatrix, data, count); // copy the data into it } } @@ -2201,7 +2201,7 @@ static void P_MakeMapMD5(virtres_t *virt, void *dest) for (i = 0; i < 16; i++) resmd5[i] = (linemd5[i] + sectormd5[i] + thingmd5[i] + sidedefmd5[i]) & 0xFF; - M_Memcpy(dest, &resmd5, 16); + memcpy(dest, &resmd5, 16); } static void P_LoadMapFromFile(void) diff --git a/src/p_spec.c b/src/p_spec.c index e08030e9e..c7a6dc15f 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -252,10 +252,10 @@ void P_InitPicAnims(void) // Populate the new array for (currentPos = animatedLump; *currentPos != UINT8_MAX; i++, currentPos+=23) { - M_Memcpy(&(animdefs[i].istexture), currentPos, 1); // istexture, 1 byte - M_Memcpy(animdefs[i].endname, (currentPos + 1), 9); // endname, 9 bytes - M_Memcpy(animdefs[i].startname, (currentPos + 10), 9); // startname, 9 bytes - M_Memcpy(&(animdefs[i].speed), (currentPos + 19), 4); // speed, 4 bytes + memcpy(&(animdefs[i].istexture), currentPos, 1); // istexture, 1 byte + memcpy(animdefs[i].endname, (currentPos + 1), 9); // endname, 9 bytes + memcpy(animdefs[i].startname, (currentPos + 10), 9); // startname, 9 bytes + memcpy(&(animdefs[i].speed), (currentPos + 19), 4); // speed, 4 bytes } Z_Free(animatedLump); diff --git a/src/r_data.c b/src/r_data.c index 3077326ad..4dc6653ea 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -269,7 +269,7 @@ static inline void R_DrawColumnInCache(column_t *patch, UINT8 *cache, texpatch_t count = cacheheight - position; if (count > 0) - M_Memcpy(cache + position, source, count); + memcpy(cache + position, source, count); patch = (column_t *)((UINT8 *)patch + patch->length + 4); } @@ -412,7 +412,7 @@ UINT8 *R_GenerateTexture(size_t texnum) texture->holes = true; blocksize = lumplength; block = Z_Calloc(blocksize, PU_LEVEL, &texturecache[texnum]); // will change tag at end of this function - M_Memcpy(block, realpatch, blocksize); + memcpy(block, realpatch, blocksize); texturememory += blocksize; // use the patch's column lookup @@ -621,7 +621,7 @@ Rloadtextures (INT32 i, INT32 w) texture = textures[i] = Z_Calloc(sizeof(texture_t) + sizeof(texpatch_t), PU_STATIC, NULL); // Set texture properties. - M_Memcpy(texture->name, W_CheckNameForNumPwad(wadnum, lumpnum), sizeof(texture->name)); + memcpy(texture->name, W_CheckNameForNumPwad(wadnum, lumpnum), sizeof(texture->name)); texture->hash = quickncasehash(texture->name, 8); texture->width = SHORT(patchlump.width); @@ -854,7 +854,7 @@ static texpatch_t *R_ParsePatch(boolean actuallyLoadPatch) Z_Free(patchName); } patchName = (char *)Z_Malloc((texturesTokenLength+1)*sizeof(char),PU_STATIC,NULL); - M_Memcpy(patchName,texturesToken,texturesTokenLength*sizeof(char)); + memcpy(patchName,texturesToken,texturesTokenLength*sizeof(char)); patchName[texturesTokenLength] = '\0'; } @@ -985,7 +985,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) else { memset(&newTextureName, 0, 9); - M_Memcpy(newTextureName, texturesToken, texturesTokenLength); + memcpy(newTextureName, texturesToken, texturesTokenLength); // ^^ we've confirmed that the token is <= 8 characters so it will never overflow a 9 byte char buffer strupr(newTextureName); // Just do this now so we don't have to worry about it } @@ -1077,7 +1077,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) { // Allocate memory for a zero-patch texture. Obviously, we'll be adding patches momentarily. resultTexture = (texture_t *)Z_Calloc(sizeof(texture_t), PU_STATIC, NULL); - M_Memcpy(resultTexture->name, newTextureName, 8); + memcpy(resultTexture->name, newTextureName, 8); resultTexture->hash = quickncasehash(newTextureName, 8); resultTexture->width = newTextureWidth; resultTexture->height = newTextureHeight; @@ -1104,7 +1104,7 @@ static texture_t *R_ParseTexture(boolean actuallyLoadTexture) // Make room for the new patch resultTexture = Z_Realloc(resultTexture, sizeof(texture_t) + (resultTexture->patchcount+1)*sizeof(texpatch_t), PU_STATIC, NULL); // Populate the uninitialized values in the new patch entry of our array - M_Memcpy(&resultTexture->patches[resultTexture->patchcount], newPatch, sizeof(texpatch_t)); + memcpy(&resultTexture->patches[resultTexture->patchcount], newPatch, sizeof(texpatch_t)); // Account for the new number of patches in the texture resultTexture->patchcount++; // Then free up the memory assigned to R_ParsePatch, as it's unneeded now diff --git a/src/r_draw.cpp b/src/r_draw.cpp index 39f8918bb..a1bbbbc96 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -655,7 +655,7 @@ void R_VideoErase(size_t ofs, INT32 count) // is not optimal, e.g. byte by byte on // a 32bit CPU, as GNU GCC/Linux libc did // at one point. - M_Memcpy(vid.screens[0] + ofs, vid.screens[1] + ofs, count); + memcpy(vid.screens[0] + ofs, vid.screens[1] + ofs, count); } // ========================================================================== diff --git a/src/r_patch.cpp b/src/r_patch.cpp index 7510520dd..515f5ea38 100644 --- a/src/r_patch.cpp +++ b/src/r_patch.cpp @@ -147,7 +147,7 @@ static void R_ParseSpriteInfo(boolean spr2) else { memset(&newSpriteName, 0, 5); - M_Memcpy(newSpriteName, sprinfoToken, sprinfoTokenLength); + memcpy(newSpriteName, sprinfoToken, sprinfoTokenLength); // ^^ we've confirmed that the token is == 4 characters so it will never overflow a 5 byte char buffer strupr(newSpriteName); // Just do this now so we don't have to worry about it } @@ -211,7 +211,7 @@ static void R_ParseSpriteInfo(boolean spr2) // copy skin name yada yada sprinfoTokenLength = strlen(sprinfoToken); skinName = (char *)Z_Malloc((sprinfoTokenLength+1)*sizeof(char),PU_STATIC,NULL); - M_Memcpy(skinName,sprinfoToken,sprinfoTokenLength*sizeof(char)); + memcpy(skinName,sprinfoToken,sprinfoTokenLength*sizeof(char)); skinName[sprinfoTokenLength] = '\0'; strlwr(skinName); Z_Free(sprinfoToken); @@ -240,11 +240,11 @@ static void R_ParseSpriteInfo(boolean spr2) skin = &localskins[allskins[skinnum].localnum]; else skin = &skins[allskins[skinnum].localnum]; - M_Memcpy(&skin->sprinfo, info, sizeof(spriteinfo_t)); + memcpy(&skin->sprinfo, info, sizeof(spriteinfo_t)); } } else - M_Memcpy(&spriteinfo[sprnum], info, sizeof(spriteinfo_t)); + memcpy(&spriteinfo[sprnum], info, sizeof(spriteinfo_t)); } else { @@ -371,7 +371,7 @@ patch_t *Patch_Create(softwarepatch_t *source, size_t srcsize, void *dest) I_Error("Patch_Create: no column data!"); patch->columns = static_cast(Z_Calloc(colsize, PU_PATCH_DATA, NULL)); - M_Memcpy(patch->columns, ((UINT8 *)source + LONG(source->columnofs[0])), colsize); + memcpy(patch->columns, ((UINT8 *)source + LONG(source->columnofs[0])), colsize); } return patch; diff --git a/src/r_patchrotation.cpp b/src/r_patchrotation.cpp index ebf8960e6..5d4b5478c 100644 --- a/src/r_patchrotation.cpp +++ b/src/r_patchrotation.cpp @@ -241,7 +241,7 @@ void RotatedPatch_DoRotation(rotsprite_t *rotsprite, patch_t *patch, INT32 angle while (dy--) { - M_Memcpy(dest, src, width * sizeof(UINT16)); + memcpy(dest, src, width * sizeof(UINT16)); dest += width; src += newwidth; } diff --git a/src/r_segs.cpp b/src/r_segs.cpp index 121920a69..c6cb63bf5 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -3003,14 +3003,14 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (((ds_p->silhouette & SIL_TOP) || maskedtexture) && !ds_p->sprtopclip) { - M_Memcpy(lastopening, ceilingclip + start, 2*(rw_stopx - start)); + memcpy(lastopening, ceilingclip + start, 2*(rw_stopx - start)); ds_p->sprtopclip = lastopening - start; lastopening += rw_stopx - start; } if (((ds_p->silhouette & SIL_BOTTOM) || maskedtexture) && !ds_p->sprbottomclip) { - M_Memcpy(lastopening, floorclip + start, 2*(rw_stopx - start)); + memcpy(lastopening, floorclip + start, 2*(rw_stopx - start)); ds_p->sprbottomclip = lastopening - start; lastopening += rw_stopx - start; } diff --git a/src/r_skins.c b/src/r_skins.c index 53765e269..8a08da7b2 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -520,7 +520,7 @@ void R_AddSkins(UINT16 wadnum, boolean local) buf2 = malloc(size+1); if (!buf2) I_Error("R_AddSkins: No more free memory\n"); - M_Memcpy(buf2,buf,size); + memcpy(buf2,buf,size); buf2[size] = '\0'; // set defaults diff --git a/src/r_things.cpp b/src/r_things.cpp index 75c333cd4..03eab22c8 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -267,7 +267,7 @@ boolean R_AddSingleSpriteDef(const char *sprname, spritedef_t *spritedef, UINT16 if (spritedef->numframes) // (then spriteframes is not null) { // copy the already defined sprite frames - M_Memcpy(sprtemp, spritedef->spriteframes, + memcpy(sprtemp, spritedef->spriteframes, spritedef->numframes * sizeof (spriteframe_t)); maxframe = spritedef->numframes - 1; } @@ -403,7 +403,7 @@ boolean R_AddSingleSpriteDef(const char *sprname, spritedef_t *spritedef, UINT16 spritedef->spriteframes = static_cast(Z_Malloc(maxframe * sizeof (*spritedef->spriteframes), PU_STATIC, NULL)); spritedef->numframes = maxframe; - M_Memcpy(spritedef->spriteframes, sprtemp, maxframe*sizeof (spriteframe_t)); + memcpy(spritedef->spriteframes, sprtemp, maxframe*sizeof (spriteframe_t)); return true; } @@ -1019,7 +1019,7 @@ static void R_SplitSprite(vissprite_t *sprite) INT16 *cliptop = newsprite->cliptop; INT16 *clipbot = newsprite->clipbot; - M_Memcpy(newsprite, sprite, sizeof (vissprite_t)); + memcpy(newsprite, sprite, sizeof (vissprite_t)); newsprite->cliptop = cliptop; newsprite->clipbot = clipbot; diff --git a/src/s_sound.c b/src/s_sound.c index 1e3f8bf7a..52b01be35 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -1409,7 +1409,7 @@ void S_LoadMusicDefs(UINT16 wadnum) musdeftext = malloc(size+1); if (!musdeftext) I_Error("S_LoadMusicDefs: No more free memory for the parser\n"); - M_Memcpy(musdeftext, lump, size); + memcpy(musdeftext, lump, size); musdeftext[size] = '\0'; // Find music def diff --git a/src/sdl/i_net.c b/src/sdl/i_net.c index 9fcc1fd38..000890332 100644 --- a/src/sdl/i_net.c +++ b/src/sdl/i_net.c @@ -107,7 +107,7 @@ static void NET_Get(void) { size_t i; newnode++; - M_Memcpy(&clientaddress[newnode], &mypacket.address, sizeof (IPaddress)); + memcpy(&clientaddress[newnode], &mypacket.address, sizeof (IPaddress)); DEBFILE(va("New node detected: node:%d address:%s\n", newnode, NET_GetNodeAddress(newnode))); doomcom->remotenode = newnode; // good packet from a game player @@ -257,7 +257,7 @@ static SINT8 NET_NetMakeNodewPort(const char *hostname, const char *port) return newnode; } newnode++; - M_Memcpy(&clientaddress[newnode],&hostnameIP,sizeof (IPaddress)); + memcpy(&clientaddress[newnode],&hostnameIP,sizeof (IPaddress)); return (SINT8)newnode; } @@ -303,7 +303,7 @@ static boolean NET_Ban(INT32 node) if (numbans == MAXBANS) return false; - M_Memcpy(&banned[numbans], &clientaddress[node], sizeof (IPaddress)); + memcpy(&banned[numbans], &clientaddress[node], sizeof (IPaddress)); banned[numbans].port = 0; numbans++; return true; diff --git a/src/sdl/sdl_sound.c b/src/sdl/sdl_sound.c index c986b9b54..ab4bcd796 100644 --- a/src/sdl/sdl_sound.c +++ b/src/sdl/sdl_sound.c @@ -244,7 +244,7 @@ static void *getsfx(lumpnum_t sfxlump, size_t *len) sfxcvt.len = (INT32)size-8; //Alam: Chop off the header sfxcvt.buf = malloc(sfxcvt.len * sfxcvt.len_mult); //Alam: make room - if (sfxcvt.buf) M_Memcpy(sfxcvt.buf, &(sfx->data), sfxcvt.len); //Alam: copy the sfx sample + if (sfxcvt.buf) memcpy(sfxcvt.buf, &(sfx->data), sfxcvt.len); //Alam: copy the sfx sample if (sfxcvt.buf && SDL_ConvertAudio(&sfxcvt) == 0) //Alam: let convert it! { @@ -255,9 +255,9 @@ static void *getsfx(lumpnum_t sfxlump, size_t *len) paddedsfx = (dssfx_t *) Z_Malloc(size, PU_SOUND, NULL); // Now copy and pad. - M_Memcpy(paddedsfx->data, sfxcvt.buf, sfxcvt.len_cvt); + memcpy(paddedsfx->data, sfxcvt.buf, sfxcvt.len_cvt); free(sfxcvt.buf); - M_Memcpy(paddedsfx,sfx,8); + memcpy(paddedsfx,sfx,8); paddedsfx->samplerate = SHORT(csr); // new freq } else //Alam: the convert failed, not needed or I couldn't malloc the buf @@ -266,7 +266,7 @@ static void *getsfx(lumpnum_t sfxlump, size_t *len) *len = size - 8; // Allocate from zone memory then copy and pad - paddedsfx = (dssfx_t *)M_Memcpy(Z_Malloc(size, PU_SOUND, NULL), sfx, size); + paddedsfx = (dssfx_t *)memcpy(Z_Malloc(size, PU_SOUND, NULL), sfx, size); } } else @@ -276,7 +276,7 @@ static void *getsfx(lumpnum_t sfxlump, size_t *len) *len = size - 8; // Allocate from zone memory then copy and pad - paddedsfx = (dssfx_t *)M_Memcpy(Z_Malloc(size, PU_SOUND, NULL), sfx, size); + paddedsfx = (dssfx_t *)memcpy(Z_Malloc(size, PU_SOUND, NULL), sfx, size); } // Remove the cached lump. diff --git a/src/v_video.c b/src/v_video.c index 3b9880942..c26d8c9bd 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -626,13 +626,13 @@ void VID_BlitLinearScreen(const UINT8 *restrict srcptr, UINT8 *restrict destptr, i -= 16; } #endif - M_Memcpy(destptr, srcptr, i); + memcpy(destptr, srcptr, i); } else { while (height--) { - M_Memcpy(destptr, srcptr, width); + memcpy(destptr, srcptr, width); destptr += destrowbytes; srcptr += srcrowbytes; @@ -1193,7 +1193,7 @@ void V_DrawBlock(INT32 x, INT32 y, INT32 scrn, INT32 width, INT32 height, const while (height--) { - M_Memcpy(dest, src, width); + memcpy(dest, src, width); src += width; dest += vid.width; @@ -3647,7 +3647,7 @@ void V_DoPostProcessor(INT32 view, INT32 param) if (sine < 0) { - M_Memcpy(&tmpscr[(y*vid.width)+xoffset+newpix], &srcscr[(y*vid.width)+xoffset], viewwidth-newpix); + memcpy(&tmpscr[(y*vid.width)+xoffset+newpix], &srcscr[(y*vid.width)+xoffset], viewwidth-newpix); // Cleanup edge while (newpix) @@ -3658,7 +3658,7 @@ void V_DoPostProcessor(INT32 view, INT32 param) } else { - M_Memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); + memcpy(&tmpscr[(y*vid.width)+xoffset+0], &srcscr[(y*vid.width)+xoffset+sine], viewwidth-newpix); // Cleanup edge while (newpix) @@ -3718,10 +3718,10 @@ void V_DoPostProcessor(INT32 view, INT32 param) { // Shift this row of pixels to the right by 2 tmpscr[(y*vid.width)+xoffset] = srcscr[(y*vid.width)+xoffset]; - M_Memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset+vid.dup], viewwidth-vid.dup); } else - M_Memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); + memcpy(&tmpscr[(y*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); heatindex[view] %= viewheight; } @@ -3758,7 +3758,7 @@ void V_DoPostProcessor(INT32 view, INT32 param) INT32 y, y2; for (y = yoffset, y2 = yoffset+viewheight - 1; y < yoffset+viewheight; y++, y2--) - M_Memcpy(&tmpscr[(y2*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); + memcpy(&tmpscr[(y2*vid.width)+xoffset], &srcscr[(y*vid.width)+xoffset], viewwidth); UINT8 *tmp = tmpscr; tmpscr = srcscr; diff --git a/src/w_wad.c b/src/w_wad.c index 96fe56303..b55d0e98f 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -906,7 +906,7 @@ UINT16 W_InitFile(const char *filename, boolean local, boolean startup) wadfile->endfolders = M_AATreeAlloc(AATREE_STRING); // already generated, just copy it over - M_Memcpy(&wadfile->md5sum, &md5sum, 16); + memcpy(&wadfile->md5sum, &md5sum, 16); // // set up caching @@ -1637,7 +1637,7 @@ size_t W_ReadLumpHeaderPwad(UINT16 wad, UINT16 lump, void *dest, size_t size, si if (!decData) // Did we get no data at all? return 0; - M_Memcpy(dest, decData + offset, size); + memcpy(dest, decData + offset, size); Z_Free(rawData); Z_Free(decData); #ifdef NO_PNG_LUMPS diff --git a/src/z_zone.cpp b/src/z_zone.cpp index 8ed23e4a7..549696bd7 100644 --- a/src/z_zone.cpp +++ b/src/z_zone.cpp @@ -35,7 +35,6 @@ #include "i_system.h" // I_GetFreeMem #include "i_video.h" // rendermode #include "z_zone.h" -#include "m_misc.h" // M_Memcpy #include "lua_script.h" #ifdef HWRENDER @@ -383,7 +382,7 @@ void *Z_Realloc(void *ptr, size_t size, INT32 tag, void *user) else copysize = block->size; - M_Memcpy(rez, ptr, copysize); + memcpy(rez, ptr, copysize); #ifdef ZDEBUG Z_Free2(ptr, file, line); -- 2.54.0 From 29b4f78b64414c022385da40af81e912d4715ae4 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 18:44:26 +0100 Subject: [PATCH 094/116] lib_concat: fix zero lenght string case continue the loop, not return, it might just be an empty line, so returning might break some luas 0 lenght would make realloc allocate nothing at all, so just skip it --- src/lua_baselib.c | 77 ++++++++++++++++++++++++++--------------------- 1 file changed, 42 insertions(+), 35 deletions(-) diff --git a/src/lua_baselib.c b/src/lua_baselib.c index 1cac121b7..f64224a41 100644 --- a/src/lua_baselib.c +++ b/src/lua_baselib.c @@ -45,27 +45,33 @@ boolean luaL_checkboolean(lua_State *L, int narg) { // String concatination static int lib_concat(lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - int i; - char *r = NULL; - size_t rl = 0,sl; - lua_getglobal(L, "tostring"); - for (i=1; i<=n; i++) { - const char *s; - lua_pushvalue(L, -1); /* function to be called */ - lua_pushvalue(L, i); /* value to print */ - lua_call(L, 1, 1); - s = lua_tolstring(L, -1, &sl); /* get result */ - if (s == NULL) - return luaL_error(L, LUA_QL("tostring") " must return a string to " - LUA_QL("__add")); + int n = lua_gettop(L); /* number of arguments */ + int i; + char *r = NULL; + size_t rl = 0, sl; + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tolstring(L, -1, &sl); /* get result */ + + if (sl == 0) { + lua_pop(L, 1); /* pop result */ + continue; + } + + if (s == NULL) + return luaL_error(L, LUA_QL("tostring") " must return a string to " + LUA_QL("__add")); r = Z_Realloc(r, rl+sl, PU_STATIC, NULL); memcpy(r+rl, s, sl); rl += sl; - lua_pop(L, 1); /* pop result */ - } - lua_pushlstring(L, r, rl); - Z_Free(r); + lua_pop(L, 1); /* pop result */ + } + lua_pushlstring(L, r, rl); + Z_Free(r); return 1; } @@ -73,23 +79,24 @@ static int lib_concat(lua_State *L) // Copied from base Lua code static int lib_print(lua_State *L) { - int n = lua_gettop(L); /* number of arguments */ - int i; - //HUDSAFE - lua_getglobal(L, "tostring"); - for (i=1; i<=n; i++) { - const char *s; - lua_pushvalue(L, -1); /* function to be called */ - lua_pushvalue(L, i); /* value to print */ - lua_call(L, 1, 1); - s = lua_tostring(L, -1); /* get result */ - if (s == NULL) - return luaL_error(L, LUA_QL("tostring") " must return a string to " - LUA_QL("print")); - if (i>1) CONS_Printf("\n"); - CONS_Printf("%s", s); - lua_pop(L, 1); /* pop result */ - } + int n = lua_gettop(L); /* number of arguments */ + int i; + //HUDSAFE + lua_getglobal(L, "tostring"); + for (i=1; i<=n; i++) { + const char *s; + lua_pushvalue(L, -1); /* function to be called */ + lua_pushvalue(L, i); /* value to print */ + lua_call(L, 1, 1); + s = lua_tostring(L, -1); /* get result */ + + if (s == NULL) + return luaL_error(L, LUA_QL("tostring") " must return a string to " + LUA_QL("print")); + if (i>1) CONS_Printf("\n"); + CONS_Printf("%s", s); + lua_pop(L, 1); /* pop result */ + } CONS_Printf("\n"); return 0; } -- 2.54.0 From 33b62cba337a238660bb68fe5a7b2faa49f877d8 Mon Sep 17 00:00:00 2001 From: Indev Date: Thu, 6 Nov 2025 20:44:18 +0300 Subject: [PATCH 095/116] Push empty string instead of null if len == 0 in lua_pushlstring --- src/blua/lapi.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/blua/lapi.c b/src/blua/lapi.c index 73fbbf561..557896f43 100644 --- a/src/blua/lapi.c +++ b/src/blua/lapi.c @@ -434,7 +434,7 @@ LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) { lua_lock(L); luaC_checkGC(L); - setsvalue2s(L, L->top, luaS_newlstr(L, s, len)); + setsvalue2s(L, L->top, (len == 0) ? luaS_new(L, "") : luaS_newlstr(L, s, len)); api_incr_top(L); lua_unlock(L); } -- 2.54.0 From e2df018e3802b12541170701f95c2059db487695 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 19:00:48 +0100 Subject: [PATCH 096/116] simplify srb2::floattofixed my tired ass didnt think about just reusing shit kek ty indev <3 --- src/cxxutil.hpp | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/src/cxxutil.hpp b/src/cxxutil.hpp index 91c1a8641..98c9d9e5f 100644 --- a/src/cxxutil.hpp +++ b/src/cxxutil.hpp @@ -189,29 +189,7 @@ static inline int32_t floattofixed(FloatT val) static_assert(std::is_floating_point_v, "Input must be a floating-point type"); // fixed_t is just an int32_t, i dont wanna include doomtype here if it can be avoided - - if (std::fpclassify(val) == FP_NAN) - return 0; // if stuffs not a number we sure screwed up lmao - - // treat inifinity as "int min/max" - if (std::fpclassify(val) == FP_INFINITE) - { - // yes infinity can be signed kek - if (std::signbit(val)) - return std::numeric_limits::min(); // negative infinity, so return min - else - return std::numeric_limits::max(); - } - - const FloatT ret = (val * 65536.0); - - // make sure we fit into our targettype uwu - if (ret > static_cast(std::numeric_limits::max())) - return std::numeric_limits::max(); - else if (ret < static_cast(std::numeric_limits::min())) - return std::numeric_limits::min(); - - return static_cast(ret); + return floattoint(val * 65535.); } } // namespace srb2 -- 2.54.0 From 01a54e4d0bd2b7a529cfddb9fa759dadc94ef323 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 19:15:59 +0100 Subject: [PATCH 097/116] delete remaining M_Memcpy that were missed those werent there in lugstuff branch oops lel --- src/lzf.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lzf.c b/src/lzf.c index 97c74ff2b..549484b03 100644 --- a/src/lzf.c +++ b/src/lzf.c @@ -192,7 +192,7 @@ lzf_decompress (const void *const in_data, size_t in_len, #endif #if USE_MEMCPY - M_Memcpy (op, ip, ctrl); + memcpy(op, ip, ctrl); op += ctrl; ip += ctrl; #else @@ -435,7 +435,7 @@ lzf_compress (const void *const in_data,size_t in_len, *op++ = MAX_LIT - 1; #if USE_MEMCPY - M_Memcpy (op, ip - MAX_LIT, MAX_LIT); + memcpy(op, ip - MAX_LIT, MAX_LIT); op += MAX_LIT; lit = 0; #else -- 2.54.0 From 325338bfbf340690bfe6f498155f95466047836d Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 6 Nov 2025 20:33:43 +0100 Subject: [PATCH 098/116] sound precache: add option to keep sounds cached but not precache them ugh i suck so much at explaining this is the default now pretty much --- src/m_menudefs.c | 9 ++++++-- src/p_setup.c | 5 +++-- src/s_sound.c | 56 ++++++++++++++++++++++++++++++------------------ src/s_sound.h | 12 +++++++++-- src/sounds.c | 4 +++- 5 files changed, 58 insertions(+), 28 deletions(-) diff --git a/src/m_menudefs.c b/src/m_menudefs.c index 6633085bf..8ec8e2cd1 100644 --- a/src/m_menudefs.c +++ b/src/m_menudefs.c @@ -1153,8 +1153,10 @@ static menuitem_t OP_SoundAdvancedMenu[] = {IT_STRING | IT_CVAR, NULL, "Keep Map Music", &cv_keepmusic, 80}, {IT_STRING | IT_CVAR, NULL, "Skip Intro Music", &cv_skipintromusic, 85}, - {IT_STRING | IT_CVAR, NULL, "Audio Buffer Size", &cv_audbuffersize, 90}, - {IT_DISABLED, NULL, "", NULL, 100}, // dummy text + {IT_STRING | IT_CVAR, NULL, "Cache Sound", &cv_cachesound, 90}, + + {IT_STRING | IT_CVAR, NULL, "Audio Buffer Size", &cv_audbuffersize, 95}, + {IT_DISABLED, NULL, "", NULL, 105}, // dummy text }; static const char* OP_SoundAdvancedTooltips[] = @@ -1175,7 +1177,10 @@ static const char* OP_SoundAdvancedTooltips[] = "Should the Invulnerability music be on or off?", "Should music be kept when restarting the map?", "Should the Intro fanfare be skipped\nand map music be played on map start?", + "Controls Sound effects caching.\nKeep will retain previously played sound effects in cache." // man idk how to describe this in a non awful way lmao + "\nOn will preload all sound effects.\nEliminates sound-related lag and stutters but increases memory usage.", "Size of the Audio Buffer\nreducing it will result in less sound latency\nbut may cause issues such as crackling or distorted Sound.", + NULL, }; static menuitem_t OP_FocusOptionsMenu[] = diff --git a/src/p_setup.c b/src/p_setup.c index f331b9dee..9de109aae 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -2766,7 +2766,8 @@ boolean P_SetupLevel(boolean fromnetsave, boolean reloadinggamestate) // Make sure all sounds are stopped before Z_FreeTags. S_StopSounds(); - if (!S_PrecacheSound()) + // if we dont intend to cache our sound effects, wipe them + if (S_CacheSound() == SOUNDCACHE_OFF) S_ClearSfx(); // As oddly named as this is, this handles music only. @@ -3034,7 +3035,7 @@ static boolean P_CheckSoundReplacements(UINT16 wadnum, char *name, size_t i) I_FreeSfx(&S_sfx[j]); // Re-cache it - if (S_PrecacheSound()) + if (S_CacheSound() == SOUNDCACHE_PRECACHE) S_sfx[j].data = I_GetSfx(&S_sfx[j]); sreplaces++; diff --git a/src/s_sound.c b/src/s_sound.c index 52b01be35..7625a3f60 100644 --- a/src/s_sound.c +++ b/src/s_sound.c @@ -45,7 +45,7 @@ static void Command_ShowMusicCredit_f(void); static void GameSounds_OnChange(void); static void GameMusic_OnChange(void); -static void SoundPrecache_OnChange(void); +static void SoundCache_OnChange(void); static void BufferSize_OnChange(void); #ifdef HAVE_OPENMPT @@ -68,7 +68,8 @@ consvar_t cv_audbuffersize = {"audiobuffersize", "2048", CV_SAVE|CV_CALL, audbuf consvar_t stereoreverse = {"stereoreverse", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; // if true, all sounds are loaded at game startup -consvar_t precachesound = {"precachesound", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, SoundPrecache_OnChange, 0, NULL, NULL, 0, 0, NULL}; +static CV_PossibleValue_t cachesounds_cons_t[] = {{0, "Off"}, {1, "Keep"}, {2, "On"}, {0, NULL}}; +consvar_t cv_cachesound = {"cachesound", "1", CV_SAVE|CV_CALL|CV_NOINIT, cachesounds_cons_t, SoundCache_OnChange, 0, NULL, NULL, 0, 0, NULL}; // actual general (maximum) sound & music volume, saved into the config static CV_PossibleValue_t soundvolume_cons_t[] = {{0, "MIN"}, {31, "MAX"}, {0, NULL}}; @@ -274,7 +275,7 @@ void S_RegisterSoundStuff(void) } CV_RegisterVar(&stereoreverse); - CV_RegisterVar(&precachesound); + CV_RegisterVar(&cv_cachesound); #if defined(HAVE_SDL) && SOUND==SOUND_SDL CV_RegisterVar(&cv_samplerate); #endif @@ -362,9 +363,15 @@ boolean S_SoundDisabled(void) return (sound_disabled || (window_notinfocus && !cv_playsoundifunfocused.value)); } -boolean S_PrecacheSound(void) +int S_CacheSound(void) { - return (!sound_disabled && (M_CheckParm("-precachesound") || precachesound.value)); + if (sound_disabled) + return SOUNDCACHE_OFF; + + if (M_CheckParm("-precachesound")) + return SOUNDCACHE_PRECACHE; + + return cv_cachesound.value; } // Stop all sounds, load level info, THEN start sounds. @@ -1150,28 +1157,35 @@ void S_InitSfxChannels(INT32 sfxVolume) SetChannelsNum(); - // Note that sounds have not been cached (yet). - for (i = 1; i < NUMSFX; i++) - { - S_sfx[i].lumpnum = LUMPERROR; - } - // Precache sounds if requested - if (S_PrecacheSound()) + if (S_CacheSound() == SOUNDCACHE_PRECACHE) { // Initialize external data (all sounds) at start, keep static. CONS_Printf(M_GetText("Pre-caching sounds...")); - for (i = 1; i < sfx_freeslot0; i++) - if (S_sfx[i].name && !S_sfx[i].data) - S_sfx[i].data = I_GetSfx(&S_sfx[i]); + // NUMSFX is a big number, so merge the loops + for (i = 1; i < NUMSFX; i++) + { + S_sfx[i].lumpnum = LUMPERROR; - for (i = sfx_freeslot0; i < NUMSFX; i++) - if (S_sfx[i].priority && !S_sfx[i].data) - S_sfx[i].data = I_GetSfx(&S_sfx[i]); + if (S_sfx[i].data) + continue; + + if ((i < sfx_freeslot0 && S_sfx[i].name) || + (i >= sfx_freeslot0 && S_sfx[i].priority)) + S_sfx[i].data = I_GetSfx(&S_sfx[i]); + } CONS_Printf(M_GetText("...pre-cached all sound data\n")); } + else + { + // Note that sounds have not been cached (yet). + for (i = 1; i < NUMSFX; i++) + { + S_sfx[i].lumpnum = LUMPERROR; + } + } } /// ------------------------ @@ -2277,13 +2291,13 @@ static void GameSounds_OnChange(void) } } -static void SoundPrecache_OnChange(void) +static void SoundCache_OnChange(void) { - if (S_PrecacheSound()) + if (S_CacheSound() != SOUNDCACHE_OFF) { S_InitSfxChannels(cv_soundvolume.value); } - else if (!S_PrecacheSound()) + else { S_ClearSfx(); diff --git a/src/s_sound.h b/src/s_sound.h index 7aa218062..1fa895d03 100644 --- a/src/s_sound.h +++ b/src/s_sound.h @@ -75,9 +75,10 @@ extern consvar_t cv_skipintromusic; //extern consvar_t cv_ignoremusicchanges; extern boolean keepmapmusic; extern boolean skipintromus; + #define MUSICSTARTTIME (starttime + (TICRATE/2)) -extern consvar_t precachesound; +extern consvar_t cv_cachesound; typedef enum { @@ -148,11 +149,18 @@ void S_StopSound(void *origin); // Music Status // +enum +{ + SOUNDCACHE_OFF, + SOUNDCACHE_KEEP, + SOUNDCACHE_PRECACHE +}; + boolean S_MusicDisabled(void); boolean S_MusicPlaying(void); boolean S_MusicPaused(void); boolean S_MusicNotInFocus(void); -boolean S_PrecacheSound(void); +int S_CacheSound(void); musictype_t S_MusicType(void); const char *S_MusicName(void); boolean S_MusicInfo(char *mname, UINT16 *mflags, boolean *looping); diff --git a/src/sounds.c b/src/sounds.c index 02e02b08a..c1e2f83a7 100644 --- a/src/sounds.c +++ b/src/sounds.c @@ -1018,6 +1018,8 @@ sfxenum_t S_AddSoundFx(const char *name, boolean singular, INT32 flags, boolean else slot = sfx_freeslot0; + const int precache = S_CacheSound(); + for (i = slot; i < NUMSFX; i++) { if (!S_sfx[i].priority) @@ -1030,7 +1032,7 @@ sfxenum_t S_AddSoundFx(const char *name, boolean singular, INT32 flags, boolean S_sfx[i].length = 0; S_sfx[i].skinsound = -1; - if (S_PrecacheSound()) + if (precache == SOUNDCACHE_PRECACHE) S_sfx[i].data = I_GetSfx(&S_sfx[i]); else S_sfx[i].data = NULL; -- 2.54.0 From 237aeb78341488ca9fb4da7bac6c6fdcc4038c41 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 7 Nov 2025 21:26:55 +0100 Subject: [PATCH 099/116] use early returns for "I_Finish" stuff i like that more, less checks for stuff --- src/sdl/i_video.c | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 2ea66dbc2..ebb8d7685 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -1329,14 +1329,12 @@ void I_UpdateNoBlit(void) if (rendermode == render_opengl) { OglSdlFinishUpdate(cv_vidwait.value); + return; } - else + #endif - if (rendermode == render_soft) - { - SDL_RenderCopy(renderer, texture, NULL, NULL); - SDL_RenderPresent(renderer); - } + SDL_RenderCopy(renderer, texture, NULL, NULL); + SDL_RenderPresent(renderer); } exposevideo = SDL_FALSE; @@ -1371,7 +1369,15 @@ void I_FinishUpdate(void) ST_AskToJoinEnvelope(); #endif - if (rendermode == render_soft && vid.screens[0]) +#ifdef HWRENDER + if (rendermode == render_opengl) + { + OglSdlFinishUpdate(cv_vidwait.value); + return; + } +#endif + + if (vid.screens[0]) { void *pixels; int pitch; @@ -1393,12 +1399,6 @@ void I_FinishUpdate(void) SDL_RenderCopy(renderer, texture, &src_rect, NULL); SDL_RenderPresent(renderer); } -#ifdef HWRENDER - else if (rendermode == render_opengl) - { - OglSdlFinishUpdate(cv_vidwait.value); - } -#endif exposevideo = SDL_FALSE; } @@ -1421,7 +1421,8 @@ void I_ReadScreen(UINT8 * restrict scr, INT32 scale) { if (rendermode != render_soft) I_Error("I_ReadScreen: called while in non-software mode"); - else if (scale == 1) + + if (scale == 1) VID_BlitLinearScreen(vid.screens[0], scr, vid.width, vid.height, vid.width, vid.width); else { @@ -1596,8 +1597,9 @@ static SDL_bool Impl_CreateContext(void) } SDL_GL_MakeCurrent(window, sdlglcontext); + + return SDL_TRUE; } - else #endif if (rendermode == render_soft) { @@ -1637,9 +1639,11 @@ static SDL_bool Impl_CreateContext(void) } SDL_RenderSetLogicalSize(renderer, BASEVIDWIDTH, BASEVIDHEIGHT); + + return SDL_TRUE; } - return SDL_TRUE; + return SDL_FALSE; } static SDL_bool Impl_CreateWindow(SDL_bool fullscreen) -- 2.54.0 From b421893646145c6b137f58631673b4a082d833f7 Mon Sep 17 00:00:00 2001 From: Alug Date: Fri, 7 Nov 2025 21:28:28 +0100 Subject: [PATCH 100/116] call NetKeepAlive during ogl precache should prevent timeouts on slower systems (*cough* *cough* windoze *cough*) hopefully thx neppy for the idea! --- src/hardware/hw_cache.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index ccd6980f3..b368fae6c 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -615,6 +615,9 @@ static void HWR_PrecacheLevelFlats(void) // go through all sectors to determine if it should be remapped for encore for (i = 0; i < numsectors; i++) { + // prevent timeouts + NetKeepAlive(); + sector_t *sec = §ors[i]; // gotta check sector floor and ceiling @@ -646,6 +649,9 @@ static void HWR_PrecacheLevelFlats(void) // just load every flat in the level for (i = 0; i < numlevelflats; i++) { + // prevent timeouts + NetKeepAlive(); + const levelflat_t *levelflat = &levelflats[i]; lump = levelflat->lumpnum; @@ -682,6 +688,9 @@ static void HWR_PrecacheLevelTextures(void) for (i = 0; i < numlines; i++) { + // prevent timeouts + NetKeepAlive(); + const line_t *line = &lines[i]; #ifdef GLENCORE const int noencoremap = ((encoremap && (line->flags & ML_TFERLINE)) ? 2 : 1); @@ -775,6 +784,9 @@ static void HWR_PrecacheLevelTextures(void) for (i = 0; i < numsprites; i++) { + // prevent timeouts + NetKeepAlive(); + if (!spritepresent[i]) continue; -- 2.54.0 From 54f5b5ebfbef2cbe5a3276af730140663f1a46ac Mon Sep 17 00:00:00 2001 From: Alug Date: Sat, 8 Nov 2025 12:30:45 +0100 Subject: [PATCH 101/116] enable software cyan pixel "cutting" for flats by default --- src/r_main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/r_main.cpp b/src/r_main.cpp index 339e34548..b6d0e7f0f 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -187,7 +187,7 @@ consvar_t cv_shadowoffs = {"offsetshadows", "Off", CV_SAVE, CV_OnOff, NULL, consvar_t cv_skybox = {"skybox", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_ffloorclip = {"r_ffloorclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_spriteclip = {"r_spriteclip", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; -consvar_t cv_softcyancut = {"softwarecyancut", "Off", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; +consvar_t cv_softcyancut = {"softwarecyancut", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_translucency = {"translucency", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_drawdist = {"drawdist", "Infinite", CV_SAVE, drawdist_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_drawdist_precip = {"drawdist_precip", "1024", CV_SAVE|CV_CALL|CV_NOINIT, drawdist_precip_cons_t, Precipstuff_OnChange, 0, NULL, NULL, 0, 0, NULL}; -- 2.54.0 From 87e0b55f01a92c7dd178510c31a108076d826499 Mon Sep 17 00:00:00 2001 From: Alug Date: Sun, 9 Nov 2025 18:51:58 +0100 Subject: [PATCH 102/116] fix windowmoved never resetting --- src/sdl/i_video.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index ebb8d7685..787ce1b07 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -523,6 +523,7 @@ static void Impl_HandleWindowEvent(SDL_WindowEvent evt) #ifdef USE_FBO_OGL I_DownSample(); #endif + windowmoved = SDL_FALSE; } if (mousefocus && kbfocus) -- 2.54.0 From c977c4fc45ddcd9cc9cf41d2f8fce61afc606a02 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 14:19:02 +0100 Subject: [PATCH 103/116] initialize most of our global variables just to be safe, not really trusting the game at this point, maybe this helps with some obscure bugs or smth lel --- src/d_clisrv.c | 39 +++++---- src/d_main.c | 72 +++------------- src/d_net.c | 6 +- src/d_netfil.c | 8 +- src/g_demo.c | 6 +- src/g_game.c | 177 +++++++++++++++++++-------------------- src/hardware/hw_clip.c | 13 ++- src/hardware/hw_defs.h | 2 +- src/hardware/hw_main.cpp | 16 ++-- src/hardware/hw_md2.c | 7 +- src/hardware/hw_portal.c | 4 +- src/p_enemy.c | 4 +- src/p_map.c | 26 +++--- src/p_mobj.c | 2 +- src/p_saveg.c | 2 +- src/p_setup.c | 56 ++++++------- src/p_spec.c | 4 +- src/p_tick.c | 6 +- src/r_bsp.cpp | 14 ++-- src/r_data.c | 4 +- src/r_data.h | 2 - src/r_draw.cpp | 30 +++---- src/r_main.cpp | 48 +++++------ src/r_patchrotation.cpp | 4 +- src/r_portal.c | 12 +-- src/r_segs.cpp | 6 +- src/r_skins.c | 12 +-- src/r_sky.c | 16 ++-- src/r_things.cpp | 8 +- src/screen.c | 4 +- src/v_video.c | 2 +- 31 files changed, 278 insertions(+), 334 deletions(-) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index eb39f34f7..f69d67cfe 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -78,14 +78,14 @@ #define MAX_REASONLENGTH 30 #define FORCECLOSE 0x8000 -static long long unsigned packetstat[NUMPACKETTYPE+1] = {0}; +static long long unsigned packetstat[NUMPACKETTYPE+1] = {}; boolean server = true; // true or false but !server == client #define client (!server) boolean nodownload = false; boolean serverrunning = false; INT32 serverplayer = 0; -char motd[254], server_context[8]; // Message of the Day, Unique Context (even without Mumble support) +char motd[254] = {}, server_context[8] = {}; // Message of the Day, Unique Context (even without Mumble support) #define MAP_ICON_REQUEST_FREQUENCY 8 @@ -98,14 +98,13 @@ static int map_icon_request_count; // current count of icon requests sent static UINT8 *map_icon_data; static patch_t *map_icon; -plrinfo playerinfo[MAXPLAYERS]; +plrinfo playerinfo[MAXPLAYERS] = {}; SINT8 joinnode = 0; // used for CL_VIEWSERVER -boolean player_muted[MAXPLAYERS] = {0}; +boolean player_muted[MAXPLAYERS] = {}; // Server specific vars -UINT8 playernode[MAXPLAYERS]; - +UINT8 playernode[MAXPLAYERS] = {}; // Minimum timeout for sending the savegame // The actual timeout will be longer depending on the savegame length @@ -118,15 +117,15 @@ static tic_t savegameresendcooldown[MAXNETNODES]; // How long before we can rese static tic_t freezetimeout[MAXNETNODES]; // Until when can this node freeze the server before getting a timeout? UINT16 pingmeasurecount = 1; -UINT32 realpingtable[MAXPLAYERS]; //the base table of ping where an average will be sent to everyone. -UINT32 playerpingtable[MAXPLAYERS]; //table of player latency values. +UINT32 realpingtable[MAXPLAYERS] = {}; //the base table of ping where an average will be sent to everyone. +UINT32 playerpingtable[MAXPLAYERS] = {}; //table of player latency values. #define GENTLEMANSMOOTHING (TICRATE) static tic_t reference_lag; static UINT8 spike_time; -tic_t lowest_lag; -tic_t simulated_lag; -boolean server_lagless; +tic_t lowest_lag = 0; +tic_t simulated_lag = 0; +boolean server_lagless = true; static void Lagless_OnChange(void) { @@ -144,12 +143,12 @@ static CV_PossibleValue_t mindelay_cons_t[] = {{0, "MIN"}, {30, "MAX"}, {0, NULL consvar_t cv_mindelay = {"mindelay", "0", CV_SAVE, mindelay_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL}; consvar_t cv_gentlemens = {"gentlemensdelay", "Off", CV_SAVE|CV_CALL|CV_NOINIT, CV_OnOff, Lagless_OnChange, 0, NULL, NULL, 0, 0, NULL}; // this should be a netvar Zzz... -SINT8 nodetoplayer[MAXNETNODES]; -SINT8 nodetoplayer2[MAXNETNODES]; // say the numplayer for this node if any (splitscreen) -SINT8 nodetoplayer3[MAXNETNODES]; // say the numplayer for this node if any (splitscreen == 2) -SINT8 nodetoplayer4[MAXNETNODES]; // say the numplayer for this node if any (splitscreen == 3) -UINT8 playerpernode[MAXNETNODES]; // used specialy for splitscreen -boolean nodeingame[MAXNETNODES]; // set false as nodes leave game +SINT8 nodetoplayer[MAXNETNODES] = {}; +SINT8 nodetoplayer2[MAXNETNODES] = {}; // say the numplayer for this node if any (splitscreen) +SINT8 nodetoplayer3[MAXNETNODES] = {}; // say the numplayer for this node if any (splitscreen == 2) +SINT8 nodetoplayer4[MAXNETNODES] = {}; // say the numplayer for this node if any (splitscreen == 3) +UINT8 playerpernode[MAXNETNODES] = {}; // used specialy for splitscreen +boolean nodeingame[MAXNETNODES] = {}; // set false as nodes leave game tic_t servermaxping = 20; // server's max delay, in frames. Defaults to 20 static tic_t nettics[MAXNETNODES]; // what tic the client have received @@ -196,7 +195,7 @@ boolean is_client_saturn[MAXNETNODES]; static UINT8 localtextcmd[MAXSPLITSCREENPLAYERS][MAXTEXTCMD]; static tic_t neededtic; SINT8 servernode = 0; // the number of the server node -char connectedservername[MAXSERVERNAME+1]; +char connectedservername[MAXSERVERNAME+1] = {}; /// \brief do we accept new players? /// \todo WORK! boolean acceptnewnode = true; @@ -227,7 +226,7 @@ struct textcmdbuf_s static textcmdbuf_t *textcmdbuf[MAXSPLITSCREENPLAYERS] = {NULL}; static ticcmd_t playercmds[MAXPLAYERS]; -ticcmd_t netcmds[BACKUPTICS][MAXPLAYERS]; +ticcmd_t netcmds[BACKUPTICS][MAXPLAYERS] = {}; static textcmdtic_t *textcmds[TEXTCMD_HASH_SIZE] = {NULL}; consvar_t cv_showjoinaddress = {"showjoinaddress", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; @@ -285,7 +284,7 @@ static inline void *G_ScpyTiccmd(ticcmd_t* dest, void* src, const size_t n) // Some software don't support largest packet // (original sersetup, not exactely, but the probability of sending a packet // of 512 bytes is like 0.1) -UINT16 software_MAXPACKETLENGTH; +UINT16 software_MAXPACKETLENGTH = 0; /** Guesses the value of a tic from its lowest byte and from maketic * diff --git a/src/d_main.c b/src/d_main.c index bafc110e1..7a738288b 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -142,8 +142,8 @@ static char addonsdir[MAX_WADPATH]; // Events can be discarded if no responder claims them // referenced from i_system.c for I_GetKey() -event_t events[MAXEVENTS]; -INT32 eventhead, eventtail; +event_t events[MAXEVENTS] = {}; +INT32 eventhead = 0, eventtail = 0; boolean dedicated = false; @@ -161,68 +161,17 @@ void D_PostEvent(const event_t *ev) // modifier keys // Now handled in I_OsPolling -UINT8 shiftdown = 0; // 0x1 left, 0x2 right -UINT8 ctrldown = 0; // 0x1 left, 0x2 right -UINT8 altdown = 0; // 0x1 left, 0x2 right -boolean capslock = 0; // gee i wonder what this does. +UINT8 shiftdown = 0; // 0x1 left, 0x2 right +UINT8 ctrldown = 0; // 0x1 left, 0x2 right +UINT8 altdown = 0; // 0x1 left, 0x2 right +boolean capslock = 0; // gee i wonder what this does. -static void D_PadMenuScrollInput(UINT8 input) -{ - event_t dpadev; - memset(&dpadev, 0, sizeof(event_t)); - dpadev.type = ev_keydown; - - switch (input) - { - case DPAD_UP: - dpadev.data1 = KEY_UPARROW; - break; - case DPAD_DOWN: - dpadev.data1 = KEY_DOWNARROW; - break; - case DPAD_LEFT: - dpadev.data1 = KEY_LEFTARROW; - break; - case DPAD_RIGHT: - dpadev.data1 = KEY_RIGHTARROW; - break; - } - - D_PostEvent(&dpadev); // put into eventlist -} - -#define SCROLLDELAY 19 - -// Check if any dpad button is held -// and pass it to the eventlist -static void D_GamePadMenuScrollTicker(void) -{ - UINT8 i; - static UINT8 menuInputDelayTimer = 0; - - for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) - { - if (dpadscrollstate[i]) - { - if (menuInputDelayTimer < SCROLLDELAY) - menuInputDelayTimer++; - else if (menuInputDelayTimer == SCROLLDELAY) - D_PadMenuScrollInput(i); - - return; - } - } - - menuInputDelayTimer = 0; -} -#undef SCROLLDELAY - -static UINT16 curcolor[MAXSPLITSCREENPLAYERS] = {0}; +static UINT16 curcolor[MAXSPLITSCREENPLAYERS] = {}; static void D_DeviceLEDTick(void) { UINT8 i; - static UINT16 color[MAXSPLITSCREENPLAYERS] = {0}; + static UINT16 color[MAXSPLITSCREENPLAYERS] = {}; if (numcontrollers == 0) { @@ -390,8 +339,7 @@ static void D_Renderview(void) } else if (rendermode == render_soft) #endif - - R_RenderPlayerView(&players[displayplayers[i]]); + R_RenderPlayerView(&players[displayplayers[i]]); } if (rendermode == render_soft) @@ -720,7 +668,7 @@ static boolean D_Display(void) // D_SRB2Loop // ========================================================================= -tic_t rendergametic; +tic_t rendergametic = 0; void D_SRB2Loop(void) { diff --git a/src/d_net.c b/src/d_net.c index d5b11f018..7fb216288 100644 --- a/src/d_net.c +++ b/src/d_net.c @@ -95,9 +95,9 @@ static INT32 sendackpacket = 0, getackpacket = 0; INT32 ticruned = 0, ticmiss = 0; // globals -INT32 getbps, sendbps; -float lostpercent, duppercent, gamelostpercent; -INT32 packetheaderlength; +INT32 getbps = 0, sendbps = 0; +float lostpercent = 0, duppercent = 0, gamelostpercent = 0; +INT32 packetheaderlength = 0; boolean Net_GetNetStat(void) { diff --git a/src/d_netfil.c b/src/d_netfil.c index 6c9183eea..d80ae7b79 100644 --- a/src/d_netfil.c +++ b/src/d_netfil.c @@ -110,14 +110,14 @@ static fileused_t transferFiles[UINT8_MAX + 1]; // Write time of file: utime // Receiver structure -INT32 fileneedednum; // Number of files needed to join the server -fileneeded_t fileneeded[MAX_WADFILES]; // List of needed files +INT32 fileneedednum = 0; // Number of files needed to join the server +fileneeded_t fileneeded[MAX_WADFILES] = {}; // List of needed files #ifdef HAVE_THREADS static I_mutex downloadmutex; #endif char downloaddir[512] = "DOWNLOAD"; -file_download_t filedownload; +file_download_t filedownload = {}; #ifdef HAVE_CURL static CURL *http_handle; @@ -131,7 +131,7 @@ static UINT32 curl_origfilesize; static UINT32 curl_origtotalfilesize; static char *curl_realname = NULL; fileneeded_t *curl_curfile = NULL; -HTTP_login *curl_logins; +HTTP_login *curl_logins = NULL; #endif /** Fills a serverinfo packet with information about wad files loaded. diff --git a/src/g_demo.c b/src/g_demo.c index 897238107..5e6f20a6d 100644 --- a/src/g_demo.c +++ b/src/g_demo.c @@ -68,8 +68,8 @@ UINT8 numDemos = 0; //3; -- i'm FED UP of losing my skincolour to a broken UINT32 demoDelayTime = 15*TICRATE; UINT32 demoIdleTime = 3*TICRATE; -boolean nodrawers; // for comparative timing purposes -boolean noblit; // for comparative timing purposes +boolean nodrawers = false; // for comparative timing purposes +boolean noblit = false; // for comparative timing purposes static tic_t demostarttime; // for comparative timing purposes //@TODO put these all in a struct for namespacing purposes? @@ -80,7 +80,7 @@ static UINT8 *demoend; static UINT8 demoflags; static boolean demosynced = true; // console warning message -struct demovars_s demo; +struct demovars_s demo = {}; consvar_t cv_resyncdemo = {"resyncdemo", "On", 0, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; diff --git a/src/g_game.c b/src/g_game.c index aa03a0524..a9b2579a8 100644 --- a/src/g_game.c +++ b/src/g_game.c @@ -59,15 +59,15 @@ #include "discord.h" #endif -gameaction_t gameaction; +gameaction_t gameaction = 0; gamestate_t gamestate = GS_NULL; UINT8 ultimatemode = false; -boolean botingame; -UINT8 botskin; -UINT8 botcolor; +boolean botingame = false; +UINT8 botskin = 0; +UINT8 botcolor = 0; -JoyType_t Joystick[MAXSPLITSCREENPLAYERS]; +JoyType_t Joystick[MAXSPLITSCREENPLAYERS] = {}; // 1024 bytes is plenty for a savegame #define SAVEGAMESIZE (1024) @@ -83,10 +83,10 @@ static void G_DoContinued(void); static void G_DoWorldDone(void); static void G_DoStartVote(void); -music_t mapmusic; +music_t mapmusic = {}; INT16 gamemap = 1; -INT16 maptol; +INT16 maptol = 0; UINT8 globalweather = 0; INT32 curWeather = PRECIP_NONE; INT32 cursaveslot = -1; // Auto-save 1p savegame slot @@ -97,29 +97,29 @@ UINT16 mainwads = 0; boolean modifiedgame = false; // Set if homebrew PWAD stuff has been added. boolean majormods = false; // Set if Lua/Gameplay SOC/replacement map has been added. boolean savemoddata = false; -UINT8 paused; +UINT8 paused = 0; UINT8 modeattacking = ATTACKING_NONE; boolean imcontinuing = false; boolean runemeraldmanager = false; -boolean netgame; // only true if packets are broadcast -boolean multiplayer; -boolean playeringame[MAXPLAYERS]; -boolean addedtogame; -player_t players[MAXPLAYERS]; +boolean netgame = false; // only true if packets are broadcast +boolean multiplayer = false; +boolean playeringame[MAXPLAYERS] = {}; +boolean addedtogame = false; +player_t players[MAXPLAYERS] = {}; -INT32 consoleplayer; // player taking events and displaying -INT32 displayplayers[MAXSPLITSCREENPLAYERS] = {0}; // view being displayed +INT32 consoleplayer = 0; // player taking events and displaying +INT32 displayplayers[MAXSPLITSCREENPLAYERS] = {}; // view being displayed -tic_t gametic; -tic_t levelstarttic; // gametic at level start -UINT32 totalrings; // for intermission -INT16 lastmap; // last level you were at (returning from special stages) -tic_t timeinmap; // Ticker for time spent in level (used for levelcard display) +tic_t gametic = 0; +tic_t levelstarttic = 0; // gametic at level start +UINT32 totalrings = 0; // for intermission +INT16 lastmap = 0; // last level you were at (returning from special stages) +tic_t timeinmap = 0; // Ticker for time spent in level (used for levelcard display) -INT16 spstage_start; -INT16 sstage_start; -INT16 sstage_end; +INT16 spstage_start = 0; +INT16 sstage_start = 0; +INT16 sstage_end = 0; boolean looptitle = true; boolean useNightsSS = false; @@ -134,42 +134,42 @@ boolean countdowntimeup = false; cutscene_t *cutscenes[128]; -INT16 nextmapoverride; -boolean skipstats; +INT16 nextmapoverride = 0; +boolean skipstats = false; // Pointers to each CTF flag -mobj_t *redflag; -mobj_t *blueflag; +mobj_t *redflag = NULL; +mobj_t *blueflag = NULL; // Pointers to CTF spawn location -mapthing_t *rflagpoint; -mapthing_t *bflagpoint; +mapthing_t *rflagpoint = NULL; +mapthing_t *bflagpoint = NULL; struct quake quake; // Map Header Information -mapheader_t* mapheaderinfo[NUMMAPS] = {NULL}; +mapheader_t* mapheaderinfo[NUMMAPS] = {}; static boolean exitgame = false; static boolean retrying = false; -UINT8 stagefailed; // Used for GEMS BONUS? Also to see if you beat the stage. +UINT8 stagefailed = 0; // Used for GEMS BONUS? Also to see if you beat the stage. -UINT16 emeralds; -UINT32 token; // Number of tokens collected in a level -UINT32 tokenlist; // List of tokens collected -INT32 tokenbits; // Used for setting token bits +UINT16 emeralds = 0; +UINT32 token = 0; // Number of tokens collected in a level +UINT32 tokenlist = 0; // List of tokens collected +INT32 tokenbits = 0; // Used for setting token bits // Old Special Stage -INT32 sstimer; // Time allotted in the special stage +INT32 sstimer = 0; // Time allotted in the special stage boolean gamedataloaded = false; // Time attack data for levels // These are dynamically allocated for space reasons now -recorddata_t *mainrecords[NUMMAPS] = {NULL}; -UINT8 mapvisited[NUMMAPS]; +recorddata_t *mainrecords[NUMMAPS] = {}; +UINT8 mapvisited[NUMMAPS] = {}; -UINT32 bluescore, redscore; // CTF and Team Match team scores +UINT32 bluescore = 0, redscore = 0; // CTF and Team Match team scores // ring count... for PERFECT! INT32 nummaprings = 0; @@ -179,12 +179,12 @@ INT32 nummapboxes = 0; INT32 numgotboxes = 0; // Elminates unnecessary searching. -boolean CheckForBustableBlocks; -boolean CheckForBouncySector; -boolean CheckForQuicksand; -boolean CheckForMarioBlocks; -boolean CheckForFloatBob; -boolean CheckForReverseGravity; +boolean CheckForBustableBlocks = false; +boolean CheckForBouncySector = false; +boolean CheckForQuicksand = false; +boolean CheckForMarioBlocks = false; +boolean CheckForFloatBob = false; +boolean CheckForReverseGravity = false; // Powerup durations UINT16 invulntics = 20*TICRATE; @@ -215,67 +215,66 @@ INT32 gameovertics = 15*TICRATE; UINT8 use1upSound = 0; UINT8 maxXtraLife = 2; // Max extra lives from rings -UINT8 introtoplay; -UINT8 creditscutscene; +UINT8 introtoplay = 0; +UINT8 creditscutscene = 0; // Emerald locations -mobj_t *hunt1; -mobj_t *hunt2; -mobj_t *hunt3; +mobj_t *hunt1 = NULL; +mobj_t *hunt2 = NULL; +mobj_t *hunt3 = NULL; -tic_t racecountdown, exitcountdown; // for racing +tic_t racecountdown = 0, exitcountdown = 0; // for racing -fixed_t gravity; -fixed_t mapobjectscale; +fixed_t gravity = 0; +fixed_t mapobjectscale = FRACUNIT; struct maplighting maplighting; -INT16 autobalance; //for CTF team balance -INT16 teamscramble; //for CTF team scramble -INT16 scrambleplayers[MAXPLAYERS]; //for CTF team scramble -INT16 scrambleteams[MAXPLAYERS]; //for CTF team scramble -INT16 scrambletotal; //for CTF team scramble -INT16 scramblecount; //for CTF team scramble +INT16 autobalance = 0; //for CTF team balance +INT16 teamscramble = 0; //for CTF team scramble +INT16 scrambleplayers[MAXPLAYERS] = {}; //for CTF team scramble +INT16 scrambleteams[MAXPLAYERS] = {}; //for CTF team scramble +INT16 scrambletotal = 0; //for CTF team scramble +INT16 scramblecount = 0; //for CTF team scramble -INT32 cheats; //for multiplayer cheat commands +INT32 cheats = 0; //for multiplayer cheat commands // SRB2Kart // Cvars that we don't want changed mid-game -UINT8 gamespeed; // Game's current speed (or difficulty, or cc, or etc); 0 for easy, 1 for normal, 2 for hard +UINT8 gamespeed = 0; // Game's current speed (or difficulty, or cc, or etc); 0 for easy, 1 for normal, 2 for hard boolean encoremode = false; // Encore Mode currently enabled? -boolean prevencoremode; -boolean franticitems; // Frantic items currently enabled? -boolean comeback; // Battle Mode's karma comeback is on/off +boolean prevencoremode = 0; +boolean franticitems = 0; // Frantic items currently enabled? +boolean comeback = 0; // Battle Mode's karma comeback is on/off // Voting system -INT16 votelevels[4][2]; // Levels that were rolled by the host -SINT8 votes[MAXPLAYERS]; // Each player's vote -SINT8 pickedvote; // What vote the host rolls +INT16 votelevels[4][2] = {}; // Levels that were rolled by the host +SINT8 votes[MAXPLAYERS] = {}; // Each player's vote +SINT8 pickedvote = 0; // What vote the host rolls // Server-sided, synched variables -SINT8 battlewanted[4]; // WANTED players in battle, worth x2 points -tic_t wantedcalcdelay; // Time before it recalculates WANTED -tic_t indirectitemcooldown; // Cooldown before any more Shrink, SPB, or any other item that works indirectly is awarded -tic_t hyubgone; // Cooldown before hyudoro is allowed to be rerolled -tic_t mapreset; // Map reset delay when enough players have joined an empty game -UINT8 nospectategrief; // How many players need to be in-game to eliminate last; for preventing spectate griefing -boolean thwompsactive; // Thwomps activate on lap 2 -SINT8 spbplace; // SPB exists, give the person behind better items -boolean startedInFreePlay; // Map was started in free play +SINT8 battlewanted[4] = {}; // WANTED players in battle, worth x2 points +tic_t wantedcalcdelay = 0; // Time before it recalculates WANTED +tic_t indirectitemcooldown = 0; // Cooldown before any more Shrink, SPB, or any other item that works indirectly is awarded +tic_t hyubgone = 0; // Cooldown before hyudoro is allowed to be rerolled +tic_t mapreset = 0; // Map reset delay when enough players have joined an empty game +UINT8 nospectategrief = 0; // How many players need to be in-game to eliminate last; for preventing spectate griefing +boolean thwompsactive = 0; // Thwomps activate on lap 2 +SINT8 spbplace = 0; // SPB exists, give the person behind better items +boolean startedInFreePlay = false; // Map was started in free play // Client-sided, unsynched variables (NEVER use in anything that needs to be synced with other players) -boolean legitimateexit; // Did this client actually finish the match? -boolean comebackshowninfo; // Have you already seen the "ATTACK OR PROTECT" message? -static INT16 randmapbuffer[NUMMAPS+1]; // Buffer for maps RandMap is allowed to roll +boolean legitimateexit = 0; // Did this client actually finish the match? +boolean comebackshowninfo = 0; // Have you already seen the "ATTACK OR PROTECT" message? +static INT16 randmapbuffer[NUMMAPS+1] = {}; // Buffer for maps RandMap is allowed to roll -tic_t hidetime; +tic_t hidetime = 0; // Grading -UINT32 timesBeaten; -UINT32 timesBeatenWithEmeralds; -//UINT32 timesBeatenUltimate; +UINT32 timesBeaten = 0; +UINT32 timesBeatenWithEmeralds = 0; -INT16 prevmap, nextmap; +INT16 prevmap = 0, nextmap = 0; // Analog Control void SendWeaponPref(void); @@ -470,7 +469,7 @@ consvar_t cv_cechotoggle = {"show_cecho", "On", CV_SAVE, cechotoggle_t, NULL, 0, #endif #ifdef SEENAMES -player_t *seenplayer; // player we're aiming at right now +player_t *seenplayer = NULL; // player we're aiming at right now #endif char player_names[MAXPLAYERS][MAXPLAYERNAME+1] = @@ -493,7 +492,7 @@ char player_names[MAXPLAYERS][MAXPLAYERNAME+1] = "Player 16" }; // SRB2kart - removed Players 17 through 32 -INT32 player_name_changes[MAXPLAYERS]; +INT32 player_name_changes[MAXPLAYERS] = {}; INT16 rw_maximums[NUM_WEAPONS] = { @@ -797,9 +796,9 @@ boolean InputDown(INT32 gc, UINT8 p) } } -INT32 localaiming[MAXSPLITSCREENPLAYERS] = {0}; -angle_t localangle[MAXSPLITSCREENPLAYERS] = {0}; -boolean camspin[MAXSPLITSCREENPLAYERS] = {0}; +INT32 localaiming[MAXSPLITSCREENPLAYERS] = {}; +angle_t localangle[MAXSPLITSCREENPLAYERS] = {}; +boolean camspin[MAXSPLITSCREENPLAYERS] = {}; static fixed_t forwardmove[2] = {25<>16, 50<>16}; static fixed_t sidemove[2] = {2<>16, 4<>16}; diff --git a/src/hardware/hw_clip.c b/src/hardware/hw_clip.c index 6066d8528..624dc4234 100644 --- a/src/hardware/hw_clip.c +++ b/src/hardware/hw_clip.c @@ -80,14 +80,13 @@ typedef struct clipnode_s - { - struct clipnode_s *prev, *next; - angle_t start, end; - } clipnode_t; +{ + struct clipnode_s *prev, *next; + angle_t start, end; +} clipnode_t; -clipnode_t *freelist; -clipnode_t *clipnodes; -clipnode_t *cliphead; +static clipnode_t *freelist; +static clipnode_t *cliphead; static clipnode_t * gld_clipnode_GetNew(void); static clipnode_t * gld_clipnode_NewRange(angle_t start, angle_t end); diff --git a/src/hardware/hw_defs.h b/src/hardware/hw_defs.h index 590e03a63..ce903c82d 100644 --- a/src/hardware/hw_defs.h +++ b/src/hardware/hw_defs.h @@ -117,7 +117,7 @@ typedef struct typedef struct { - FLOAT x,y,z; // position + FLOAT x, y, z; // position FLOAT anglex, angley, anglez; // aimingangle / viewangle FLOAT scalex, scaley, scalez; FLOAT fovangle; diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 969b976ff..2db86af78 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -75,19 +75,19 @@ boolean gl_drawing_stencil = false; static INT32 current_bsp_culling_distance = 0; -FTransform atransform; +FTransform atransform = {}; // Float variants of viewx, viewy, viewz, etc. static float gl_viewx, gl_viewy, gl_viewz; -float gl_viewsin, gl_viewcos; +float gl_viewsin = 0.0f, gl_viewcos = 0.0f; static float gl_viewludsin, gl_viewludcos; static angle_t gl_aimingangle; -seg_t *gl_curline; -side_t *gl_sidedef; -line_t *gl_linedef; -sector_t *gl_frontsector; -sector_t *gl_backsector; +seg_t *gl_curline = NULL; +side_t *gl_sidedef = NULL; +line_t *gl_linedef = NULL; +sector_t *gl_frontsector = NULL; +sector_t *gl_backsector = NULL; // values for the far clipping plane static constexpr float clipping_distances[] = {1024.0f, 2048.0f, 4096.0f, 6144.0f, 8192.0f, 12288.0f, 16384.0f}; @@ -5327,7 +5327,9 @@ void HWR_SetTransform(float fpov) atransform.fliptype = TRANSFORM_FLIP; } else if (postimg & POSTIMG_MIRROR) + { atransform.fliptype = TRANSFORM_MIRROR; + } // Set transform. GL_SetTransform(&atransform); diff --git a/src/hardware/hw_md2.c b/src/hardware/hw_md2.c index 911f382a9..763fb873c 100644 --- a/src/hardware/hw_md2.c +++ b/src/hardware/hw_md2.c @@ -72,10 +72,9 @@ #include #endif -md2_t md2_models[NUMSPRITES]; -md2_t md2_playermodels[MAXSKINS]; -md2_t md2_localplayermodels[MAXLOCALSKINS]; - +md2_t md2_models[NUMSPRITES] = {}; +md2_t md2_playermodels[MAXSKINS] = {}; +md2_t md2_localplayermodels[MAXLOCALSKINS] = {}; /* * free model diff --git a/src/hardware/hw_portal.c b/src/hardware/hw_portal.c index db17d05bf..d8ad87354 100644 --- a/src/hardware/hw_portal.c +++ b/src/hardware/hw_portal.c @@ -30,7 +30,7 @@ SINT8 gl_portal_state = GLPORTAL_OFF; -gl_portallist_t *currentportallist; +gl_portallist_t *currentportallist = NULL; // clip the area outside the portal destination window void HWR_PortalClipping(gl_portal_t *portal) @@ -168,8 +168,10 @@ void HWR_RenderPortal(gl_portal_t* portal, gl_portal_t* rootportal, const float // go to portal frame lmao HWR_PortalFrame(portal); + // call HWR_RenderViewpoint HWR_RenderPortalViewpoint(portal, player, stencil_level + 1, true); + // return to current frame if (rootportal) HWR_PortalFrame(rootportal); diff --git a/src/p_enemy.c b/src/p_enemy.c index a487eb328..880f110cd 100644 --- a/src/p_enemy.c +++ b/src/p_enemy.c @@ -28,8 +28,8 @@ boolean LUA_CallAction(enum actionnum actionnum, void *thing); -INT32 var1; -INT32 var2; +INT32 var1 = 0; +INT32 var2 = 0; // // P_NewChaseDir related LUT. diff --git a/src/p_map.c b/src/p_map.c index aea01c6a7..f9d828b98 100644 --- a/src/p_map.c +++ b/src/p_map.c @@ -41,32 +41,32 @@ #include "m_perfstats.h" // ps_checkposition_calls -fixed_t tmbbox[4]; -mobj_t *tmthing; +fixed_t tmbbox[4] = {}; +mobj_t *tmthing = NULL; static INT32 tmflags; -fixed_t tmx; -fixed_t tmy; +fixed_t tmx = 0; +fixed_t tmy = 0; // If "floatok" true, move would be ok // if within "tmfloorz - tmceilingz". -boolean floatok; +boolean floatok = false; -fixed_t tmfloorz, tmceilingz; -static fixed_t tmdropoffz, tmdrpoffceilz; // drop-off floor/ceiling heights -mobj_t *tmfloorthing; // the thing corresponding to tmfloorz or NULL if tmfloorz is from a sector -mobj_t *tmhitthing; // the solid thing you bumped into (for collisions) -pslope_t *tmfloorslope, *tmceilingslope; +fixed_t tmfloorz = 0, tmceilingz = 0; +static fixed_t tmdropoffz = 0, tmdrpoffceilz = 0; // drop-off floor/ceiling heights +mobj_t *tmfloorthing = NULL; // the thing corresponding to tmfloorz or NULL if tmfloorz is from a sector +mobj_t *tmhitthing = NULL; // the solid thing you bumped into (for collisions) +pslope_t *tmfloorslope = NULL, *tmceilingslope = NULL; // keep track of the line that lowers the ceiling, // so missiles don't explode against sky hack walls -line_t *ceilingline; +line_t *ceilingline = NULL; // set by PIT_CheckLine() for any line that stopped the PIT_CheckLine() // that is, for any line which is 'solid' -line_t *blockingline; +line_t *blockingline = NULL; msecnode_t *sector_list = NULL; -camera_t *mapcampointer; +camera_t *mapcampointer = NULL; // // TELEPORT MOVE diff --git a/src/p_mobj.c b/src/p_mobj.c index 86261a644..1813522e7 100644 --- a/src/p_mobj.c +++ b/src/p_mobj.c @@ -43,7 +43,7 @@ consvar_t cv_splats = {"splats", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL}; #endif -actioncache_t actioncachehead; +actioncache_t actioncachehead = {}; static mobj_t *overlaycap = NULL; static mobj_t *shadowcap = NULL; diff --git a/src/p_saveg.c b/src/p_saveg.c index 46d52917a..7c2bd9e95 100644 --- a/src/p_saveg.c +++ b/src/p_saveg.c @@ -35,7 +35,7 @@ #include "lua_script.h" #include "p_slopes.h" -savedata_t savedata; +savedata_t savedata = {}; // Block UINT32s to attempt to ensure that the correct data is // being sent and received diff --git a/src/p_setup.c b/src/p_setup.c index b70cdebd6..b81bfd30f 100644 --- a/src/p_setup.c +++ b/src/p_setup.c @@ -92,7 +92,7 @@ // Map MD5, calculated on level load. // Sent to clients in PT_SERVERINFO. // -unsigned char mapmd5[16]; +unsigned char mapmd5[16] = {}; // true when level was loaded from netsave boolean midgamejoin = false; @@ -102,22 +102,22 @@ boolean midgamejoin = false; // Store VERTEXES, LINEDEFS, SIDEDEFS, etc. // -size_t numvertexes, numsegs, numsectors, numsubsectors, numnodes, numlines, numsides, nummapthings; -vertex_t *vertexes; -seg_t *segs; -sector_t *sectors; -subsector_t *subsectors; -node_t *nodes; -line_t *lines; -side_t *sides; -mapthing_t *mapthings; -sector_t *spawnsectors; -line_t *spawnlines; -side_t *spawnsides; -INT32 numstarposts; -boolean levelloading; +size_t numvertexes = 0, numsegs = 0, numsectors = 0, numsubsectors = 0, numnodes = 0, numlines = 0, numsides = 0, nummapthings = 0; +vertex_t *vertexes = NULL; +seg_t *segs = NULL; +sector_t *sectors = NULL; +subsector_t *subsectors = NULL; +node_t *nodes = NULL; +line_t *lines = NULL; +side_t *sides = NULL; +mapthing_t *mapthings = NULL; +sector_t *spawnsectors = NULL; +line_t *spawnlines = NULL; +side_t *spawnsides = NULL; +INT32 numstarposts = 0; +boolean levelloading = false; -virtres_t *curmapvirt; +virtres_t *curmapvirt = NULL; // BLOCKMAP // Created from axis aligned bounding box @@ -127,32 +127,32 @@ virtres_t *curmapvirt; // by spatial subdivision in 2D. // // Blockmap size. -INT32 bmapwidth, bmapheight; // size in mapblocks +INT32 bmapwidth = 0, bmapheight = 0; // size in mapblocks -INT32 *blockmap; // INT32 for large maps +INT32 *blockmap = NULL; // INT32 for large maps // offsets in blockmap are from here -INT32 *blockmaplump; // Big blockmap +INT32 *blockmaplump = NULL; // Big blockmap // origin of block map -fixed_t bmaporgx, bmaporgy; +fixed_t bmaporgx = 0, bmaporgy = 0; // for thing chains -mobj_t **blocklinks; -precipmobj_t **precipblocklinks; +mobj_t **blocklinks = NULL; +precipmobj_t **precipblocklinks = NULL; // REJECT // For fast sight rejection. // Speeds up enemy AI by skipping detailed LineOf Sight calculation. // Without special effect, this could be used as a PVS lookup as well. // -UINT8 *rejectmatrix; +UINT8 *rejectmatrix = NULL; // Maintain single and multi player starting spots. -INT32 numdmstarts, numcoopstarts, numredctfstarts, numbluectfstarts; +INT32 numdmstarts = 0, numcoopstarts = 0, numredctfstarts = 0, numbluectfstarts = 0; -mapthing_t *deathmatchstarts[MAX_DM_STARTS]; -mapthing_t *playerstarts[MAXPLAYERS]; -mapthing_t *bluectfstarts[MAXPLAYERS]; -mapthing_t *redctfstarts[MAXPLAYERS]; +mapthing_t *deathmatchstarts[MAX_DM_STARTS] = {}; +mapthing_t *playerstarts[MAXPLAYERS] = {}; +mapthing_t *bluectfstarts[MAXPLAYERS] = {}; +mapthing_t *redctfstarts[MAXPLAYERS] = {}; // Global state for PartialAddWadFile/MultiSetupWadFiles // Might be replacable with parameters, but non-trivial when the functions are called on separate tics diff --git a/src/p_spec.c b/src/p_spec.c index c7a6dc15f..7332154a8 100644 --- a/src/p_spec.c +++ b/src/p_spec.c @@ -44,7 +44,7 @@ // Not sure if this is necessary, but it was in w_wad.c, so I'm putting it here too -Shadow Hog #include -mobj_t *skyboxmo[2]; +mobj_t *skyboxmo[2] = {}; // Amount (dx, dy) vector linedef is shifted right to get scroll amount #define SCROLL_SHIFT 5 @@ -93,7 +93,7 @@ static void P_AddSpikeThinker(sector_t *sec, INT32 referrer); //SoM: 3/7/2000: New sturcture without limits. -anim_t *lastanim; +anim_t *lastanim = NULL; anim_t *anims = NULL; /// \todo free leak static size_t maxanims; diff --git a/src/p_tick.c b/src/p_tick.c index 35dc25164..d8b21aa86 100644 --- a/src/p_tick.c +++ b/src/p_tick.c @@ -44,7 +44,7 @@ // Dynamic slopes #include "p_slopes.h" -tic_t leveltime; +tic_t leveltime = 0; // // THINKERS @@ -55,8 +55,8 @@ tic_t leveltime; // // Both the head and tail of the thinker list. -thinker_t thinkercap; -thinker_t precipcap; +thinker_t thinkercap = {}; +thinker_t precipcap = {}; void Command_Numthinkers_f(void) { diff --git a/src/r_bsp.cpp b/src/r_bsp.cpp index 87d775c87..ea0f5c17a 100644 --- a/src/r_bsp.cpp +++ b/src/r_bsp.cpp @@ -26,11 +26,11 @@ #include "qs22j.h" -seg_t *curline; -side_t *sidedef; -line_t *linedef; -sector_t *frontsector; -sector_t *backsector; +seg_t *curline = NULL; +side_t *sidedef = NULL; +line_t *linedef = NULL; +sector_t *frontsector = NULL; +sector_t *backsector = NULL; // very ugly realloc() of drawsegs at run-time, I upped it to 512 // instead of 256.. and someone managed to send me a level with @@ -40,11 +40,11 @@ drawseg_t *drawsegs = NULL; drawseg_t *ds_p = NULL; // indicates doors closed wrt automap bugfix: -INT32 doorclosed; +INT32 doorclosed = 0; // A wall was drawn covering the whole screen, which means we // can block off the BSP across that seg. -boolean g_walloffscreen; +boolean g_walloffscreen = false; boolean R_NoEncore(sector_t *sector, boolean ceiling) { diff --git a/src/r_data.c b/src/r_data.c index 4dc6653ea..da5a81dac 100644 --- a/src/r_data.c +++ b/src/r_data.c @@ -83,7 +83,7 @@ typedef struct // a patch or sprite is composed of zero or more columns. // -size_t numspritelumps, max_spritelumps; +size_t numspritelumps = 0, max_spritelumps = 0; // textures INT32 numtextures = 0; // total number of textures found, @@ -110,7 +110,7 @@ UINT8 invertmap[256]; #endif // for debugging/info purposes -size_t flatmemory, spritememory, texturememory; // gotta play by 2.2 rules to get this to work +static size_t flatmemory = 0, spritememory = 0, texturememory = 0; // gotta play by 2.2 rules to get this to work // Blends two pixels together, using the equation // that matches the specified alpha style. diff --git a/src/r_data.h b/src/r_data.h index c77ac8b0e..090c363ed 100644 --- a/src/r_data.h +++ b/src/r_data.h @@ -91,8 +91,6 @@ UINT8 *R_GetFlat(lumpnum_t flatnum); void R_InitData(void); void R_PrecacheLevel(void); -extern size_t flatmemory, spritememory, texturememory; - // Retrieval. // Floor/ceiling opaque texture tiles, // lookup by name. For animation? diff --git a/src/r_draw.cpp b/src/r_draw.cpp index c2b0f9e28..f27b0023c 100644 --- a/src/r_draw.cpp +++ b/src/r_draw.cpp @@ -41,40 +41,40 @@ /** \brief view info */ -INT32 viewwidth, viewheight, viewwindowx, viewwindowy; +INT32 viewwidth = 0, viewheight = 0, viewwindowx = 0, viewwindowy = 0; // ========================================================================= // COLUMN DRAWING CODE STUFF // ========================================================================= -drawcolumndata_t g_dc; +drawcolumndata_t g_dc = {}; // ----------------------- // translucency stuff here // ----------------------- #define NUMTRANSTABLES 9 // how many translucency tables are used -UINT8 *transtables; // translucency tables -UINT8 *blendtables[NUMBLENDMAPS]; +UINT8 *transtables = NULL; // translucency tables +UINT8 *blendtables[NUMBLENDMAPS] = {}; // -------------------------------------------- // c drawer routines // -------------------------------------------- -coldrawfunc_t *colfunc; -coldrawfunc_t *colfuncs[COLDRAWFUNC_MAX]; -int colfunctype; +coldrawfunc_t *colfunc = NULL; +coldrawfunc_t *colfuncs[COLDRAWFUNC_MAX] = {}; +int colfunctype = 0; // ========================================================================= // SPAN DRAWING CODE STUFF // ========================================================================= -drawspandata_t g_ds; +drawspandata_t g_ds = {}; // Vectors for Software's tilted slope drawers -floatv3_t *ds_su, *ds_sv, *ds_sz; +floatv3_t *ds_su = NULL, *ds_sv = NULL, *ds_sz = NULL; -float focallengthf; +float focallengthf = 0.0f; // For, uh, tilted lighting, duh. //static INT32 *tiltlighting; @@ -83,8 +83,8 @@ float focallengthf; // c drawer routines // -------------------------------------------- -spandrawfunc_t *spanfunc; -spandrawfunc_t *spanfuncs[SPANDRAWFUNC_MAX]; +spandrawfunc_t *spanfunc = NULL; +spandrawfunc_t *spanfuncs[SPANDRAWFUNC_MAX] = {}; // ========================================================================== // OLD DOOM FUZZY EFFECT @@ -105,10 +105,10 @@ spandrawfunc_t *spanfuncs[SPANDRAWFUNC_MAX]; #define DEFAULT_STARTTRANSCOLOR 160 #define NUM_PALETTE_ENTRIES 256 -static UINT8 **translationtablecache[TT_CACHE_SIZE] = {NULL}; -static UINT8 **localtranslationtablecache[MAXLOCALSKINS] = {NULL}; +static UINT8 **translationtablecache[TT_CACHE_SIZE] = {}; +static UINT8 **localtranslationtablecache[MAXLOCALSKINS] = {}; -CV_PossibleValue_t Color_cons_t[MAXSKINCOLORS+1]; +CV_PossibleValue_t Color_cons_t[MAXSKINCOLORS+1] = {}; struct GenerateBlendTables_State { diff --git a/src/r_main.cpp b/src/r_main.cpp index b6d0e7f0f..1887b0381 100644 --- a/src/r_main.cpp +++ b/src/r_main.cpp @@ -49,54 +49,54 @@ // increment every time a check is made size_t validcount = 1; -INT32 centerx, centery; +INT32 centerx = 0, centery = 0; -fixed_t centerxfrac, centeryfrac; -fixed_t projection; -fixed_t projectiony; // aspect ratio -fixed_t fovtan; // field of view +fixed_t centerxfrac = 0, centeryfrac = 0; +fixed_t projection = 0; +fixed_t projectiony = 0; // aspect ratio +fixed_t fovtan = 0; // field of view // just for profiling purposes -size_t framecount; +size_t framecount = 0; -size_t loopcount; +size_t loopcount = 0; -fixed_t viewx, viewy, viewz; -angle_t viewangle, aimingangle, viewroll; +fixed_t viewx = 0, viewy = 0, viewz = 0; +angle_t viewangle = 0, aimingangle = 0, viewroll = 0; UINT8 viewssnum = 0; -fixed_t viewcos, viewsin; -boolean skyVisible; -boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS]; // saved values of skyVisible for each splitscreen player -sector_t *viewsector; -player_t *viewplayer; +fixed_t viewcos = 0, viewsin = 0; +boolean skyVisible = 0; +boolean skyVisiblePerPlayer[MAXSPLITSCREENPLAYERS] = {}; // saved values of skyVisible for each splitscreen player +sector_t *viewsector = NULL; +player_t *viewplayer = NULL; -fixed_t renderdeltatics; -boolean renderisnewtic; +fixed_t renderdeltatics = 0; +boolean renderisnewtic = true; // // precalculated math tables // -angle_t clipangle; -angle_t doubleclipangle; +angle_t clipangle = 0; +angle_t doubleclipangle = 0; // The viewangletox[viewangle + FINEANGLES/4] lookup // maps the visible view angles to screen X coordinates, // flattening the arc to a flat projection plane. // There will be many angles mapped to the same X. -INT32 viewangletox[FINEANGLES/2]; +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 = NULL; -lighttable_t *scalelight[LIGHTLEVELS][MAXLIGHTSCALE]; -lighttable_t *scalelightfixed[MAXLIGHTSCALE]; -lighttable_t *zlight[LIGHTLEVELS][MAXLIGHTZ]; +lighttable_t *scalelight[LIGHTLEVELS][MAXLIGHTSCALE] = {}; +lighttable_t *scalelightfixed[MAXLIGHTSCALE] = {}; +lighttable_t *zlight[LIGHTLEVELS][MAXLIGHTZ] = {}; // Hack to support extra boom colormaps. -size_t num_extra_colormaps; -extracolormap_t extra_colormaps[MAXCOLORMAPS]; +size_t num_extra_colormaps = 0; +extracolormap_t extra_colormaps[MAXCOLORMAPS] = {}; // Performance stats precise_t ps_prevframetime = 0; diff --git a/src/r_patchrotation.cpp b/src/r_patchrotation.cpp index 5d4b5478c..485a8b9f1 100644 --- a/src/r_patchrotation.cpp +++ b/src/r_patchrotation.cpp @@ -23,8 +23,8 @@ // // Angles precalculated in R_InitSprites. // -fixed_t rollcosang[ROTANGLES]; -fixed_t rollsinang[ROTANGLES]; +fixed_t rollcosang[ROTANGLES] = {}; +fixed_t rollsinang[ROTANGLES] = {}; INT32 R_GetRollAngle(angle_t rollangle) { diff --git a/src/r_portal.c b/src/r_portal.c index 432e3f50d..1a5c7c4a8 100644 --- a/src/r_portal.c +++ b/src/r_portal.c @@ -21,16 +21,16 @@ #include "r_things.h" #include "r_sky.h" -UINT8 portalrender; /**< When rendering a portal, it establishes the depth of the current BSP traversal. */ +UINT8 portalrender = 0; /**< When rendering a portal, it establishes the depth of the current BSP traversal. */ // Linked list for portals. -portal_t *portal_base, *portal_cap; +portal_t *portal_base = NULL, *portal_cap = NULL; -line_t *portalclipline; -sector_t *portalcullsector; -INT32 portalclipstart, portalclipend; +line_t *portalclipline = NULL; +sector_t *portalcullsector = NULL; +INT32 portalclipstart = 0, portalclipend = 0; -portal_t *g_portal; // is curline a portal seg? +portal_t *g_portal = NULL; // is curline a portal seg? void Portal_InitList (void) { diff --git a/src/r_segs.cpp b/src/r_segs.cpp index c6cb63bf5..61eac0c35 100644 --- a/src/r_segs.cpp +++ b/src/r_segs.cpp @@ -47,10 +47,10 @@ static INT32 toptexture, bottomtexture, midtexture; static bool topremap, bottomremap, midremap; static INT32 numthicksides, numbackffloors; -angle_t rw_normalangle; +angle_t rw_normalangle = 0; // angle to line origin -angle_t rw_angle1; -fixed_t rw_distance; +angle_t rw_angle1 = 0; +fixed_t rw_distance = 0; // // regular wall diff --git a/src/r_skins.c b/src/r_skins.c index 8a08da7b2..538b8c38a 100644 --- a/src/r_skins.c +++ b/src/r_skins.c @@ -33,7 +33,7 @@ #include "qs22j.h" -CV_PossibleValue_t Forceskin_cons_t[MAXSKINS+2]; // huehuehuehuehue +CV_PossibleValue_t Forceskin_cons_t[MAXSKINS+2] = {}; // huehuehuehuehue #include "discord.h" @@ -55,15 +55,15 @@ UINT8 skinstatscount[9][9] = { {0, 0, 0, 0, 0, 0, 0, 0, 0} }; -UINT8 skinsorted[MAXSKINS]; -skin_t localskins[MAXLOCALSKINS]; -skin_t allskins[MAXSKINS+MAXLOCALSKINS]; +UINT8 skinsorted[MAXSKINS] = {}; +skin_t localskins[MAXLOCALSKINS] = {}; +skin_t allskins[MAXSKINS+MAXLOCALSKINS] = {}; // FIXTHIS: don't work because it must be inistilised before the config load //#define SKINVALUES #ifdef SKINVALUES -CV_PossibleValue_t skin_cons_t[MAXSKINS+1]; -CV_PossibleValue_t localskin_cons_t[MAXLOCALSKINS+1]; +CV_PossibleValue_t skin_cons_t[MAXSKINS+1] = {}; +CV_PossibleValue_t localskin_cons_t[MAXLOCALSKINS+1] = {}; #endif static void Sk_SetDefaultValue(skin_t *skin, boolean local) diff --git a/src/r_sky.c b/src/r_sky.c index 9b0a9262c..795a0f572 100644 --- a/src/r_sky.c +++ b/src/r_sky.c @@ -22,8 +22,6 @@ #include "w_wad.h" #include "z_zone.h" -#include "p_maputl.h" // P_PointOnLineSide - // // sky mapping // @@ -31,28 +29,28 @@ /** \brief Needed to store the number of the dummy sky flat. Used for rendering, as well as tracking projectiles etc. */ -INT32 skyflatnum; +INT32 skyflatnum = 0; /** \brief the lump number of the sky texture */ -INT32 skytexture; +INT32 skytexture = 0; /** \brief the horizon line in a 256x128 sky texture */ -INT32 skytexturemid; +INT32 skytexturemid = 0; /** \brief the x offset of the sky texture */ -INT32 skytextureoffset; +INT32 skytextureoffset = 0; /** \brief the scale of the sky */ -fixed_t skyscale; +fixed_t skyscale = 0; /** \brief used for keeping track of the current sky */ -INT32 levelskynum; -INT32 globallevelskynum; +INT32 levelskynum = 0; +INT32 globallevelskynum = 0; /** \brief The R_SetupSkyDraw function diff --git a/src/r_things.cpp b/src/r_things.cpp index 03eab22c8..3cf92381e 100644 --- a/src/r_things.cpp +++ b/src/r_things.cpp @@ -95,15 +95,15 @@ static INT32 drawsegs_xrange_count = 0; // There was a lot of stuff grabbed wrong, so I changed it... // -spriteinfo_t spriteinfo[NUMSPRITES]; +spriteinfo_t spriteinfo[NUMSPRITES] = {}; // // INITIALIZATION FUNCTIONS // // variables used to look up and range check thing_t sprites patches -spritedef_t *sprites; -size_t numsprites; +spritedef_t *sprites = NULL; +size_t numsprites = 0; static spriteframe_t sprtemp[64]; static size_t maxframe; @@ -112,7 +112,7 @@ static const char *spritename; // // GAME FUNCTIONS // -UINT32 visspritecount, numvisiblesprites; +UINT32 visspritecount = 0, numvisiblesprites = 0; static UINT32 clippedvissprites; static vissprite_t *visspritechunks[MAXVISSPRITES >> VISSPRITECHUNKBITS] = {NULL}; diff --git a/src/screen.c b/src/screen.c index cae7d2479..f588d0e38 100644 --- a/src/screen.c +++ b/src/screen.c @@ -36,8 +36,8 @@ // ------------------ // global video state // ------------------ -viddef_t vid; -INT32 setmodeneeded; // video mode change needed if > 0 (the mode number to set + 1) +viddef_t vid = {}; +INT32 setmodeneeded = 0; // video mode change needed if > 0 (the mode number to set + 1) static CV_PossibleValue_t shittyscreen_cons_t[] = {{0, "Okay"}, {1, "Shitty"}, {2, "Extra Shitty"}, {0, NULL}}; diff --git a/src/v_video.c b/src/v_video.c index 20c98c154..815583dc5 100644 --- a/src/v_video.c +++ b/src/v_video.c @@ -100,7 +100,7 @@ Please check it out if you're trying to maintain this. toast 18/04/17 */ -float Cubepal[2][2][2][3]; +float Cubepal[2][2][2][3] = {}; boolean Cubeapply = false; // returns whether to apply cube, selectively avoiding expensive operations -- 2.54.0 From 2a6a7e1d2b1c7ed67868d3d63f5c663f06eecd65 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 14:16:00 +0100 Subject: [PATCH 104/116] smol optimization R_NoEncore reuse secspecial for invertencore check --- src/r_bsp.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/r_bsp.cpp b/src/r_bsp.cpp index ea0f5c17a..5a0a21d76 100644 --- a/src/r_bsp.cpp +++ b/src/r_bsp.cpp @@ -48,21 +48,30 @@ boolean g_walloffscreen = false; boolean R_NoEncore(sector_t *sector, boolean ceiling) { - boolean invertencore = (GETSECSPECIAL(sector->special, 2) == 12 || GETSECSPECIAL(sector->special, 2) == 15); // keeping this incase its used + const INT32 invspecial = GETSECSPECIAL(sector->special, 2); + boolean invertencore = (invspecial == 12 || invspecial == 15); // keeping this incase its used + #if 0 // perfect implementation - INT32 val = GETSECSPECIAL(sector->special, 3); - if (val != 1 && val != 3 // spring panel + const INT32 sprnspecial = GETSECSPECIAL(sector->special, 3); + if (sprnspecial != 1 && sprnspecial != 3 // spring panel #else // optimised, see #define GETSECSPECIAL(i,j) ((i >> ((j-1)*4))&15) if ((!(sector->special & (1<<8)) || (sector->special & ((4|8)<<8))) // spring panel #endif && GETSECSPECIAL(sector->special, 4) != 6) // sneaker panel - return invertencore; + { + return invertencore; + } if (invertencore) + { return false; + } if (ceiling) + { return ((boolean)(sector->flags & SF_FLIPSPECIAL_CEILING)); + } + return ((boolean)(sector->flags & SF_FLIPSPECIAL_FLOOR)); } -- 2.54.0 From 83d538b16a43c9deed7b891dba0b285b29dbd008 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 14:17:41 +0100 Subject: [PATCH 105/116] gl_viewludsin/viewludcos is only needed for sprite billboarding which is not needed with shearing --- src/hardware/hw_main.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 2db86af78..afce789f6 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -3474,7 +3474,7 @@ static void HWR_DrawSpriteShadow(gl_vissprite_t *spr, patch_t *gpatch, GLPatch_t // This is expecting a pointer to an array containing 4 wallVerts for a sprite static void HWR_RotateSpritePolyToAim(gl_vissprite_t *spr, FOutVector *wallVerts, const boolean precip, const boolean papersprite) { - if (!cv_glspritebillboarding.value || papersprite) + if (!cv_glspritebillboarding.value || cv_glshearing.value || papersprite) { return; } @@ -5310,8 +5310,12 @@ void HWR_SetTransform(float fpov) HWR_SetTransformAiming(&atransform); atransform.angley = (float)(viewangle>>ANGLETOFINESHIFT)*(FINEDEGREE); - gl_viewludsin = FixedToFloat(FINECOSINE(gl_aimingangle>>ANGLETOFINESHIFT)); - gl_viewludcos = FixedToFloat(-FINESINE(gl_aimingangle>>ANGLETOFINESHIFT)); + // only needed for sprite billboarding + if (cv_glspritebillboarding.value && !cv_glshearing.value) + { + gl_viewludsin = FixedToFloat(FINECOSINE(gl_aimingangle>>ANGLETOFINESHIFT)); + gl_viewludcos = FixedToFloat(-FINESINE(gl_aimingangle>>ANGLETOFINESHIFT)); + } atransform.fovangle = fpov; // Tails HWR_RollTransform(&atransform, viewroll); -- 2.54.0 From bcd54110d523333b188df0bba2a8c07a721c38b2 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 14:18:21 +0100 Subject: [PATCH 106/116] only call netkeepalive between calls during gl precache this caused some crashes in blankart, hopefully this is fine though --- src/hardware/hw_cache.c | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/hardware/hw_cache.c b/src/hardware/hw_cache.c index b368fae6c..b4bc067be 100644 --- a/src/hardware/hw_cache.c +++ b/src/hardware/hw_cache.c @@ -615,9 +615,6 @@ static void HWR_PrecacheLevelFlats(void) // go through all sectors to determine if it should be remapped for encore for (i = 0; i < numsectors; i++) { - // prevent timeouts - NetKeepAlive(); - sector_t *sec = §ors[i]; // gotta check sector floor and ceiling @@ -649,9 +646,6 @@ static void HWR_PrecacheLevelFlats(void) // just load every flat in the level for (i = 0; i < numlevelflats; i++) { - // prevent timeouts - NetKeepAlive(); - const levelflat_t *levelflat = &levelflats[i]; lump = levelflat->lumpnum; @@ -688,9 +682,6 @@ static void HWR_PrecacheLevelTextures(void) for (i = 0; i < numlines; i++) { - // prevent timeouts - NetKeepAlive(); - const line_t *line = &lines[i]; #ifdef GLENCORE const int noencoremap = ((encoremap && (line->flags & ML_TFERLINE)) ? 2 : 1); @@ -784,9 +775,6 @@ static void HWR_PrecacheLevelTextures(void) for (i = 0; i < numsprites; i++) { - // prevent timeouts - NetKeepAlive(); - if (!spritepresent[i]) continue; @@ -830,11 +818,20 @@ void HWR_PrecacheLevel(void) // Precache flats. HWR_PrecacheLevelFlats(); + // prevent timeouts + NetKeepAlive(); + // Precache textures. HWR_PrecacheLevelTextures(); + // prevent timeouts + NetKeepAlive(); + // Precache sprites. //HWR_PrecacheLevelSprites(); + + // prevent timeouts + //NetKeepAlive(); } void HWR_LoadMapTextures(size_t pnumtextures) -- 2.54.0 From d93419724630e76cdce8a126307e9a6baeadf1c1 Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 14:48:59 +0100 Subject: [PATCH 107/116] git merge pls --- src/d_main.c | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/d_main.c b/src/d_main.c index 7a738288b..14b205418 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -166,6 +166,57 @@ UINT8 ctrldown = 0; // 0x1 left, 0x2 right UINT8 altdown = 0; // 0x1 left, 0x2 right boolean capslock = 0; // gee i wonder what this does. +static void D_PadMenuScrollInput(UINT8 input) +{ + event_t dpadev; + memset(&dpadev, 0, sizeof(event_t)); + dpadev.type = ev_keydown; + + switch (input) + { + case DPAD_UP: + dpadev.data1 = KEY_UPARROW; + break; + case DPAD_DOWN: + dpadev.data1 = KEY_DOWNARROW; + break; + case DPAD_LEFT: + dpadev.data1 = KEY_LEFTARROW; + break; + case DPAD_RIGHT: + dpadev.data1 = KEY_RIGHTARROW; + break; + } + + D_PostEvent(&dpadev); // put into eventlist +} + +#define SCROLLDELAY 19 + +// Check if any dpad button is held +// and pass it to the eventlist +static void D_GamePadMenuScrollTicker(void) +{ + UINT8 i; + static UINT8 menuInputDelayTimer = 0; + + for (i = 0; i < MAXSPLITSCREENPLAYERS; i++) + { + if (dpadscrollstate[i]) + { + if (menuInputDelayTimer < SCROLLDELAY) + menuInputDelayTimer++; + else if (menuInputDelayTimer == SCROLLDELAY) + D_PadMenuScrollInput(i); + + return; + } + } + + menuInputDelayTimer = 0; +} +#undef SCROLLDELAY + static UINT16 curcolor[MAXSPLITSCREENPLAYERS] = {}; static void D_DeviceLEDTick(void) -- 2.54.0 From c080fc873247280c5c677f5381ae677abe2d320c Mon Sep 17 00:00:00 2001 From: Alug Date: Tue, 11 Nov 2025 22:39:13 +0100 Subject: [PATCH 108/116] GL_UpdateTexture: fix small oversight from when i refactored it GL_TEXFMT_AP_88 needs to increment the image data ptr even if chromakeyed --- src/hardware/r_opengl/r_opengl.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 566d2458c..cb7eca43c 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -2004,7 +2004,7 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) { if (chromakeyed && (*pImgData == HWR_PATCHES_CHROMAKEY_COLORINDEX)) { - tex[idx].s = (byteColor_t){0, 0, 0, 0}; + memset(&tex[idx].s, 0, sizeof(byteColor_t)); pTexInfo->flags |= TF_TRANSPARENT; // there is a hole in it } else @@ -2016,10 +2016,9 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) if (texinfoformat != GL_TEXFMT_AP_88) continue; - if (chromakeyed) - continue; - tex[idx].s.alpha = *pImgData; + if (!chromakeyed) + tex[idx].s.alpha = *pImgData; pImgData++; } } @@ -2054,9 +2053,9 @@ void GL_UpdateTexture(GLMipmap_t *pTexInfo) { for (i = 0; i < w; i++, idx++) { - tex[idx].s.red = *pImgData; - tex[idx].s.green = *pImgData; - tex[idx].s.blue = *pImgData; + tex[idx].s.red = + tex[idx].s.green = + tex[idx].s.blue = *pImgData; pImgData++; tex[idx].s.alpha = *pImgData; pImgData++; @@ -3187,7 +3186,8 @@ void GL_SetTransform(FTransform *stransform) { float dy = stransform->viewaiming * 2; - if (stransform->fliptype == TRANSFORM_FLIP || stransform->fliptype == TRANSFORM_MIRRORFLIP) + if (stransform->fliptype == TRANSFORM_FLIP + || stransform->fliptype == TRANSFORM_MIRRORFLIP) dy *= -1.0f; pglTranslatef(0.0f, -dy/BASEVIDHEIGHT, 0.0f); -- 2.54.0 From c58e54544d1dc5cade58dc8d4c0fedb373d7f0d2 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 12 Nov 2025 16:49:44 +0100 Subject: [PATCH 109/116] initialize all remaining globals well atleast all i can find lel --- src/command.c | 2 +- src/console.c | 8 +++--- src/dehacked.c | 6 ++--- src/f_finale.c | 2 +- src/filesrch.c | 10 ++++---- src/hardware/r_opengl/r_opengl.c | 11 ++++---- src/hu_stuff.c | 44 ++++++++++++++++---------------- src/lua_script.c | 2 +- src/m_argv.c | 4 +-- src/m_cond.c | 4 +-- src/m_menu.c | 13 +++------- src/m_menu.h | 3 --- src/mserv.c | 4 +-- src/p_ceilng.c | 3 --- src/p_local.h | 2 -- src/p_polyobj.c | 10 ++++---- src/p_slopes.c | 3 +-- src/sdl/i_main.c | 2 +- src/sdl/i_system.cpp | 2 +- src/sdl/i_video.c | 6 ++--- src/sounds.c | 2 +- src/st_stuff.c | 18 ++++++------- src/w_wad.c | 2 +- 23 files changed, 75 insertions(+), 88 deletions(-) diff --git a/src/command.c b/src/command.c index 459938aa8..d12ae5d49 100644 --- a/src/command.c +++ b/src/command.c @@ -277,7 +277,7 @@ static xcommand_t *com_commands = NULL; // current commands #define MAX_ARGS 80 static size_t com_argc; -char *com_argv[MAX_ARGS]; +char *com_argv[MAX_ARGS] = {}; static const char *com_null_string = ""; static char *com_args = NULL; // current command args or NULL diff --git a/src/console.c b/src/console.c index 3172b9f20..2757b22e7 100644 --- a/src/console.c +++ b/src/console.c @@ -58,7 +58,7 @@ I_mutex con_mutex; static boolean con_started = false; // console has been initialised boolean con_startup = false; // true at game startup, screen need refreshing static boolean con_forcepic = true; // at startup toggle console translucency when first off - boolean con_recalc; // set true when screen size has changed + boolean con_recalc = false; // set true when screen size has changed static tic_t con_tick; // console ticker for anim or blinking prompt cursor // con_scrollup should use time (currenttime - lasttime).. @@ -66,8 +66,8 @@ static tic_t con_tick; // console ticker for anim or blinking prompt cursor static boolean consoletoggle; // true when console key pushed, ticker will handle 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_destlines = 0; // vid lines used by console at final position +static INT32 con_curlines; // vid lines currently used by console static UINT8 con_hudlines; // number of console heads up message lines static UINT32 con_hudtime[MAXHUDLINES]; // remaining time of display for hud msg lines @@ -83,7 +83,7 @@ static size_t con_totallines; // lines of console text into the console buf static size_t con_width; // columns of chars, depend on vid mode width static size_t con_scrollup; // how many rows of text to scroll up (pgup/pgdn) -UINT32 con_scalefactor; // text size scale factor +UINT32 con_scalefactor = 0; // text size scale factor // hold 32 last lines of input for history #define CON_MAXPROMPTCHARS 256 diff --git a/src/dehacked.c b/src/dehacked.c index 1e2fd5798..a3540fdff 100644 --- a/src/dehacked.c +++ b/src/dehacked.c @@ -47,9 +47,9 @@ // Free slot names // The crazy word-reading stuff uses these. -char *FREE_STATES[NUMSTATEFREESLOTS]; -char *FREE_MOBJS[NUMMOBJFREESLOTS]; -UINT8 used_spr[(NUMSPRITEFREESLOTS / 8) + 1]; // Bitwise flag for sprite freeslot in use! I would use ceil() here if I could, but it only saves 1 byte of memory anyway. +char *FREE_STATES[NUMSTATEFREESLOTS] = {}; +char *FREE_MOBJS[NUMMOBJFREESLOTS] = {}; +UINT8 used_spr[(NUMSPRITEFREESLOTS / 8) + 1] = {}; // Bitwise flag for sprite freeslot in use! I would use ceil() here if I could, but it only saves 1 byte of memory anyway. #define initfreeslots() {\ memset(FREE_STATES,0,sizeof(char *) * NUMSTATEFREESLOTS);\ diff --git a/src/f_finale.c b/src/f_finale.c index ca22349a0..450910021 100644 --- a/src/f_finale.c +++ b/src/f_finale.c @@ -208,7 +208,7 @@ static void F_SkyScroll(INT32 scrollspeed) INT32 intro_scenenum = 0; INT32 intro_curtime = 0; -const char *introtext[NUMINTROSCENES]; +const char *introtext[NUMINTROSCENES] = {}; static tic_t introscenetime[NUMINTROSCENES] = { diff --git a/src/filesrch.c b/src/filesrch.c index eb68222e2..c0940b2eb 100644 --- a/src/filesrch.c +++ b/src/filesrch.c @@ -44,16 +44,16 @@ 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[MAXFILEPATH]; -size_t menupathindex[menudepth]; +char menupath[MAXFILEPATH] = {}; +size_t menupathindex[menudepth] = {}; size_t menudepthleft = menudepth; char menusearchbuf[MAXSTRINGLENGTH+1]; textinput_t menusearch; -char **dirmenu, **coredirmenu; // core only local for this file -size_t sizedirmenu, sizecoredirmenu; // ditto -size_t dir_on[menudepth]; +char **dirmenu = NULL, **coredirmenu = NULL; // core only local for this file +size_t sizedirmenu = 0, sizecoredirmenu = 0; // ditto +size_t dir_on[menudepth] = {}; UINT8 refreshdirmenu = 0; char *refreshdirname = NULL; diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index cb7eca43c..80697eb8c 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -25,7 +25,7 @@ // Eeeeh not sure is this right way, but it works < sry :c < sry again it had to go :c -#if defined (HWRENDER) && !defined (NOROPENGL) +#if defined (HWRENDER) #include "../../r_fps.h" // For R_GetTimeFrac, used for the leveltime shader uniform @@ -101,7 +101,7 @@ static LTListItem *LightTablesHead = NULL; static RGBA_t screenPalette[256] = {0}; // the palette for the postprocessing step in palette rendering static GLuint screenPaletteTex = 0; // 1D texture containing the screen palette static GLuint paletteLookupTex = 0; // 3D texture containing RGB -> palette index lookup table -RGBA_t myPaletteData[256]; // the palette for converting textures to RGBA +RGBA_t myPaletteData[256] = {0}; // the palette for converting textures to RGBA static GLint gltexformat = GL_RGB5_A1; GLint screen_width = 0; // used by Draw2DLine() @@ -128,7 +128,7 @@ int majorGL = 0, minorGL = 0; //Hurdler: 04/10/2000: added for the kick ass coronas as Boris wanted;-) static GLfloat modelMatrix[16]; -GLfloat projMatrix[16]; +GLfloat projMatrix[16] = {0}; static GLint viewport[4]; #ifdef USE_FBO_OGL @@ -216,7 +216,7 @@ static const GLfloat byte2float[256] = { // -----------------+ #ifdef DEBUG_TO_FILE -FILE *gllogstream; +FILE *gllogstream = NULL; #endif FUNCPRINTF void GL_DBG_Printf(const char *format, ...) @@ -1138,7 +1138,6 @@ static void GL_Perspective(GLfloat fovy, GLfloat aspect) { 0.0f, 0.0f, 0.0f, 0.0f}, }; - const GLfloat focallength = (GLfloat)(1.0f / (GLfloat)tan(fovy * (GLfloat)M_PIl / 360.0f)); const GLfloat deltaZ = FAR_CLIPPING_PLANE - NEAR_CLIPPING_PLANE; if ((fabsf((float)deltaZ) < 1.0E-36f) || fpclassify(aspect) == FP_ZERO) @@ -1146,6 +1145,8 @@ static void GL_Perspective(GLfloat fovy, GLfloat aspect) return; } + const GLfloat focallength = (GLfloat)(1.0f / (GLfloat)tan(fovy * (GLfloat)M_PIl / 360.0f)); + m[0][0] = focallength / aspect; m[1][1] = focallength; m[2][2] = -(FAR_CLIPPING_PLANE + NEAR_CLIPPING_PLANE) / deltaZ; diff --git a/src/hu_stuff.c b/src/hu_stuff.c index 955bebb2f..8819d63b4 100644 --- a/src/hu_stuff.c +++ b/src/hu_stuff.c @@ -68,32 +68,32 @@ //------------------------------------------- // heads up font //------------------------------------------- -patch_t *hu_font[HU_FONTSIZE]; -patch_t *kart_font[KART_FONTSIZE]; // SRB2kart -patch_t *tny_font[HU_FONTSIZE]; -patch_t *tallnum[10]; // 0-9 +patch_t *hu_font[HU_FONTSIZE] = {}; +patch_t *kart_font[KART_FONTSIZE] = {}; // SRB2kart +patch_t *tny_font[HU_FONTSIZE] = {}; +patch_t *tallnum[10] = {}; // 0-9 // Level title and credits fonts -patch_t *lt_font[LT_FONTSIZE]; -patch_t *cred_font[CRED_FONTSIZE]; +patch_t *lt_font[LT_FONTSIZE] = {}; +patch_t *cred_font[CRED_FONTSIZE] = {}; // ping font // Note: I'd like to adress that at this point we might *REALLY* want to work towards a common drawString function that can take any font we want because this is really turning into a MESS. :V -Lat' -patch_t *pingnum[10]; -patch_t *pinggfx[5]; // small ping graphic -patch_t *pingmeasure[2]; // ping measurement graphic +patch_t *pingnum[10] = {}; +patch_t *pinggfx[5] = {}; // small ping graphic +patch_t *pingmeasure[2] = {}; // ping measurement graphic -patch_t *ranknum[10]; // rank numbers +patch_t *ranknum[10] = {}; // rank numbers -patch_t *framecounter; -patch_t *frameslash; // framerate stuff. Used in screen.c +patch_t *framecounter = NULL; +patch_t *frameslash = NULL; // framerate stuff. Used in screen.c -static player_t *plr; -boolean chat_on; // entering a chat message? +static player_t *plr = NULL; +boolean chat_on = false; // entering a chat message? static char w_chat_buf[HU_MAXMSGLEN + 1]; static textinput_t w_chat; static boolean headsupactive = false; -boolean hu_showscores; // draw rankings +boolean hu_showscores = false; // draw rankings static char hu_tick; static tic_t hu_emoteanim = 0; #define MAXEMOTESUGGESTIONS 8 @@ -101,14 +101,14 @@ static emote_t *emote_suggestions[MAXEMOTESUGGESTIONS] = {0}; static huddrawlist_h luahuddrawlist_scores; -patch_t *rflagico; -patch_t *bflagico; -patch_t *rmatcico; -patch_t *bmatcico; -patch_t *tallminus; +patch_t *rflagico = NULL; +patch_t *bflagico = NULL; +patch_t *rmatcico = NULL; +patch_t *bmatcico = NULL; +patch_t *tallminus = NULL; // song credits -static patch_t *songcreditbg; +static patch_t *songcreditbg = NULL; // ------- // protos. @@ -122,7 +122,7 @@ consvar_t cv_showspecstuff = {"showspecstuff", "No", CV_SAVE, CV_YesNo, NULL, 0, // KEYBOARD LAYOUTS FOR ENTERING TEXT //====================================================================== -char *shiftxform; +char *shiftxform = NULL; char english_shiftxform[] = { diff --git a/src/lua_script.c b/src/lua_script.c index 448d7221d..96ce94a22 100644 --- a/src/lua_script.c +++ b/src/lua_script.c @@ -41,7 +41,7 @@ lua_State *gL = NULL; // Mathlib global state static lua_State *mL = NULL; -int hook_defrosting; +int hook_defrosting = 0; // List of internal libraries to load from SRB2 static lua_CFunction liblist[] = { diff --git a/src/m_argv.c b/src/m_argv.c index b62d390d9..36c73d61c 100644 --- a/src/m_argv.c +++ b/src/m_argv.c @@ -20,11 +20,11 @@ /** \brief number of arg */ -INT32 myargc; +INT32 myargc = 0; /** \brief string table */ -char **myargv; +char **myargv = NULL; /** \brief did we alloc myargv ourselves? */ diff --git a/src/m_cond.c b/src/m_cond.c index f9d871969..acf78e6ef 100644 --- a/src/m_cond.c +++ b/src/m_cond.c @@ -25,10 +25,10 @@ // Map triggers for linedef executors // 32 triggers, one bit each -UINT32 unlocktriggers; +UINT32 unlocktriggers = 0; // The meat of this system lies in condition sets -conditionset_t conditionSets[MAXCONDITIONSETS]; +conditionset_t conditionSets[MAXCONDITIONSETS] = {}; // Default Emblem locations emblem_t emblemlocations[MAXEMBLEMS] = diff --git a/src/m_menu.c b/src/m_menu.c index 09a0c6350..cd5aa04b6 100644 --- a/src/m_menu.c +++ b/src/m_menu.c @@ -145,19 +145,19 @@ I_mutex m_menu_mutex; M_waiting_mode_t m_waiting_mode = M_NOT_WAITING; -const char *quitmsg[NUM_QUITMESSAGES]; +const char *quitmsg[NUM_QUITMESSAGES] = {}; // Stuff for customizing the player select screen Tails 09-22-2003 -description_t description[MAXSKINS]; +description_t description[MAXSKINS] = {}; -INT32 mapwads[NUMMAPS]; +INT32 mapwads[NUMMAPS] = {}; boolean browselocalskins = false; boolean menuactive = false; boolean fromlevelselect = false; -char menu_text_input_buf[MAXSTRINGLENGTH]; +char menu_text_input_buf[MAXSTRINGLENGTH] = {}; static textinput_t menuinput; static INT32 coolalphatimer = 9; @@ -171,7 +171,6 @@ typedef enum } levellist_mode_t; levellist_mode_t levellistmode = LLM_CREATESERVER; -UINT8 maplistoption = 0; static char joystickInfo[8][29]; @@ -181,10 +180,6 @@ static float serverlistslidex; static INT32 serverlistsearched[MAXSERVERLIST] = {0}; static UINT32 serverlistsearchedcount = 0; -//static saveinfo_t savegameinfo[MAXSAVEGAMES]; // Extra info about the save games. - -INT16 startmap; // Mario, NiGHTS, or just a plain old normal game? - static INT16 itemOn = 1; // menu item skull is on, Hack by Tails 09-18-2002 static INT16 skullAnimCounter = 10; // skull animation counter static boolean interpTimerHackAllow = 0; diff --git a/src/m_menu.h b/src/m_menu.h index de4f3b983..8391ef994 100644 --- a/src/m_menu.h +++ b/src/m_menu.h @@ -282,9 +282,6 @@ extern CV_PossibleValue_t gametype_cons_t[]; extern char dummystaffname[22]; -extern INT16 startmap; -extern INT32 ultimate_selectable; - #define MAXSAVEGAMES 31 //note: last save game is "no save" #define NOSAVESLOT MAXSAVEGAMES-1 //slot where Play Without Saving appears diff --git a/src/mserv.c b/src/mserv.c index c7eb50442..4de05216e 100644 --- a/src/mserv.c +++ b/src/mserv.c @@ -89,10 +89,10 @@ consvar_t cv_masterserver_nagattempts = {"masterserver_nagattempts", "5", CV_SAV #if defined (MASTERSERVER) && defined (HAVE_THREADS) -int ms_QueryId; +int ms_QueryId = 0; I_mutex ms_QueryId_mutex; -msg_server_t *ms_ServerList; +msg_server_t *ms_ServerList = NULL; I_mutex ms_ServerList_mutex; #endif diff --git a/src/p_ceilng.c b/src/p_ceilng.c index 8170343c9..a00d78008 100644 --- a/src/p_ceilng.c +++ b/src/p_ceilng.c @@ -24,9 +24,6 @@ // CEILINGS // ========================================================================== -// the list of ceilings moving currently, including crushers -INT32 ceilmovesound = sfx_None; - /** Moves a moving ceiling. * * \param ceiling Thinker for the ceiling to be moved. diff --git a/src/p_local.h b/src/p_local.h index dc101502f..6977cc4b1 100644 --- a/src/p_local.h +++ b/src/p_local.h @@ -474,8 +474,6 @@ void P_DoNightsScore(player_t *player); // #include "p_spec.h" -extern INT32 ceilmovesound; - // Factor to scale scrolling effect into mobj-carrying properties = 3/32. // (This is so scrolling floors and objects on them can move at same speed.) #define CARRYFACTOR (FRACUNIT-ORIG_FRICTION) diff --git a/src/p_polyobj.c b/src/p_polyobj.c index 5e5590ced..15090a7ea 100644 --- a/src/p_polyobj.c +++ b/src/p_polyobj.c @@ -90,14 +90,14 @@ // // The Polyobjects -polyobj_t *PolyObjects; -INT32 numPolyObjects; +polyobj_t *PolyObjects = NULL; +INT32 numPolyObjects = 0; // Polyobject Blockmap -- initialized in P_LoadBlockMap -polymaplink_t **polyblocklinks; +polymaplink_t **polyblocklinks = NULL; -static size_t *KnownPolySides; -static size_t KnownPolySidesCount; +static size_t *KnownPolySides = NULL; +static size_t KnownPolySidesCount = 0; // // Static Data diff --git a/src/p_slopes.c b/src/p_slopes.c index 850813331..2ec2898b9 100644 --- a/src/p_slopes.c +++ b/src/p_slopes.c @@ -38,7 +38,6 @@ static void P_UpdateSlopeLightOffset(pslope_t *slope) fixed_t light = FRACUNIT; fixed_t extralight = 0; - if (slope->normal.z == 0) { slope->lightOffset = 0; @@ -296,7 +295,7 @@ static fixed_t P_GetExtent(sector_t *sector, line_t *line) // Find furthest vertex from the reference line. It, along with the two ends // of the line, will define the plane. - for(i = 0; i < sector->linecount; i++) + for (i = 0; i < sector->linecount; i++) { line_t *li = sector->lines[i]; vertex_t tempv; diff --git a/src/sdl/i_main.c b/src/sdl/i_main.c index b2ab7777f..cc04dc6a6 100644 --- a/src/sdl/i_main.c +++ b/src/sdl/i_main.c @@ -53,7 +53,7 @@ extern int SDL_main(int argc, char *argv[]); #ifdef LOGMESSAGES FILE *logstream = NULL; -char logfilename[1024]; +char logfilename[1024] = {}; #endif #ifndef DOXYGEN diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 5281a7f01..272379aa8 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -227,7 +227,7 @@ typedef struct char buffer[256]; } feild_t; -feild_t tty_con; +feild_t tty_con = {}; // lock to prevent clearing partial lines, since not everything // printed ends on a newline. diff --git a/src/sdl/i_video.c b/src/sdl/i_video.c index 787ce1b07..0410dc442 100644 --- a/src/sdl/i_video.c +++ b/src/sdl/i_video.c @@ -151,9 +151,9 @@ static UINT32 localPalette[256]; Uint16 realwidth = BASEVIDWIDTH; Uint16 realheight = BASEVIDHEIGHT; #define HalfWarpMouse(x,y) if (wrapmouseok) SDL_WarpMouseInWindow(window, (Uint16)(x/2),(Uint16)(y/2)) -static SDL_bool exposevideo = SDL_FALSE; -static SDL_bool usesdl2soft = SDL_FALSE; -static SDL_bool borderlesswindow = SDL_FALSE; +static SDL_bool exposevideo = SDL_FALSE; +static SDL_bool usesdl2soft = SDL_FALSE; +static SDL_bool borderlesswindow = SDL_FALSE; // SDL2 vars SDL_Window *window = NULL; diff --git a/src/sounds.c b/src/sounds.c index c1e2f83a7..dbd5478bd 100644 --- a/src/sounds.c +++ b/src/sounds.c @@ -972,7 +972,7 @@ sfxinfo_t S_sfx[NUMSFX] = // initialized to NULL }; -char freeslotnames[sfx_freeslot0 + NUMSFXFREESLOTS + NUMSKINSFXSLOTS][7]; +char freeslotnames[sfx_freeslot0 + NUMSFXFREESLOTS + NUMSKINSFXSLOTS][7] = {}; // Prepare free sfx slots to add sfx at run time void S_InitRuntimeSounds (void) diff --git a/src/st_stuff.c b/src/st_stuff.c index a4b3d0465..99188e919 100644 --- a/src/st_stuff.c +++ b/src/st_stuff.c @@ -61,13 +61,13 @@ tic_t directortoggletimer = 0; // STATUS BAR DATA // -patch_t *facerankprefix[MAXSKINS]; // ranking -patch_t *facewantprefix[MAXSKINS]; // wanted -patch_t *facemmapprefix[MAXSKINS]; // minimap +patch_t *facerankprefix[MAXSKINS] = {}; // ranking +patch_t *facewantprefix[MAXSKINS] = {}; // wanted +patch_t *facemmapprefix[MAXSKINS] = {}; // minimap -patch_t *localfacerankprefix[MAXLOCALSKINS]; // ranking -patch_t *localfacewantprefix[MAXLOCALSKINS]; // wanted -patch_t *localfacemmapprefix[MAXLOCALSKINS]; // minimap +patch_t *localfacerankprefix[MAXLOCALSKINS] = {}; // ranking +patch_t *localfacewantprefix[MAXLOCALSKINS] = {}; // wanted +patch_t *localfacemmapprefix[MAXLOCALSKINS] = {}; // minimap /*char *facerankprefix_name[MAXSKINS]; // ranking char *facewantprefix_name[MAXSKINS]; // wanted @@ -91,8 +91,8 @@ static patch_t *envelope; #endif // current player for overlay drawing -player_t *stplyr; -UINT8 stplyrnum; +player_t *stplyr = NULL; +UINT8 stplyrnum = 0; // SRB2kart @@ -342,7 +342,7 @@ void ST_changeDemoView(void) // STATUS BAR OVERLAY // ========================================================================= -boolean st_overlay; +boolean st_overlay = true; // ========================================================================= // INTERNAL DRAWING diff --git a/src/w_wad.c b/src/w_wad.c index b55d0e98f..640ee0367 100644 --- a/src/w_wad.c +++ b/src/w_wad.c @@ -107,7 +107,7 @@ static const char pat_end[] = {0x50, 0x4b, 0x05, 0x06, 0x00}; // GLOBALS //=========================================================================== UINT16 numwadfiles = 0; // number of active wadfiles -wadfile_t *wadfiles[MAX_WADFILES]; // 0 to numwadfiles-1 are valid +wadfile_t *wadfiles[MAX_WADFILES] = {}; // 0 to numwadfiles-1 are valid // W_Shutdown // Closes all of the WAD files before quitting -- 2.54.0 From b779c9e63d28c228817fda203ed7fb99b82786da Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 12 Nov 2025 19:04:26 +0100 Subject: [PATCH 110/116] ensure byteColor_t is packed make sure it is always sized 4 bytes and not padded at all since that is assumed to be the size --- src/doomtype.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/doomtype.h b/src/doomtype.h index 78867ed69..8043b7285 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -293,7 +293,7 @@ typedef struct UINT8 green; UINT8 blue; UINT8 alpha; -} byteColor_t; +} ATTRPACK byteColor_t; union FColorRGBA { -- 2.54.0 From aa985823ba451838206435552203d8c6885c6f23 Mon Sep 17 00:00:00 2001 From: Alug Date: Wed, 12 Nov 2025 19:20:29 +0100 Subject: [PATCH 111/116] speed up GL_SetPalette "take 2" ensuring bytecolor is packed nd mypalettedata is initialized this seems to now work properly on windows --- src/hardware/r_opengl/r_opengl.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index 80697eb8c..b8466ee3a 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -1499,14 +1499,14 @@ void GL_ReadScreenTexture(int tex, UINT8 *restrict dest, INT32 scale) // -----------------+ void GL_SetPalette(RGBA_t *palette) { - INT32 i; + const size_t palsize = (sizeof(RGBA_t) * 256); - for (i = 0; i < 256; i++) + // on a palette change, you have to reload all of the textures + if (memcmp(myPaletteData, palette, palsize)) { - myPaletteData[i].s = palette[i].s; + memcpy(myPaletteData, palette, palsize); + GL_Flush(); } - - GL_Flush(); } // -----------------+ -- 2.54.0 From dfca24b37093dc2bc2e5df85377f45e1d9691f91 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 13 Nov 2025 14:53:12 +0100 Subject: [PATCH 112/116] HWR_SkyDomeVertex: tiny optimization save a tiny bit of float division, use float sin and cos functions, handle implicit float conversions --- src/hardware/hw_main.cpp | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index afce789f6..a2539cc7d 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -5067,42 +5067,46 @@ static void HWR_ProjectPrecipitationSprite(precipmobj_t *thing) static gl_sky_t gl_sky; -#define DEG2RADGL(a) ((a * M_PIl) / 180.0f) - static void HWR_SkyDomeVertex(gl_sky_t *sky, gl_skyvertex_t *vbo, int r, int c, signed char yflip, float delta, boolean foglayer) { + static constexpr float radians = (float)(M_PIl / 180.0f); static constexpr float scale = 10000.0f; - static constexpr float maxSideAngle = DEG2RADGL(60.0f); + static constexpr float maxSideAngle = 60.0f * radians; - float topAngle = DEG2RADGL(c / (float)sky->columns * 360.0f); + float topAngle = ((float)c / (float)sky->columns * 360.0f) * radians; float sideAngle = (maxSideAngle * (float)(sky->rows - r) / (float)sky->rows); - float height = (float)(sin(sideAngle)); - float realRadius = (scale * (float)cos(sideAngle)); - float x = (realRadius * (float)cos(topAngle)); + float height = sinf(sideAngle); + float realRadius = (scale * cosf(sideAngle)); + float x = (realRadius * cosf(topAngle)); float y = (!yflip) ? scale * height : -scale * height; - float z = (realRadius * (float)sin(topAngle)); - float timesRepeat = (4 * (256.0f / sky->width)); - - if (std::fpclassify(timesRepeat) == FP_ZERO) - timesRepeat = 1.0f; + float z = (realRadius * sinf(topAngle)); + float timesRepeat; if (!foglayer) { + timesRepeat = (4.0f * (256.0f / (float)sky->width)); + + if (std::fpclassify(timesRepeat) == FP_ZERO) + timesRepeat = 1.0f; + vbo->r = 255; vbo->g = 255; vbo->b = 255; vbo->a = (r == 0 ? 0 : 255); // And the texture coordinates. - vbo->u = (-timesRepeat * c / (float)sky->columns); - if (!yflip) // Flipped Y is for the lower hemisphere. - vbo->v = (r / (float)sky->rows) + 0.5f; + vbo->u = (-timesRepeat * (float)c / (float)sky->columns); + + if (!yflip) // Flipped Y is for the lower hemisphere. + vbo->v = ((float)r / (float)sky->rows) + 0.5f; else - vbo->v = 1.0f + ((sky->rows - r) / (float)sky->rows) + 0.5f; + vbo->v = 1.0f + ((float)(sky->rows - r) / (float)sky->rows) + 0.5f; } if (r != 4) + { y += 300.0f; + } // And finally the vertex. vbo->x = x; -- 2.54.0 From 4e8865d4957894ff9bbb1ef0beb03f253212632d Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 13 Nov 2025 17:37:30 +0100 Subject: [PATCH 113/116] cleanup some wonky float/double maths --- src/dedicated/i_system.c | 42 ++++++++++++++++++-------------- src/hardware/hw_main.cpp | 24 +++++++++--------- src/hardware/r_opengl/r_opengl.c | 14 +++++------ src/sdl/i_system.cpp | 34 ++++++++++++++------------ 4 files changed, 63 insertions(+), 51 deletions(-) diff --git a/src/dedicated/i_system.c b/src/dedicated/i_system.c index d2ffa12ad..fe8889405 100644 --- a/src/dedicated/i_system.c +++ b/src/dedicated/i_system.c @@ -808,20 +808,23 @@ static void I_SetupMumble(void) void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) { #ifdef HAVE_MUMBLE - double angle; + float angle; fixed_t anglef; if (!mumble) return; - if (mumble->uiVersion != 2) { - wcsncpy(mumble->name, L"SRB2Kart "VERSIONSTRINGW, 256); + if (mumble->uiVersion != 2) + { + wcsncpy(mumble->name, L"SRB2Kart " VERSIONSTRINGW, 256); wcsncpy(mumble->description, L"Sonic Robo Blast 2 Kart with integrated Mumble Link support.", 2048); mumble->uiVersion = 2; } mumble->uiTick++; - if (!netgame || gamestate != GS_LEVEL) { // Zero out, but never delink. + // Zero out, but never delink. + if (!netgame || gamestate != GS_LEVEL) + { mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f; mumble->fAvatarFront[0] = 1.0f; mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f; @@ -838,31 +841,34 @@ void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) mumble->context_len = (UINT32)(p - mumble->context); } - if (mobj) { - mumble->fAvatarPosition[0] = FIXED_TO_FLOAT(mobj->x) / MUMBLEUNIT; - mumble->fAvatarPosition[1] = FIXED_TO_FLOAT(mobj->z) / MUMBLEUNIT; - mumble->fAvatarPosition[2] = FIXED_TO_FLOAT(mobj->y) / MUMBLEUNIT; + if (mobj) + { + mumble->fAvatarPosition[0] = FixedToFloat(mobj->x) / MUMBLEUNIT; + mumble->fAvatarPosition[1] = FixedToFloat(mobj->z) / MUMBLEUNIT; + mumble->fAvatarPosition[2] = FixedToFloat(mobj->y) / MUMBLEUNIT; anglef = AngleFixed(mobj->angle); - angle = FIXED_TO_FLOAT(anglef)*DEG2RAD; - mumble->fAvatarFront[0] = (float)cos(angle); + angle = (float)(FixedToFloat(anglef) * DEG2RAD); + mumble->fAvatarFront[0] = cosf(angle); mumble->fAvatarFront[1] = 0.0f; - mumble->fAvatarFront[2] = (float)sin(angle); - } else { + mumble->fAvatarFront[2] = sinf(angle); + } + else + { mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f; mumble->fAvatarFront[0] = 1.0f; mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f; } - mumble->fCameraPosition[0] = FIXED_TO_FLOAT(listener.x) / MUMBLEUNIT; - mumble->fCameraPosition[1] = FIXED_TO_FLOAT(listener.z) / MUMBLEUNIT; - mumble->fCameraPosition[2] = FIXED_TO_FLOAT(listener.y) / MUMBLEUNIT; + mumble->fCameraPosition[0] = FixedToFloat(listener.x) / MUMBLEUNIT; + mumble->fCameraPosition[1] = FixedToFloat(listener.z) / MUMBLEUNIT; + mumble->fCameraPosition[2] = FixedToFloat(listener.y) / MUMBLEUNIT; anglef = AngleFixed(listener.angle); - angle = FIXED_TO_FLOAT(anglef)*DEG2RAD; - mumble->fCameraFront[0] = (float)cos(angle); + angle = (float)(FixedToFloat(anglef) * DEG2RAD); + mumble->fCameraFront[0] = cosf(angle); mumble->fCameraFront[1] = 0.0f; - mumble->fCameraFront[2] = (float)sin(angle); + mumble->fCameraFront[2] = sinf(angle); #else (void)mobj; (void)listener; diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index a2539cc7d..8dc4d3804 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -5940,31 +5940,33 @@ static void HWR_DoPostProcessor(player_t *player) float disStart = (leveltime-1) + FixedToFloat(R_GetTimeFrac(RTF_LEVEL)); UINT8 x, y; - INT32 WAVELENGTH; - INT32 AMPLITUDE; - INT32 FREQUENCY; + float WAVELENGTH; + float AMPLITUDE; + float FREQUENCY; // Modifies the wave. if (thiscam->postimg & POSTIMG_WATER) { - WAVELENGTH = 5; - AMPLITUDE = 40; - FREQUENCY = 8; + WAVELENGTH = 5.0f; + AMPLITUDE = 40.0f; + FREQUENCY = 8.0f; } else { - WAVELENGTH = 10; - AMPLITUDE = 60; - FREQUENCY = 4; + WAVELENGTH = 10.0f; + AMPLITUDE = 60.0f; + FREQUENCY = 4.0f; } + //static constexpr float scale = ((float)SCREENVERTS - 1.0f) / 9.0f; // well this evals to just 1.0f and what is x / 1? kek + for (x = 0; x < SCREENVERTS; x++) { for (y = 0; y < SCREENVERTS; y++) { // Change X position based on its Y position. - v[x][y][0] = (x/((float)(SCREENVERTS-1.0f)/9.0f))-4.5f + (float)sin((disStart+(y*WAVELENGTH))/FREQUENCY)/AMPLITUDE; - v[x][y][1] = (y/((float)(SCREENVERTS-1.0f)/9.0f))-4.5f; + v[x][y][0] = x-4.5f + sinf(((disStart+((float)y * WAVELENGTH)) / FREQUENCY)) / AMPLITUDE; // (x / scale) + v[x][y][1] = y-4.5f; // (y / scale) } } diff --git a/src/hardware/r_opengl/r_opengl.c b/src/hardware/r_opengl/r_opengl.c index b8466ee3a..024dd2629 100644 --- a/src/hardware/r_opengl/r_opengl.c +++ b/src/hardware/r_opengl/r_opengl.c @@ -1583,11 +1583,11 @@ void GL_Draw2DLine(F2DCoord * v1, F2DCoord * v2, RGBA_t Color) // This is the preferred, 'modern' way of rendering lines -- creating a polygon. if (fabsf(v2->x - v1->x) > FLT_EPSILON) - angle = (float)atan((v2->y-v1->y)/(v2->x-v1->x)); + angle = atanf((v2->y-v1->y)/(v2->x-v1->x)); else angle = (float)N_PI_DEMI; - dx = (float)sin(angle) / (float)screen_width; - dy = (float)cos(angle) / (float)screen_height; + dx = sinf(angle) / (float)screen_width; + dy = cosf(angle) / (float)screen_height; p[0] = v1->x - dx; p[1] = -(v1->y + dy); p[2] = 1; p[3] = v2->x - dx; p[4] = -(v2->y + dy); p[5] = 1; @@ -3136,8 +3136,8 @@ void GL_DrawModelEx(model_t *model, INT32 frameIndex, float duration, float tics void GL_SetTransform(FTransform *stransform) { static boolean special_splitscreen; - GLdouble used_fov; boolean shearing = false; + float used_fov; pglLoadIdentity(); @@ -3196,11 +3196,11 @@ void GL_SetTransform(FTransform *stransform) if (special_splitscreen) { - used_fov = (float)(atan(tan(used_fov * M_PIl / 360) * 0.8) * 360 / M_PIl); - GL_Perspective((GLfloat)used_fov, 2*ASPECT_RATIO); + used_fov = (atanf(tanf(used_fov * (float)M_PI / 360.0f) * 0.8f) * 360.0f / (float)M_PI); + GL_Perspective(used_fov, 2*ASPECT_RATIO); } else - GL_Perspective((GLfloat)used_fov, ASPECT_RATIO); + GL_Perspective(used_fov, ASPECT_RATIO); pglGetFloatv(GL_PROJECTION_MATRIX, projMatrix); // added for new coronas' code (without depth buffer) pglMatrixMode(GL_MODELVIEW); diff --git a/src/sdl/i_system.cpp b/src/sdl/i_system.cpp index 272379aa8..0dc751c85 100644 --- a/src/sdl/i_system.cpp +++ b/src/sdl/i_system.cpp @@ -1260,7 +1260,7 @@ static void I_SetupMumble(void) void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) { #ifdef HAVE_MUMBLE - double angle; + float angle; fixed_t anglef; if (!mumble) @@ -1274,7 +1274,9 @@ void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) } mumble->uiTick++; - if (!netgame || gamestate != GS_LEVEL) { // Zero out, but never delink. + // Zero out, but never delink. + if (!netgame || gamestate != GS_LEVEL) + { mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f; mumble->fAvatarFront[0] = 1.0f; mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f; @@ -1293,30 +1295,32 @@ void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) if (mobj) { - mumble->fAvatarPosition[0] = FIXED_TO_FLOAT(mobj->x) / MUMBLEUNIT; - mumble->fAvatarPosition[1] = FIXED_TO_FLOAT(mobj->z) / MUMBLEUNIT; - mumble->fAvatarPosition[2] = FIXED_TO_FLOAT(mobj->y) / MUMBLEUNIT; + mumble->fAvatarPosition[0] = FixedToFloat(mobj->x) / MUMBLEUNIT; + mumble->fAvatarPosition[1] = FixedToFloat(mobj->z) / MUMBLEUNIT; + mumble->fAvatarPosition[2] = FixedToFloat(mobj->y) / MUMBLEUNIT; anglef = AngleFixed(mobj->angle); - angle = FIXED_TO_FLOAT(anglef)*DEG2RAD; - mumble->fAvatarFront[0] = (float)cos(angle); + angle = (float)(FixedToFloat(anglef) * DEG2RAD); + mumble->fAvatarFront[0] = cosf(angle); mumble->fAvatarFront[1] = 0.0f; - mumble->fAvatarFront[2] = (float)sin(angle); - } else { + mumble->fAvatarFront[2] = sinf(angle); + } + else + { mumble->fAvatarPosition[0] = mumble->fAvatarPosition[1] = mumble->fAvatarPosition[2] = 0.0f; mumble->fAvatarFront[0] = 1.0f; mumble->fAvatarFront[1] = mumble->fAvatarFront[2] = 0.0f; } - mumble->fCameraPosition[0] = FIXED_TO_FLOAT(listener.x) / MUMBLEUNIT; - mumble->fCameraPosition[1] = FIXED_TO_FLOAT(listener.z) / MUMBLEUNIT; - mumble->fCameraPosition[2] = FIXED_TO_FLOAT(listener.y) / MUMBLEUNIT; + mumble->fCameraPosition[0] = FixedToFloat(listener.x) / MUMBLEUNIT; + mumble->fCameraPosition[1] = FixedToFloat(listener.z) / MUMBLEUNIT; + mumble->fCameraPosition[2] = FixedToFloat(listener.y) / MUMBLEUNIT; anglef = AngleFixed(listener.angle); - angle = FIXED_TO_FLOAT(anglef)*DEG2RAD; - mumble->fCameraFront[0] = (float)cos(angle); + angle = (float)(FixedToFloat(anglef) * DEG2RAD); + mumble->fCameraFront[0] = cosf(angle); mumble->fCameraFront[1] = 0.0f; - mumble->fCameraFront[2] = (float)sin(angle); + mumble->fCameraFront[2] = sinf(angle); #else (void)mobj; (void)listener; -- 2.54.0 From 19a4e379d7531550f8f93ff41c86ea06ca2884f5 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 13 Nov 2025 17:38:27 +0100 Subject: [PATCH 114/116] HWR_DoWipe: always draw a black screen if it returns early otherwise this just flashes like crazy should there ever be any issue here --- src/hardware/hw_main.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/hardware/hw_main.cpp b/src/hardware/hw_main.cpp index 8dc4d3804..100028a20 100644 --- a/src/hardware/hw_main.cpp +++ b/src/hardware/hw_main.cpp @@ -5992,20 +5992,27 @@ void HWR_DoWipe(UINT8 wipenum, UINT8 scrnnum) } if (wipenum > 99 || scrnnum > 99) // not a valid wipe number + { + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap return; // shouldn't end up here really, the loop should've stopped running beforehand + } // puts the numbers into the lumpname sprintf(&lumpname[4], "%.2hu%.2hu", (UINT16)wipenum, (UINT16)scrnnum); lumpnum = W_CheckNumForName(lumpname); if (lumpnum == LUMPERROR) // again, shouldn't be here really + { + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap return; + } lsize = W_LumpLength(lumpnum); if (!(lsize == 256000 || lsize == 64000 || lsize == 16000 || lsize == 4000)) { CONS_Alert(CONS_WARNING, "Fade mask lump %s of incorrect size, ignored\n", lumpname); + V_DrawFill(0, 0, BASEVIDWIDTH, BASEVIDHEIGHT, 31); // just draw a black screen instead of flashing and crap return; // again, shouldn't get here if it is a bad size } -- 2.54.0 From efe700965014e7150a02bbcf32a1c998012b7cd9 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 13 Nov 2025 19:00:06 +0100 Subject: [PATCH 115/116] PT_ReceivedGamestate: add missing SATURNPAK ifdef --- src/d_clisrv.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/d_clisrv.c b/src/d_clisrv.c index f69d67cfe..038661541 100644 --- a/src/d_clisrv.c +++ b/src/d_clisrv.c @@ -5854,12 +5854,14 @@ static void PT_FileFragmentFromPlayer(SINT8 node) Got_Filetxpak(); } +#ifdef SATURNPAK static void PT_ReceivedGamestate(SINT8 node) { sendingsavegame[node] = false; resendingsavegame[node] = 0; savegameresendcooldown[node] = I_GetTime() + cv_resynchcooldown.value * TICRATE; // I_GetTime() + 5 * TICRATE; } +#endif /** Handles a packet received from a node that is in game * -- 2.54.0 From 1fb60e823031358d3257cb32b407edaaece6109e Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 13 Nov 2025 19:31:20 +0100 Subject: [PATCH 116/116] fix sourcefile for src dir --- src/Sourcefile | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Sourcefile b/src/Sourcefile index 352081bc5..462ec9871 100644 --- a/src/Sourcefile +++ b/src/Sourcefile @@ -20,6 +20,7 @@ i_tcp.c i_time.c info.c lzf.c +md5.c m_aatree.c m_anigif.c m_argv.c @@ -43,18 +44,19 @@ screen.c sounds.c st_stuff.c string.c +stun.c tables.c v_video.c w_wad.c y_inter.c z_zone.cpp -r_bsp.c +r_bsp.cpp r_data.c -r_draw.c +r_draw.cpp r_fps.cpp r_main.cpp r_patch.cpp -r_patchrotation.c +r_patchrotation.cpp r_plane.cpp r_segs.cpp r_skins.c -- 2.54.0