diff --git a/CMakeLists.txt b/CMakeLists.txt index aa867c4..acf7c10 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,26 +1,129 @@ cmake_minimum_required(VERSION 3.20) -project(CleanQuake CXX) +project(Quake.cpp LANGUAGES CXX) -# Set standard C++ flags -set(CMAKE_CXX_STANDARD 20) +if(NOT CMAKE_GENERATOR MATCHES "^Visual Studio") +include(GNUInstallDirs) +include(FindPkgConfig) +endif() + +set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS ON) -# Add SDL definition -add_compile_definitions(SDL) +if( NOT CMAKE_BUILD_TYPE ) + set( CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE ) +endif() -# Fetch SDL2 -include(FetchContent) -FetchContent_Declare( - SDL2 - GIT_REPOSITORY https://github.com/libsdl-org/SDL.git - GIT_TAG release-2.30.3 -) -# Disable unnecessary SDL2 features for faster build -set(SDL_TEST OFF CACHE BOOL "" FORCE) -set(SDL_SHARED OFF CACHE BOOL "" FORCE) -set(SDL_STATIC ON CACHE BOOL "" FORCE) +string(TOUPPER "${CMAKE_SYSTEM_PROCESSOR}" SYSTEM_PROCESSOR_UPPER) +message(STATUS "OS: ${CMAKE_HOST_SYSTEM_NAME}-${CMAKE_HOST_SYSTEM_PROCESSOR} => ${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") +message(STATUS "CXX: ${CMAKE_CXX_COMPILER_ID}/${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}") +message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") + +add_compile_definitions(_FILE_OFFSET_BITS=64) +add_compile_definitions($<$:DEBUG=1> $<$>:NDEBUG=1>) +add_compile_definitions($<$:_DEBUG=1> $<$>:_NDEBUG=1>) + +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_compile_options(-Wno-gnu-alignof-expression) +endif() + +if (CMAKE_CXX_COMPILER_FRONTEND_VARIANT MATCHES "GNU|AppleClang") + if( NOT CMAKE_BUILD_OPTLEVEL ) + set( CMAKE_BUILD_OPTLEVEL 3 CACHE STRING "Choose the optimization level." FORCE ) + endif() + add_compile_options(-O${CMAKE_BUILD_OPTLEVEL}) + if (NOT CMAKE_CROSSCOMPILING) + add_compile_options(-march=native) + + if (${SYSTEM_PROCESSOR_UPPER} MATCHES "X64|X86_64|AMD64") + add_compile_options(-mfpmath=sse) + endif() + if (${SYSTEM_PROCESSOR_UPPER} MATCHES "PPC|POWERPC|PPC64|PPC64LE") + include(CheckCSourceCompiles) -FetchContent_MakeAvailable(SDL2) + set(CMAKE_REQUIRED_FLAGS "-maltivec") + check_c_source_compiles("#include int main() { vector int v = (vector int){0}; return 0; }" HAVE_ALTIVEC) + + if(HAVE_ALTIVEC) + add_compile_options(-maltivec) + endif() + endif() + endif() + add_compile_options(-ftree-vectorize) + add_compile_options(-fopenmp) + if(NOT CMAKE_CXX_COMPILER_FRONTEND_VARIANT MATCHES "AppleClang") + add_compile_options(-fopenmp-simd) + endif() + add_compile_options(-fpermissive) + add_compile_options(-fno-asynchronous-unwind-tables) + add_compile_options(-Wall) + add_compile_options(-Wextra) + add_compile_options(-Wno-write-strings) + if (CMAKE_BUILD_TYPE MATCHES Debug) + add_compile_options(-g) + else() + # Use IPO/LTO if available + if(NOT ${CMAKE_VERSION} VERSION_LESS "3.9.0") + cmake_policy(SET CMP0069 NEW) + include(CheckIPOSupported) + check_ipo_supported(RESULT result) + if(result) + set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) + message(STATUS "Using IPO/LTO.") + endif() + endif() + add_compile_options(-Wno-unused-result) + add_compile_options(-Wno-unused-variable) + add_compile_options(-Wno-unused-but-set-variable) + endif() + add_compile_options(-Wunreachable-code) # Warn about unreachable code paths + add_compile_options(-ffunction-sections) # Put each function in its own section + add_compile_options(-fdata-sections) # Put each variable in its own section + if (CMAKE_BUILD_TYPE MATCHES ReleaseStrip) + add_link_options(-Wl,--gc-sections) # Garbage collect empty sections + add_link_options(-Wl,-s) # Print out everything the linker throws away + endif() + link_libraries(m) + if (WIN32 AND MINGW) + link_libraries(mingw32) + endif() +else (CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC") + if( NOT CMAKE_BUILD_OPTLEVEL ) + set( CMAKE_BUILD_OPTLEVEL 2 CACHE STRING "Choose the optimization level." FORCE ) + endif() + add_compile_options(/openmp:experimental) + add_compile_options(/O${CMAKE_BUILD_OPTLEVEL}) + add_compile_options(/Zc:__cplusplus) + add_compile_options(/std:c++latest) + add_compile_options(/Zc:preprocessor) + add_compile_options(/W4) + add_compile_options(/Z7) + add_compile_options(/w14702) # Force C4702 (Unreachable code) to be a Level 1 Warning + add_compile_options(/wd4996) + add_compile_options(/wd4244) + add_compile_options(/wd4113) + add_compile_options(/wd4047) + add_compile_options(/wd4024) + add_compile_options(/Gy) # Function-level linking (puts each function in its own section) + add_compile_options(/Gw) # Optimize global data (puts each variable in its own section) + if (CMAKE_BUILD_TYPE MATCHES ReleaseStrip) + add_link_options(/DEBUG:NONE) + add_link_options(/OPT:REF) # Eliminate unreferenced functions and data + add_link_options(/VERBOSE:REF) # Print out everything the linker throws away + endif() + if (NOT CMAKE_CROSSCOMPILING) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS _WIN32) + if (CMAKE_VS_PLATFORM_NAME MATCHES "x64|Win32") + # add_compile_options(/Gv) + endif() + endif() + if (CMAKE_BUILD_TYPE MATCHES Debug) + add_compile_options(/Zi) + add_link_options(/DEBUG:FULL) + endif() + add_link_options(/INCREMENTAL:NO) + link_libraries(ws2_32 winmm) +endif() # Gather source files set(CORE_SRCS @@ -55,39 +158,34 @@ set(CORE_SRCS src/zone.cpp ) -add_executable(Quake.cpp ${CORE_SRCS}) - -target_include_directories(Quake.cpp PRIVATE src) - -# Link SDL2 and Windows libraries -target_link_libraries(Quake.cpp PRIVATE SDL2main SDL2-static ws2_32 winmm) - -# Suppress some old C warnings for cleaner output -if(MSVC) - target_compile_options(Quake.cpp PRIVATE - /W4 - /Z7 - /w14702 # Force C4702 (Unreachable code) to be a Level 1 Warning - /Gy # Function-level linking (puts each function in its own section) - /Gw # Optimize global data (puts each variable in its own section) - ) - # Target-specific linker overrides - # NOTE: /INCREMENTAL:NO is required to allow /OPT:REF to function. - target_link_options(Quake.cpp PRIVATE - /INCREMENTAL:NO - /OPT:REF # Eliminate unreferenced functions and data - /VERBOSE:REF # Print out everything the linker throws away - ) -else() - target_compile_options(Quake.cpp PRIVATE - -Wall -Wextra - -Wunreachable-code # Warn about unreachable code paths - -Wno-write-strings - -ffunction-sections # Put each function in its own section - -fdata-sections # Put each variable in its own section - ) - target_link_options(Quake.cpp PRIVATE - -Wl,--gc-sections # Garbage collect empty sections - -Wl,--print-gc-sections # Print out everything the linker throws away - ) -endif() \ No newline at end of file +cmake_policy(SET CMP0072 NEW) #OpenGL_GL_PREFERENCE to GLVND +find_package(OpenGL) + +find_package(SDL2) +if(NOT SDL2_FOUND) + include(FetchContent) + FetchContent_Declare( + SDL2 + GIT_REPOSITORY https://github.com/libsdl-org/SDL.git + GIT_TAG release-2.30.3 + ) + # Disable unnecessary SDL2 features for faster build + set(SDL_TEST OFF CACHE BOOL "" FORCE) + set(SDL_SHARED OFF CACHE BOOL "" FORCE) + set(SDL_STATIC ON CACHE BOOL "" FORCE) + + FetchContent_MakeAvailable(SDL2) +endif() +find_library(SDL2_MAIN_LIBRARY NAMES SDL2main) +set(SDL2_LIBRARIES SDL2::SDL2) +if(SDL2_MAIN_LIBRARY) + list(APPEND SDL2_LIBRARIES ${SDL2_MAIN_LIBRARY}) +endif() +add_compile_definitions(SDL) +include_directories(SDL2::SDL2) + +# clean-quake executable +add_executable(${PROJECT_NAME} ${CORE_SRCS}) +target_include_directories(${PROJECT_NAME} PRIVATE src) +target_link_libraries(${PROJECT_NAME} PRIVATE ${SDL2_LIBRARIES}) + diff --git a/src/audio.cpp b/src/audio.cpp index 94f4a97..61bc123 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -1,6 +1,5 @@ // audio.cpp -- merged audio subsystem (snd_*.cpp) // Contains: sound control, caching, mixing, and SDL audio driver -#pragma warning(disable: 4324) #include #include "quakedef.hpp" diff --git a/src/audio.hpp b/src/audio.hpp index 8f6db5f..79c8c53 100644 --- a/src/audio.hpp +++ b/src/audio.hpp @@ -24,9 +24,7 @@ struct sfx_s { using sfx_t = sfx_s; -// !!! if this is changed, it much be changed in asm_i386.h too !!! -#pragma warning(push) -#pragma warning(disable: 4200) // Silence nonstandard extension: zero-sized array warning +#pragma pack(push,1) struct sfxcache_t { int length; int loopstart; @@ -35,7 +33,7 @@ struct sfxcache_t { int stereo; byte data[]; // variable sized }; -#pragma warning(pop) +#pragma pack(pop) struct dma_t { std::atomic gamealive; diff --git a/src/client.cpp b/src/client.cpp index b094dd5..a4f4042 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -137,11 +137,11 @@ void CL_ClearState(void) // clear other arrays memset(cl_efrags, 0, sizeof(cl_efrags)); - for (auto& e : cl_entities) e = {}; - for (auto& dl : cl_dlights) dl = {}; + std::fill(std::begin(cl_entities), std::end(cl_entities), entity_t{}); + std::fill(std::begin(cl_dlights), std::end(cl_dlights), dlight_t{}); memset(cl_lightstyle, 0, sizeof(cl_lightstyle)); - for (auto& e : cl_temp_entities) e = {}; - for (auto& b : cl_beams) b = {}; + std::fill(std::begin(cl_temp_entities), std::end(cl_temp_entities), entity_t{}); + std::fill(std::begin(cl_beams), std::end(cl_beams), beam_t{}); // // allocate the efrags and chain together into a free list @@ -259,7 +259,7 @@ void CL_SignonReply(void) ((int)cl_color.value) & 15)); MSG_WriteByte(&cls.message, clc_stringcmd); - sprintf_s(str, sizeof(str), "spawn %s", cls.spawnparms); + snprintf(str, sizeof(str), "spawn %s", cls.spawnparms); MSG_WriteString(&cls.message, str); break; @@ -292,7 +292,7 @@ void CL_NextDemo(void) SCR_BeginLoadingPlaque(); - if (!cls.demos[cls.demonum][0] || cls.demonum == MAX_DEMOS) { + if (!cls.demos[cls.demonum][0] || cls.demonum >= MAX_DEMOS) { cls.demonum = 0; if (!cls.demos[cls.demonum][0]) { Con_Printf("No demos listed with startdemos\n"); @@ -302,7 +302,7 @@ void CL_NextDemo(void) } } - sprintf_s(str, sizeof(str), "playdemo %s\n", cls.demos[cls.demonum]); + snprintf(str, sizeof(str), "playdemo %s\n", cls.demos[cls.demonum]); Cmd::BufferInsertText(str); cls.demonum++; } @@ -977,7 +977,7 @@ void CL_BaseMove(usercmd_t* cmd) CL_SendMove ============== */ -void CL_SendMove(usercmd_t* cmd) +void CL_SendMove(const usercmd_t* cmd) { int i; int bits; @@ -1154,7 +1154,6 @@ Handles recording and playback of demos, on top of NET_ code */ int CL_GetMessage(void) { - int r, i; float f; if (cls.demoplayback) { @@ -1180,7 +1179,7 @@ int CL_GetMessage(void) // get the next message fread(&net_message.cursize, 4, 1, cls.demofile); VectorCopy(cl.mviewangles[0], cl.mviewangles[1]); - for (i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) { fread(&f, 4, 1, cls.demofile); cl.mviewangles[0][i] = LittleFloat(f); } @@ -1190,7 +1189,7 @@ int CL_GetMessage(void) Sys_Error("Demo message > MAX_MSGLEN"); } - r = (int)fread(net_message.data, net_message.cursize, 1, cls.demofile); + int r = (int)fread(net_message.data, net_message.cursize, 1, cls.demofile); if (r != 1) { CL_StopPlayback(); @@ -1200,6 +1199,8 @@ int CL_GetMessage(void) return 1; } + int r; + while (1) { r = NET_GetMessage(cls.netcon); @@ -1299,7 +1300,7 @@ void CL_Record_f(void) track = -1; } - sprintf_s(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); + snprintf(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); // // start the map up @@ -1314,7 +1315,7 @@ void CL_Record_f(void) COM_DefaultExtension(name, ".dem"); Con_Printf("recording to %s.\n", name); - fopen_s(&cls.demofile, name, "wb"); + cls.demofile = fopen(name, "wb"); if (!cls.demofile) { Con_Printf("ERROR: couldn't open.\n"); @@ -1622,7 +1623,7 @@ void CL_ParseServerInfo(void) // parse signon message str = MSG_ReadString(); - strncpy_s(cl.levelname, sizeof(cl.levelname), str, _TRUNCATE); + strlcpy(cl.levelname, str, sizeof(cl.levelname)); // seperate the printfs so the server message can have a color Con_Printf( @@ -1650,7 +1651,7 @@ void CL_ParseServerInfo(void) return; } - strcpy_s(model_precache[nummodels], sizeof(model_precache[nummodels]), str); + strlcpy(model_precache[nummodels], str, sizeof(model_precache[nummodels])); Mod_TouchModel(str); } @@ -1668,7 +1669,7 @@ void CL_ParseServerInfo(void) return; } - strcpy_s(sound_precache[numsounds], sizeof(sound_precache[numsounds]), str); + strlcpy(sound_precache[numsounds], str, sizeof(sound_precache[numsounds])); S_TouchSound(str); } @@ -1931,7 +1932,7 @@ void CL_ParseClientdata(int bits) if (cl.items != i) { // set flash times Sbar_Changed(); for (j = 0; j < 32; j++) { - if ((i & (1 << j)) && !(cl.items & (1 << j))) { + if ((i & (1U << static_cast(j))) && !(cl.items & (1U << static_cast(j)))) { cl.item_gettime[j] = static_cast(cl.time); } } @@ -2108,7 +2109,6 @@ CL_ParseServerMessage */ void CL_ParseServerMessage(void) { - int cmd; int i; // @@ -2131,9 +2131,8 @@ void CL_ParseServerMessage(void) Host_Error("CL_ParseServerMessage: Bad server message"); } - cmd = MSG_ReadByte(); - - if (cmd == -1) { + int cmd = MSG_ReadByte(); + if (msg_badread) { SHOWNET("END OF MESSAGE"); return; // end of message @@ -2238,7 +2237,7 @@ void CL_ParseServerMessage(void) Host_Error("CL_ParseServerMessage: svc_updatename > MAX_SCOREBOARD"); } - strcpy_s(cl.scores[i].name, sizeof(cl.scores[i].name), MSG_ReadString()); + strlcpy(cl.scores[i].name, MSG_ReadString(), sizeof(cl.scores[i].name)); break; case svc_updatefrags: @@ -2406,7 +2405,7 @@ void CL_ParseBeam(model_t* m) // override any beam with the same entity for (i = 0, b = cl_beams; i < MAX_BEAMS; i++, b++) { if (b->entity == ent) { - b->entity = ent; + // b->entity already matches ent, just update the rest b->model = m; b->endtime = static_cast(cl.time + 0.2); b->start = start; diff --git a/src/client.hpp b/src/client.hpp index ae2a963..f8a19f3 100644 --- a/src/client.hpp +++ b/src/client.hpp @@ -1,13 +1,13 @@ // client.h -- client state, connection, and entity structures #pragma once -typedef struct { +typedef struct usercmd_s { Vector3 viewangles; // intended velocities - float forwardmove; - float sidemove; - float upmove; + float forwardmove = 0.0f; + float sidemove = 0.0f; + float upmove = 0.0f; } usercmd_t; typedef struct { @@ -15,12 +15,12 @@ typedef struct { char map[MAX_STYLESTRING]; } lightstyle_t; -typedef struct { - char name[MAX_SCOREBOARDNAME]; - float entertime; - int frags; - int colors; // two 4 bit fields - byte translations[VID_GRADES * 256]; +typedef struct scoreboard_s { + char name[MAX_SCOREBOARDNAME] = {}; + float entertime = 0.0f; + int frags = 0; + int colors = 0; // two 4 bit fields + byte translations[VID_GRADES * 256] = {}; } scoreboard_t; typedef struct { @@ -44,21 +44,21 @@ typedef struct { #define MAX_DLIGHTS 32 -typedef struct { +typedef struct dlight_s { Vector3 origin; - float radius; - float die; // stop lighting after this time - float decay; // drop this each second - float minlight; // don't add when contributing less - int key; + float radius = 0.0f; + float die = 0.0f; // stop lighting after this time + float decay = 0.0f; // drop this each second + float minlight = 0.0f; // don't add when contributing less + int key = 0; } dlight_t; #define MAX_BEAMS 24 -typedef struct { - int entity; - struct model_s* model; - float endtime; +typedef struct beam_s { + int entity = 0; + struct model_s* model = nullptr; + float endtime = 0.0f; Vector3 start, end; } beam_t; @@ -113,21 +113,21 @@ namespace Client { // the client_state_t structure is wiped completely at every // server signon // -typedef struct { - int movemessages; // since connecting to this server +typedef struct client_state_s { + int movemessages = 0; // since connecting to this server // throw out the first couple, so the player // doesn't accidentally do something the // first frame - usercmd_t cmd; // last command sent to the server + usercmd_t cmd = {}; // last command sent to the server // information for local display - int stats[MAX_CL_STATS]; // health, etc - int items; // inventory bit flags - float item_gettime[32]; // cl.time of aquiring item, for blinking - float faceanimtime; // use anim frame if cl.time < this + int stats[MAX_CL_STATS] = {}; // health, etc + int items = 0; // inventory bit flags + float item_gettime[32] = {}; // cl.time of aquiring item, for blinking + float faceanimtime = 0.0f; // use anim frame if cl.time < this - cshift_t cshifts[NUM_CSHIFTS]; // color shifts for damage, powerups - cshift_t prev_cshifts[NUM_CSHIFTS]; // and content types + cshift_t cshifts[NUM_CSHIFTS] = {}; // color shifts for damage, powerups + cshift_t prev_cshifts[NUM_CSHIFTS] = {}; // and content types // the client maintains its own idea of view angles, which are // sent to the server each frame. The server sets punchangle when @@ -144,53 +144,53 @@ typedef struct { Vector3 punchangle; // temporary offset // pitch drifting vars - float idealpitch; - float pitchvel; - qboolean nodrift; - float driftmove; - double laststop; + float idealpitch = 0.0f; + float pitchvel = 0.0f; + qboolean nodrift = false; + float driftmove = 0.0f; + double laststop = 0.0; - float viewheight; - float crouch; // local amount for smoothing stepups + float viewheight = 0.0f; + float crouch = 0.0f; // local amount for smoothing stepups - qboolean paused; // send over by server - qboolean onground; - qboolean inwater; + qboolean paused = false; // send over by server + qboolean onground = false; + qboolean inwater = false; - int intermission; // don't change view angle, full screen, etc - int completed_time; // latched at intermission start + int intermission = 0; // don't change view angle, full screen, etc + int completed_time = 0; // latched at intermission start - double mtime[2]; // the timestamp of last two messages - double time; // clients view of time, should be between + double mtime[2] = {}; // the timestamp of last two messages + double time = 0.0; // clients view of time, should be between // servertime and oldservertime to generate // a lerp point for other data - double oldtime; // previous cl.time, time-oldtime is used + double oldtime = 0.0; // previous cl.time, time-oldtime is used // to decay light values and smooth step ups - float last_received_message; // (realtime) for net trouble icon + float last_received_message = 0.0f; // (realtime) for net trouble icon // // information that is static for the entire time connected to a server // - struct model_s* model_precache[MAX_MODELS]; - struct sfx_s* sound_precache[MAX_SOUNDS]; + struct model_s* model_precache[MAX_MODELS] = {}; + struct sfx_s* sound_precache[MAX_SOUNDS] = {}; - char levelname[40]; // for display on solo scoreboard - int viewentity; // cl_entitites[cl.viewentity] = player - int maxclients; - int gametype; + char levelname[40] = {}; // for display on solo scoreboard + int viewentity = 0; // cl_entitites[cl.viewentity] = player + int maxclients = 0; + int gametype = 0; // refresh related state - struct model_s* worldmodel; // cl_entitites[0].model - struct efrag_s* free_efrags; - int num_entities; // held in cl_entities array - int num_statics; // held in cl_staticentities array - entity_t viewent; // the gun model + struct model_s* worldmodel = nullptr; // cl_entitites[0].model + struct efrag_s* free_efrags = nullptr; + int num_entities = 0; // held in cl_entities array + int num_statics = 0; // held in cl_staticentities array + entity_t viewent = {}; // the gun model - int cdtrack, looptrack; // cd audio + int cdtrack = 0, looptrack = 0; // cd audio // frag scoreboard - scoreboard_t* scores; // [cl.maxclients] + scoreboard_t* scores = nullptr; // [cl.maxclients] } client_state_t; @@ -240,6 +240,7 @@ using BeamArray = beam_t[MAX_BEAMS]; class ClientSubsystem { public: + ClientSubsystem() = default; client_static_t& GetStaticState() { return cls_; } const client_static_t& GetStaticState() const { return cls_; } @@ -255,15 +256,15 @@ class ClientSubsystem { BeamArray& GetBeams() { return cl_beams_; } private: - client_static_t cls_; - client_state_t cl_; - efrag_t cl_efrags_[MAX_EFRAGS]; - entity_t cl_entities_[MAX_EDICTS]; - entity_t cl_static_entities_[MAX_STATIC_ENTITIES]; - lightstyle_t cl_lightstyle_[MAX_LIGHTSTYLES]; - dlight_t cl_dlights_[MAX_DLIGHTS]; - entity_t cl_temp_entities_[MAX_TEMP_ENTITIES]; - beam_t cl_beams_[MAX_BEAMS]; + client_static_t cls_ = {}; + client_state_t cl_ = {}; + efrag_t cl_efrags_[MAX_EFRAGS] = {}; + entity_t cl_entities_[MAX_EDICTS] = {}; + entity_t cl_static_entities_[MAX_STATIC_ENTITIES] = {}; + lightstyle_t cl_lightstyle_[MAX_LIGHTSTYLES] = {}; + dlight_t cl_dlights_[MAX_DLIGHTS] = {}; + entity_t cl_temp_entities_[MAX_TEMP_ENTITIES] = {}; + beam_t cl_beams_[MAX_BEAMS] = {}; }; ClientSubsystem& GetClientSubsystem(); @@ -316,7 +317,7 @@ extern kbutton_t in_speed; void CL_InitInput(void); void CL_SendCmd(void); -void CL_SendMove(usercmd_t* cmd); +void CL_SendMove(const usercmd_t* cmd); void CL_ParseTEnt(void); void CL_UpdateTEnts(void); diff --git a/src/cmd.cpp b/src/cmd.cpp index fe500db..82675ca 100644 --- a/src/cmd.cpp +++ b/src/cmd.cpp @@ -74,7 +74,7 @@ void CommandRegistry::BufferInsertText(std::string_view text) int templen = cmd_text_.cursize; char* temp = nullptr; if (templen) { - temp = (char *) Z_Malloc(templen); + temp = static_cast(Z_Malloc(templen)); Q_memcpy(temp, cmd_text_.data, templen); SZ_Clear(&cmd_text_); } @@ -92,7 +92,7 @@ void CommandRegistry::BufferExecute(void) char line[1024]; while (cmd_text_.cursize) { - char* text = (char*)cmd_text_.data; + char* text = reinterpret_cast(cmd_text_.data); int quotes = 0; int i; @@ -152,7 +152,7 @@ static void StuffCmds_f(void) return; } - char* text = (char *) Z_Malloc(s + 1); + char* text = static_cast(Z_Malloc(s + 1)); text[0] = 0; for (int i = 1; i < com_argc; i++) { if (!com_argv[i]) { @@ -165,7 +165,7 @@ static void StuffCmds_f(void) } } - char* build = (char *) Z_Malloc(s + 1); + char* build = static_cast(Z_Malloc(s + 1)); build[0] = 0; for (int i = 0; i < s - 1; i++) { @@ -203,7 +203,7 @@ static void Exec_f(void) int mark = Hunk_LowMark(); std::string_view filename = Cmd::Argv(1); - char* f = (char*)COM_LoadHunkFile(const_cast(filename.data())); + char* f = reinterpret_cast(COM_LoadHunkFile(const_cast(filename.data()))); if (!f) { Con_Printf("couldn't exec %.*s\n", static_cast(filename.length()), filename.data()); return; @@ -226,7 +226,7 @@ static void Echo_f(void) static char* CopyString(const char* in) { char* out = (char *) Z_Malloc(static_cast(std::strlen(in)) + 1); - strcpy_s(out, std::strlen(in) + 1, in); + strlcpy(out, in, std::strlen(in) + 1); return out; } @@ -257,7 +257,7 @@ static void Alias_f(void) } if (!a) { - a = (cmdalias_t *) Z_Malloc(sizeof(cmdalias_t)); + a = static_cast(Z_Malloc(sizeof(cmdalias_t))); a->next = GetCommandRegistry().GetAliases(); GetCommandRegistry().GetAliases() = a; } @@ -268,12 +268,12 @@ static void Alias_f(void) cmd[0] = 0; int c = Cmd::Argc(); for (int i = 2; i < c; i++) { - strcat_s(cmd, sizeof(cmd), Cmd::Argv(i).data()); + strlcat(cmd, Cmd::Argv(i).data(), sizeof(cmd)); if (i != c) { - strcat_s(cmd, sizeof(cmd), " "); + strlcat(cmd, " ", sizeof(cmd)); } } - strcat_s(cmd, sizeof(cmd), "\n"); + strlcat(cmd, "\n", sizeof(cmd)); a->value = CopyString(cmd); } @@ -308,8 +308,8 @@ void CommandRegistry::AddCommand(std::string_view cmd_name, xcommand_t function) return; } - cmd_function_t* cmd = (cmd_function_t*) Hunk_Alloc(sizeof(cmd_function_t), "cmd"); - cmd->name = (char*) Hunk_Alloc(static_cast(cmd_name.length()) + 1, "cmdname"); + cmd_function_t* cmd = static_cast(Hunk_Alloc(sizeof(cmd_function_t), "cmd")); + cmd->name = static_cast(Hunk_Alloc(static_cast(cmd_name.length()) + 1, "cmdname")); std::memcpy(cmd->name, cmd_name.data(), cmd_name.length()); cmd->name[cmd_name.length()] = '\0'; cmd->function = function; @@ -319,7 +319,7 @@ void CommandRegistry::AddCommand(std::string_view cmd_name, xcommand_t function) bool CommandRegistry::Exists(std::string_view cmd_name) { - for (cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { + for (const cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { if (cmd_name == cmd->name) { return true; } @@ -333,7 +333,7 @@ std::string_view CommandRegistry::CompleteCommand(std::string_view partial) return ""; } - for (cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { + for (const cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { if (std::string_view(cmd->name).starts_with(partial)) { return cmd->name; } @@ -381,7 +381,6 @@ void CommandRegistry::TokenizeString(std::string_view text) } if (*ptr == '\n') { - ptr++; break; } @@ -393,18 +392,16 @@ void CommandRegistry::TokenizeString(std::string_view text) cmd_args_ = std::string_view(ptr); } - char* next_ptr = COM_Parse(const_cast(ptr)); + const char* next_ptr = COM_Parse(const_cast(ptr)); if (!next_ptr) { return; } ptr = next_ptr; - if (!command_parsed) { - command_parsed = true; - } + command_parsed = true; if (cmd_argc_ < 80) { // MAX_ARGS - cmd_argv_[cmd_argc_] = (char *) Z_Malloc(Q_strlen(com_token) + 1); + cmd_argv_[cmd_argc_] = static_cast(Z_Malloc(Q_strlen(com_token) + 1)); Q_strcpy(cmd_argv_[cmd_argc_], com_token); cmd_argc_++; } @@ -420,14 +417,14 @@ void CommandRegistry::ExecuteString(std::string_view text, Source src) return; } - for (cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { + for (const cmd_function_t* cmd = cmd_functions_; cmd; cmd = cmd->next) { if (Q_strcasecmp(cmd_argv_[0], cmd->name) == 0) { cmd->function(); return; } } - for (cmdalias_t* a = cmd_alias_; a; a = a->next) { + for (const cmdalias_t* a = cmd_alias_; a; a = a->next) { if (Q_strcasecmp(cmd_argv_[0], a->name) == 0) { BufferInsertText(a->value); return; @@ -479,4 +476,4 @@ std::string_view Args(void) { return GetCommandRegistry().Args(); } void ExecuteString(std::string_view text, Source src) { GetCommandRegistry().ExecuteString(text, src); } // ForwardToServer is implemented directly above -} // namespace Cmd \ No newline at end of file +} // namespace Cmd diff --git a/src/cmd.hpp b/src/cmd.hpp index 5f858ee..dd16a49 100644 --- a/src/cmd.hpp +++ b/src/cmd.hpp @@ -56,12 +56,12 @@ class CommandRegistry { private: State state_; - sizebuf_t cmd_text_; + sizebuf_t cmd_text_ = {}; bool cmd_wait_ = false; cmdalias_t* cmd_alias_ = nullptr; cmd_function_t* cmd_functions_ = nullptr; int cmd_argc_ = 0; - char* cmd_argv_[80]; // MAX_ARGS + char* cmd_argv_[80] = {}; // MAX_ARGS std::string_view cmd_args_; }; diff --git a/src/common.cpp b/src/common.cpp index 7074fc2..24dea62 100644 --- a/src/common.cpp +++ b/src/common.cpp @@ -143,11 +143,11 @@ void Q_memset(void* dest, int fill, int count) count >>= 2; fill = fill | (fill << 8) | (fill << 16) | (fill << 24); for (i = 0; i < count; i++) { - ((int*)dest)[i] = fill; + static_cast(dest)[i] = fill; } } else { for (i = 0; i < count; i++) { - ((byte*)dest)[i] = static_cast(fill); + static_cast(dest)[i] = static_cast(fill); } } } @@ -160,11 +160,11 @@ void Q_memcpy(void* dest, const void* src, int count) if ((((size_t)dest | (size_t)src | count) & 3) == 0) { count >>= 2; for (i = 0; i < count; i++) { - ((int*)dest)[i] = ((const int*)src)[i]; + static_cast(dest)[i] = static_cast(src)[i]; } } else { for (i = 0; i < count; i++) { - ((byte*)dest)[i] = ((const byte*)src)[i]; + static_cast(dest)[i] = static_cast(src)[i]; } } } @@ -260,11 +260,9 @@ int Q_strncmp(const char* s1, const char* s2, int count) int Q_strncasecmp(const char* s1, const char* s2, int n) { - int c1, c2; - while (1) { - c1 = *s1++; - c2 = *s2++; + int c1 = *s1++; + int c2 = *s2++; if (!n--) { return 0; // strings are equal until end point @@ -529,7 +527,7 @@ void MSG_WriteChar(sizebuf_t* sb, int c) #endif - buf = (byte*)SZ_GetSpace(sb, 1); + buf = static_cast(SZ_GetSpace(sb, 1)); buf[0] = static_cast(c); } @@ -544,7 +542,7 @@ void MSG_WriteByte(sizebuf_t* sb, int c) #endif - buf = (byte*)SZ_GetSpace(sb, 1); + buf = static_cast(SZ_GetSpace(sb, 1)); buf[0] = static_cast(c); } @@ -553,26 +551,26 @@ void MSG_WriteShort(sizebuf_t* sb, int c) byte* buf; #ifdef PARANOID - if (c < ((short)0x8000) || c > (short)0x7fff) { + if (c < -32768 || c > 32767) { Sys_Error("MSG_WriteShort: range error"); } #endif - buf = (byte*)SZ_GetSpace(sb, 2); + buf = static_cast(SZ_GetSpace(sb, 2)); buf[0] = c & 0xff; - buf[1] = static_cast(c >> 8); + buf[1] = static_cast(static_cast(c) >> 8); } void MSG_WriteLong(sizebuf_t* sb, int c) { byte* buf; - buf = (byte*)SZ_GetSpace(sb, 4); + buf = static_cast(SZ_GetSpace(sb, 4)); buf[0] = c & 0xff; - buf[1] = (c >> 8) & 0xff; - buf[2] = (c >> 16) & 0xff; - buf[3] = c >> 24; + buf[1] = (static_cast(c) >> 8) & 0xff; + buf[2] = (static_cast(c) >> 16) & 0xff; + buf[3] = static_cast(static_cast(c) >> 24); } void MSG_WriteFloat(sizebuf_t* sb, float f) @@ -698,11 +696,9 @@ float MSG_ReadFloat(void) char* MSG_ReadString(void) { static char string[2048]; - int l, c; - - l = 0; + int l = 0; do { - c = MSG_ReadChar(); + int c = MSG_ReadChar(); if (c == -1 || c == 0) { break; } @@ -724,7 +720,7 @@ void SZ_Alloc(sizebuf_t* buf, int startsize) startsize = 256; } - buf->data = (byte *) Hunk_Alloc(startsize, "sizebuf"); + buf->data = static_cast(Hunk_Alloc(startsize, "sizebuf")); buf->maxsize = startsize; buf->cursize = 0; } @@ -766,9 +762,9 @@ void SZ_Print(sizebuf_t* buf, const char* data) // byte * cast to keep VC++ happy if (buf->data[buf->cursize - 1]) { - Q_memcpy((byte*)SZ_GetSpace(buf, len), data, len); // no trailing 0 + Q_memcpy(SZ_GetSpace(buf, len), data, len); // no trailing 0 } else { - Q_memcpy((byte*)SZ_GetSpace(buf, len - 1) - 1, data, + Q_memcpy(static_cast(SZ_GetSpace(buf, len - 1)) - 1, data, len); // write over trailing 0 } } @@ -822,10 +818,10 @@ void COM_FileBase(const char* in, char* out) } if (s - s2 < 2) { - strcpy_s(out, 32, "?model?"); + strlcpy(out, "?model?", 32); } else { s--; - strncpy_s(out, 32, s2 + 1, s - s2); + strlcpy(out, s2 + 1, 32); out[s - s2] = 0; } } @@ -852,7 +848,7 @@ void COM_DefaultExtension(char* path, const char* extension) src--; } - strcat_s(path, 256, extension); + strlcat(path, extension, 256); } /* @@ -1081,7 +1077,7 @@ void COM_Init() if (SDL_BYTEORDER == SDL_LIL_ENDIAN) #else byte swaptest[2] = { 1, 0 }; - if (*(short*)swaptest == 1) + if (*reinterpret_cast(swaptest) == 1) #endif { bigendien = false; @@ -1124,7 +1120,7 @@ char* va(const char* format, ...) static char string[1024]; va_start(argptr, format); - vsprintf_s(string, sizeof(string), format, argptr); + vsnprintf(string, sizeof(string), format, argptr); va_end(argptr); return string; @@ -1210,12 +1206,12 @@ COM_WriteFile The filename will be prefixed by the current game directory ============ */ -void COM_WriteFile(const char* filename, void* data, int len) +void COM_WriteFile(const char* filename, const void* data, int len) { int handle; char name[MAX_OSPATH]; - sprintf_s(name, sizeof(name), "%s/%s", com_gamedir, filename); + snprintf(name, sizeof(name), "%s/%s", com_gamedir, filename); handle = Sys_FileOpenWrite(name); if (handle == -1) { @@ -1257,7 +1253,7 @@ Copies a file over from the net to the local cache, creating any directories needed. This is for the convenience of developers using ISDN from home. =========== */ -void COM_CopyFile(char* netpath, char* cachepath) +void COM_CopyFile(const char* netpath, char* cachepath) { int in, out; int remaining, count; @@ -1330,7 +1326,7 @@ int COM_FindFile(const char* filename, int* handle, FILE** file) *handle = pak->handle; Sys_FileSeek(pak->handle, pak->files[i].filepos); } else { // open a new file on the pakfile - fopen_s(file, pak->filename, "rb"); + *file = fopen(pak->filename, "rb"); if (*file) { fseek(*file, pak->files[i].filepos, SEEK_SET); } @@ -1349,7 +1345,7 @@ int COM_FindFile(const char* filename, int* handle, FILE** file) } } - sprintf_s(netpath, sizeof(netpath), "%s/%s", search->filename, filename); + snprintf(netpath, sizeof(netpath), "%s/%s", search->filename, filename); findtime = Sys_FileTime(netpath); if (findtime == -1) { @@ -1358,9 +1354,9 @@ int COM_FindFile(const char* filename, int* handle, FILE** file) // see if the file needs to be updated in the cache if (!com_cachedir[0]) { - strcpy_s(cachepath, sizeof(cachepath), netpath); + strlcpy(cachepath, netpath, sizeof(cachepath)); } else { - sprintf_s(cachepath, sizeof(cachepath), "%s/%s", com_cachedir, netpath); + snprintf(cachepath, sizeof(cachepath), "%s/%s", com_cachedir, netpath); cachetime = Sys_FileTime(cachepath); @@ -1368,7 +1364,7 @@ int COM_FindFile(const char* filename, int* handle, FILE** file) COM_CopyFile(netpath, cachepath); } - strcpy_s(netpath, sizeof(netpath), cachepath); + strlcpy(netpath, cachepath, sizeof(netpath)); } Sys_Printf("FindFile: %s\n", netpath); @@ -1377,7 +1373,7 @@ int COM_FindFile(const char* filename, int* handle, FILE** file) *handle = i; } else { Sys_FileClose(i); - fopen_s(file, netpath, "rb"); + *file = fopen(netpath, "rb"); } return com_filesize; @@ -1406,9 +1402,7 @@ If it is a pak file handle, don't really close it */ void COM_CloseFile(int h) { - searchpath_t* s; - - for (s = com_searchpaths; s; s = s->next) { + for (const searchpath_t* s = com_searchpaths; s; s = s->next) { if (s->pack && s->pack->handle == h) { return; } @@ -1448,16 +1442,16 @@ byte* COM_LoadFile(const char* path, int usehunk) COM_FileBase(path, base); if (usehunk == 1) { - buf = (byte *) Hunk_Alloc(len + 1, base); + buf = static_cast(Hunk_Alloc(len + 1, base)); } else if (usehunk == 2) { - buf = (byte *) Hunk_TempAlloc(len + 1); + buf = static_cast(Hunk_TempAlloc(len + 1)); } else if (usehunk == 0) { - buf = (byte *) Z_Malloc(len + 1); + buf = static_cast(Z_Malloc(len + 1)); } else if (usehunk == 3) { - buf = (byte *) Cache_Alloc(loadcache, len + 1, base); + buf = static_cast(Cache_Alloc(loadcache, len + 1, base)); } else if (usehunk == 4) { if (len + 1 > loadsize) { - buf = (byte *) Hunk_TempAlloc(len + 1); + buf = static_cast(Hunk_TempAlloc(len + 1)); } else { buf = loadbuf; } @@ -1469,7 +1463,7 @@ byte* COM_LoadFile(const char* path, int usehunk) Sys_Error("COM_LoadFile: not enough space for %s", path); } - ((byte*)buf)[len] = 0; + buf[len] = 0; Draw_BeginDisc(); Sys_FileRead(h, buf, len); @@ -1490,7 +1484,7 @@ byte* COM_LoadStackFile(const char* path, void* buffer, int bufsize) { byte* buf; - loadbuf = (byte*)buffer; + loadbuf = static_cast(buffer); loadsize = bufsize; buf = COM_LoadFile(path, 4); @@ -1523,7 +1517,7 @@ pack_t* COM_LoadPackFile(char* packfile) return NULL; } - Sys_FileRead(packhandle, (void*)&header, sizeof(header)); + Sys_FileRead(packhandle, &header, sizeof(header)); if (header.id[0] != 'P' || header.id[1] != 'A' || header.id[2] != 'C' || header.id[3] != 'K') { Sys_Error("%s is not a packfile", packfile); } @@ -1541,15 +1535,15 @@ pack_t* COM_LoadPackFile(char* packfile) com_modified = true; // not the original file } - newfiles = (packfile_t *) Hunk_Alloc(numpackfiles * sizeof(packfile_t), "packfile"); + newfiles = static_cast(Hunk_Alloc(numpackfiles * sizeof(packfile_t), "packfile")); Sys_FileSeek(packhandle, header.dirofs); - Sys_FileRead(packhandle, (void*)info, header.dirlen); + Sys_FileRead(packhandle, info, header.dirlen); // crc the directory to check for modifications CRC_Init(&crc); for (i = 0; i < header.dirlen; i++) { - CRC_ProcessByte(&crc, ((byte*)info)[i]); + CRC_ProcessByte(&crc, reinterpret_cast(info)[i]); } if (crc != PAK0_CRC) { com_modified = true; @@ -1557,13 +1551,13 @@ pack_t* COM_LoadPackFile(char* packfile) // parse the directory for (i = 0; i < numpackfiles; i++) { - strcpy_s(newfiles[i].name, sizeof(newfiles[i].name), info[i].name); + strlcpy(newfiles[i].name, info[i].name, sizeof(newfiles[i].name)); newfiles[i].filepos = LittleLong(info[i].filepos); newfiles[i].filelen = LittleLong(info[i].filelen); } pack = (pack_t *) Hunk_Alloc(sizeof(pack_t)); - strcpy_s(pack->filename, sizeof(pack->filename), packfile); + strlcpy(pack->filename, packfile, sizeof(pack->filename)); pack->handle = packhandle; pack->numfiles = numpackfiles; pack->files = newfiles; @@ -1588,13 +1582,13 @@ void COM_AddGameDirectory(char* dir) pack_t* pak; char pakfile[MAX_OSPATH]; - strcpy_s(com_gamedir, sizeof(com_gamedir), dir); + strlcpy(com_gamedir, dir, sizeof(com_gamedir)); // // add the directory to the search path // search = (searchpath_t *) Hunk_Alloc(sizeof(searchpath_t)); - strcpy_s(search->filename, sizeof(search->filename), dir); + strlcpy(search->filename, dir, sizeof(search->filename)); search->next = com_searchpaths; com_searchpaths = search; @@ -1602,13 +1596,13 @@ void COM_AddGameDirectory(char* dir) // add any pak files in the format pak0.pak pak1.pak, ... // for (i = 0;; i++) { - sprintf_s(pakfile, sizeof(pakfile), "%s/pak%i.pak", dir, i); + snprintf(pakfile, sizeof(pakfile), "%s/pak%i.pak", dir, i); pak = COM_LoadPackFile(pakfile); if (!pak) { break; } - search = (searchpath_t *) Hunk_Alloc(sizeof(searchpath_t)); + search = static_cast(Hunk_Alloc(sizeof(searchpath_t))); search->pack = pak; search->next = com_searchpaths; com_searchpaths = search; @@ -1636,9 +1630,9 @@ void COM_InitFilesystem(void) // i = COM_CheckParm("-basedir"); if (i && i < com_argc - 1) { - strcpy_s(basedir, sizeof(basedir), com_argv[i + 1]); + strlcpy(basedir, com_argv[i + 1], sizeof(basedir)); } else { - strcpy_s(basedir, sizeof(basedir), host_parms.basedir); + strlcpy(basedir, host_parms.basedir, sizeof(basedir)); } j = (int)strlen(basedir); @@ -1649,6 +1643,8 @@ void COM_InitFilesystem(void) } } +/* TODO: fix cache dir for UNIX */ +#if 0 // // -cachedir // Overrides the system supplied cache directory (NULL or /qcache) @@ -1666,6 +1662,7 @@ void COM_InitFilesystem(void) } else { com_cachedir[0] = 0; } +#endif // // start up with GAMENAME by default (id1) @@ -1703,14 +1700,14 @@ void COM_InitFilesystem(void) break; } - search = (searchpath_t *) Hunk_Alloc(sizeof(searchpath_t)); + search = static_cast(Hunk_Alloc(sizeof(searchpath_t))); if (!strcmp(COM_FileExtension(com_argv[i]), "pak")) { search->pack = COM_LoadPackFile(com_argv[i]); if (!search->pack) { Sys_Error("Couldn't load packfile: %s", com_argv[i]); } } else { - strcpy_s(search->filename, sizeof(search->filename), com_argv[i]); + strlcpy(search->filename, com_argv[i], sizeof(search->filename)); } search->next = com_searchpaths; diff --git a/src/common.hpp b/src/common.hpp index a551402..1038b34 100644 --- a/src/common.hpp +++ b/src/common.hpp @@ -26,10 +26,12 @@ typedef struct link_s { struct link_s *prev, *next; } link_t; +#include + // (type *)STRUCT_FROM_LINK(link_t *link, type, member) // ent = STRUCT_FROM_LINK(link,entity_t,order) // FIXME: remove this mess! -#define STRUCT_FROM_LINK(l, t, m) ((t*)((byte*)l - (intptr_t)&(((t*)0)->m))) +#define STRUCT_FROM_LINK(l, t, m) (reinterpret_cast(reinterpret_cast(l) - offsetof(t, m))) //============================================================================ @@ -156,10 +158,10 @@ inline void SZ_Write(sizebuf_t* buf, const void* data, int length) inline int Q_strcasecmp(const char* s1, const char* s2) { - int c1, c2; + int c1; do { c1 = *s1++; - c2 = *s2++; + int c2 = *s2++; if (c1 != c2) { if (c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A'); if (c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A'); @@ -219,7 +221,7 @@ extern int com_filesize; extern char com_gamedir[MAX_OSPATH]; -void COM_WriteFile(const char* filename, void* data, int len); +void COM_WriteFile(const char* filename, const void* data, int len); int COM_FindFile(const char* filename, int* handle, FILE** file); byte* COM_LoadFile(const char* path, int usehunk); diff --git a/src/console.cpp b/src/console.cpp index a03e37d..84d2c3b 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -1,8 +1,12 @@ // console.cpp -- console text display and input +#ifdef _MSC_VER #include -#include #include +#else +#include +#endif +#include #include #include "quakedef.hpp" @@ -142,7 +146,7 @@ If the line width has changed, reformat the buffer. */ void Con_CheckResize(void) { - int i, j, width, oldwidth, oldtotallines, numlines, numchars; + int width; char tbuf[CON_TEXTSIZE]; width = (vid.width >> 3) - 2; @@ -158,17 +162,17 @@ void Con_CheckResize(void) con_totallines = CON_TEXTSIZE / con_linewidth; Q_memset(con_text, ' ', CON_TEXTSIZE); } else { - oldwidth = con_linewidth; + int oldwidth = con_linewidth; con_linewidth = width; - oldtotallines = con_totallines; + int oldtotallines = con_totallines; con_totallines = CON_TEXTSIZE / con_linewidth; - numlines = oldtotallines; + int numlines = oldtotallines; if (con_totallines < numlines) { numlines = con_totallines; } - numchars = oldwidth; + int numchars = oldwidth; if (con_linewidth < numchars) { numchars = con_linewidth; @@ -177,8 +181,8 @@ void Con_CheckResize(void) Q_memcpy(tbuf, con_text, CON_TEXTSIZE); Q_memset(con_text, ' ', CON_TEXTSIZE); - for (i = 0; i < numlines; i++) { - for (j = 0; j < numchars; j++) { + for (int i = 0; i < numlines; i++) { + for (int j = 0; j < numchars; j++) { con_text[(con_totallines - 1 - i) * con_linewidth + j] = tbuf[((con_current - i + oldtotallines) % oldtotallines) * oldwidth + j]; } } @@ -205,12 +209,12 @@ void Con_Init(void) if (con_debuglog) { if (strlen(com_gamedir) < (MAXGAMEDIRLEN - strlen(t2))) { - sprintf_s(temp, sizeof(temp), "%s%s", com_gamedir, t2); - _unlink(temp); + snprintf(temp, sizeof(temp), "%s%s", com_gamedir, t2); + unlink(temp); } } - con_text = (char *) Hunk_Alloc(CON_TEXTSIZE, "context"); + con_text = static_cast(Hunk_Alloc(CON_TEXTSIZE, "context")); Q_memset(con_text, ' ', CON_TEXTSIZE); con_linewidth = -1; Con_CheckResize(); @@ -343,11 +347,11 @@ void Con_DebugLog(const char* file, const char* fmt, ...) int fd; va_start(argptr, fmt); - vsprintf_s(data, sizeof(data), fmt, argptr); + vsnprintf(data, sizeof(data), fmt, argptr); va_end(argptr); - _sopen_s(&fd, file, O_WRONLY | O_CREAT | O_APPEND, _SH_DENYNO, _S_IREAD | _S_IWRITE); - _write(fd, data, (unsigned int)strlen(data)); - _close(fd); + fd = open(file, O_WRONLY | O_CREAT | O_APPEND, 0666); + write(fd, data, (unsigned int)strlen(data)); + close(fd); } /* @@ -367,7 +371,7 @@ void Con_Printf(const char* fmt, ...) static qboolean inupdate; va_start(argptr, fmt); - vsprintf_s(msg, sizeof(msg), fmt, argptr); + vsnprintf(msg, sizeof(msg), fmt, argptr); va_end(argptr); // also echo to debugging console @@ -418,7 +422,7 @@ void Con_DPrintf(const char* fmt, ...) } va_start(argptr, fmt); - vsprintf_s(msg, sizeof(msg), fmt, argptr); + vsnprintf(msg, sizeof(msg), fmt, argptr); va_end(argptr); Con_Printf("%s", msg); @@ -482,11 +486,9 @@ Draws the last few lines of output transparently over the game top void Con_DrawNotify(void) { int x, v; - char* text; - int i; float time; - v = 0; - for (i = con_current - NUM_CON_TIMES + 1; i <= con_current; i++) { + v = 0; + for (int i = con_current - NUM_CON_TIMES + 1; i <= con_current; i++) { if (i < 0) { continue; } @@ -501,7 +503,7 @@ void Con_DrawNotify(void) continue; } - text = con_text + (i % con_totallines) * con_linewidth; + const char* text = con_text + (i % con_totallines) * con_linewidth; clearnotify = 0; scr_copytop = 1; @@ -544,10 +546,8 @@ The typing input line at the bottom should only be drawn if typing is allowed */ void Con_DrawConsole(int lines, qboolean drawinput) { - int i, x, y; + int x, y; int rows; - char* text; - int j; if (lines <= 0) { return; @@ -559,16 +559,16 @@ void Con_DrawConsole(int lines, qboolean drawinput) // draw the text con_vislines = lines; - rows = (lines - 16) >> 3; // rows of text to draw + rows = (lines - 16) / 8; // rows of text to draw y = lines - 16 - (rows << 3); // may start slightly negative - for (i = con_current - rows + 1; i <= con_current; i++, y += 8) { - j = i - con_backscroll; + for (int i = con_current - rows + 1; i <= con_current; i++, y += 8) { + int j = i - con_backscroll; if (j < 0) { j = 0; } - text = con_text + (j % con_totallines) * con_linewidth; + const char* text = con_text + (j % con_totallines) * con_linewidth; for (x = 0; x < con_linewidth; x++) { Draw_Character((x + 1) << 3, y, text[x]); diff --git a/src/cvar.cpp b/src/cvar.cpp index d645282..3a121ac 100644 --- a/src/cvar.cpp +++ b/src/cvar.cpp @@ -57,7 +57,7 @@ VariableValue */ float CvarRegistry::VariableValue(std::string_view var_name) { - cvar_t* var = FindVar(var_name); + const cvar_t* var = FindVar(var_name); if (!var) { return 0.0f; } @@ -71,7 +71,7 @@ VariableString */ std::string_view CvarRegistry::VariableString(std::string_view var_name) { - cvar_t* var = FindVar(var_name); + const cvar_t* var = FindVar(var_name); if (!var) { return ""; } @@ -114,7 +114,7 @@ void CvarRegistry::Set(std::string_view var_name, std::string_view value) Z_Free(const_cast(var->string)); // free the old value string - char* new_str = (char *) Z_Malloc(static_cast(value.length()) + 1); + char* new_str = static_cast(Z_Malloc(static_cast(value.length()) + 1)); Q_memcpy(new_str, const_cast(value.data()), static_cast(value.length())); new_str[value.length()] = '\0'; var->string = new_str; @@ -134,7 +134,7 @@ SetValue void CvarRegistry::SetValue(std::string_view var_name, float value) { char val[32]; - sprintf_s(val, sizeof(val), "%f", value); + snprintf(val, sizeof(val), "%f", value); Set(var_name, val); } @@ -159,7 +159,7 @@ void CvarRegistry::Register(cvar_t* variable) // copy the value off, because future sets will Z_Free it const char* oldstr = variable->string; - char* new_str = (char *) Z_Malloc(Q_strlen(oldstr) + 1); + char* new_str = static_cast(Z_Malloc(Q_strlen(oldstr) + 1)); Q_strcpy(new_str, oldstr); variable->string = new_str; variable->value = Q_atof(variable->string); @@ -198,7 +198,7 @@ WriteVariables */ void CvarRegistry::WriteVariables(std::FILE* f) { - for (cvar_t* var = state_.vars; var; var = var->next) { + for (const cvar_t* var = state_.vars; var; var = var->next) { if (var->archive) { std::fprintf(f, "%s \"%s\"\n", var->name, var->string); } diff --git a/src/draw.cpp b/src/draw.cpp index c535cd3..59a0904 100644 --- a/src/draw.cpp +++ b/src/draw.cpp @@ -79,10 +79,10 @@ qpic_t* Draw_CachePic(const char* path) } menu_numcachepics++; - strcpy_s(pic->name, sizeof(pic->name), path); + strlcpy(pic->name, path, sizeof(pic->name)); } - dat = (qpic_t *) Cache_Check(&pic->cache); + dat = static_cast(Cache_Check(&pic->cache)); if (dat) { return dat; @@ -93,7 +93,7 @@ qpic_t* Draw_CachePic(const char* path) // COM_LoadCacheFile(path, &pic->cache); - dat = (qpic_t*)pic->cache.data; + dat = static_cast(pic->cache.data); if (!dat) { Sys_Error("Draw_CachePic: failed to load %s", path); } @@ -110,9 +110,9 @@ Draw_Init */ void Draw_Init(void) { - draw_chars = (byte*)W_GetLumpName("conchars"); - draw_disc = (qpic_t*)W_GetLumpName("disc"); - draw_backtile = (qpic_t*)W_GetLumpName("backtile"); + draw_chars = static_cast(W_GetLumpName("conchars")); + draw_disc = static_cast(W_GetLumpName("disc")); + draw_backtile = static_cast(W_GetLumpName("backtile")); r_rectdesc.width = draw_backtile->width; r_rectdesc.height = draw_backtile->height; @@ -207,7 +207,7 @@ void Draw_Character(int x, int y, int num) } } else { // FIXME: pre-expand to native format? - pusdest = (unsigned short*)((byte*)vid.conbuffer + y * vid.conrowbytes + (x << 1)); + pusdest = reinterpret_cast(static_cast(vid.conbuffer) + y * vid.conrowbytes + (x << 1)); while (drawline--) { if (source[0]) { @@ -267,11 +267,10 @@ void Draw_String(int x, int y, const char* str) Draw_Pic ============= */ -void Draw_Pic(int x, int y, qpic_t* pic) +void Draw_Pic(int x, int y, const qpic_t* pic) { - byte *dest, *source; - unsigned short* pusdest; - int v, u; + const byte* source; + int v; if ((x < 0) || (unsigned)(x + pic->width) > vid.width || (y < 0) || (unsigned)(y + pic->height) > vid.height) { Sys_Error("Draw_Pic: bad coordinates"); @@ -280,7 +279,7 @@ void Draw_Pic(int x, int y, qpic_t* pic) source = pic->data; if (r_pixbytes == 1) { - dest = vid.buffer + y * vid.rowbytes + x; + byte* dest = vid.buffer + y * vid.rowbytes + x; for (v = 0; v < pic->height; v++) { Q_memcpy(dest, source, pic->width); @@ -289,10 +288,10 @@ void Draw_Pic(int x, int y, qpic_t* pic) } } else { // FIXME: pretranslate at load time? - pusdest = (unsigned short*)vid.buffer + y * (vid.rowbytes >> 1) + x; + unsigned short* pusdest = reinterpret_cast(vid.buffer) + y * (vid.rowbytes >> 1) + x; for (v = 0; v < pic->height; v++) { - for (u = 0; u < pic->width; u++) { + for (int u = 0; u < pic->width; u++) { pusdest[u] = d_8to16table[source[u]]; } @@ -307,10 +306,10 @@ void Draw_Pic(int x, int y, qpic_t* pic) Draw_TransPic ============= */ -void Draw_TransPic(int x, int y, qpic_t* pic) +void Draw_TransPic(int x, int y, const qpic_t* pic) { - byte *dest, *source, tbyte; - unsigned short* pusdest; + const byte* source; + byte tbyte; int v, u; if (x < 0 || (unsigned)(x + pic->width) > vid.width || y < 0 || (unsigned)(y + pic->height) > vid.height) { @@ -320,7 +319,7 @@ void Draw_TransPic(int x, int y, qpic_t* pic) source = pic->data; if (r_pixbytes == 1) { - dest = vid.buffer + y * vid.rowbytes + x; + byte* dest = vid.buffer + y * vid.rowbytes + x; if (pic->width & 7) { // general for (v = 0; v < pic->height; v++) { @@ -374,7 +373,7 @@ void Draw_TransPic(int x, int y, qpic_t* pic) } } else { // FIXME: pretranslate at load time? - pusdest = (unsigned short*)vid.buffer + y * (vid.rowbytes >> 1) + x; + unsigned short* pusdest = reinterpret_cast(vid.buffer) + y * (vid.rowbytes >> 1) + x; for (v = 0; v < pic->height; v++) { for (u = 0; u < pic->width; u++) { @@ -396,10 +395,10 @@ void Draw_TransPic(int x, int y, qpic_t* pic) Draw_TransPicTranslate ============= */ -void Draw_TransPicTranslate(int x, int y, qpic_t* pic, byte* translation) +void Draw_TransPicTranslate(int x, int y, const qpic_t* pic, const byte* translation) { - byte *dest, *source, tbyte; - unsigned short* pusdest; + const byte* source; + byte tbyte; int v, u; if (x < 0 || (unsigned)(x + pic->width) > vid.width || y < 0 || (unsigned)(y + pic->height) > vid.height) { @@ -409,7 +408,7 @@ void Draw_TransPicTranslate(int x, int y, qpic_t* pic, byte* translation) source = pic->data; if (r_pixbytes == 1) { - dest = vid.buffer + y * vid.rowbytes + x; + byte* dest = vid.buffer + y * vid.rowbytes + x; if (pic->width & 7) { // general for (v = 0; v < pic->height; v++) { @@ -463,7 +462,7 @@ void Draw_TransPicTranslate(int x, int y, qpic_t* pic, byte* translation) } } else { // FIXME: pretranslate at load time? - pusdest = (unsigned short*)vid.buffer + y * (vid.rowbytes >> 1) + x; + unsigned short* pusdest = reinterpret_cast(vid.buffer) + y * (vid.rowbytes >> 1) + x; for (v = 0; v < pic->height; v++) { for (u = 0; u < pic->width; u++) { @@ -513,17 +512,17 @@ Draw_ConsoleBackground void Draw_ConsoleBackground(int lines) { int y, v, x; - byte *src, *dest; - unsigned short* pusdest; + const byte* src; + byte* dest; int f, fstep; - qpic_t* conback; + const qpic_t* conback; char ver[100]; conback = Draw_CachePic("gfx/conback.lmp"); // hack the version number directly into the pic - dest = conback->data + 320 - 43 + 320 * 186; - sprintf_s(ver, sizeof(ver), "%4.2f", VERSION); + dest = (byte*)conback->data + 320 - 43 + 320 * 186; + snprintf(ver, sizeof(ver), "%4.2f", VERSION); for (x = 0; x < static_cast(strlen(ver)); x++) { Draw_CharToConback(ver[x], dest + (x << 3)); @@ -554,7 +553,7 @@ void Draw_ConsoleBackground(int lines) } } } else { - pusdest = (unsigned short*)vid.conbuffer; + unsigned short* pusdest = reinterpret_cast(vid.conbuffer); for (y = 0; y < lines; y++, pusdest += (vid.conrowbytes >> 1)) { // FIXME: pre-expand to native format? @@ -582,10 +581,9 @@ void Draw_ConsoleBackground(int lines) R_DrawRect8 ============== */ -void R_DrawRect8(vrect_t* prect, int rowbytes, byte* psrc, int transparent) +void R_DrawRect8(const vrect_t* prect, int rowbytes, const byte* psrc, int transparent) { - byte t; - int i, j, srcdelta, destdelta; + int i, srcdelta, destdelta; byte* pdest; pdest = vid.buffer + (prect->y * vid.rowbytes) + prect->x; @@ -595,8 +593,8 @@ void R_DrawRect8(vrect_t* prect, int rowbytes, byte* psrc, int transparent) if (transparent) { for (i = 0; i < prect->height; i++) { - for (j = 0; j < prect->width; j++) { - t = *psrc; + for (int j = 0; j < prect->width; j++) { + byte t = *psrc; if (t != TRANSPARENT_COLOR) { *pdest = t; } @@ -622,23 +620,22 @@ void R_DrawRect8(vrect_t* prect, int rowbytes, byte* psrc, int transparent) R_DrawRect16 ============== */ -void R_DrawRect16(vrect_t* prect, int rowbytes, byte* psrc, int transparent) +void R_DrawRect16(const vrect_t* prect, int rowbytes, const byte* psrc, int transparent) { - byte t; - int i, j, srcdelta, destdelta; + int i, srcdelta, destdelta; unsigned short* pdest; // FIXME: would it be better to pre-expand native-format versions? - pdest = (unsigned short*)vid.buffer + (prect->y * (vid.rowbytes >> 1)) + prect->x; + pdest = reinterpret_cast(vid.buffer) + (prect->y * (vid.rowbytes >> 1)) + prect->x; srcdelta = rowbytes - prect->width; destdelta = (vid.rowbytes >> 1) - prect->width; if (transparent) { for (i = 0; i < prect->height; i++) { - for (j = 0; j < prect->width; j++) { - t = *psrc; + for (int j = 0; j < prect->width; j++) { + byte t = *psrc; if (t != TRANSPARENT_COLOR) { *pdest = d_8to16table[t]; } @@ -652,7 +649,7 @@ void R_DrawRect16(vrect_t* prect, int rowbytes, byte* psrc, int transparent) } } else { for (i = 0; i < prect->height; i++) { - for (j = 0; j < prect->width; j++) { + for (int j = 0; j < prect->width; j++) { *pdest = d_8to16table[*psrc]; psrc++; pdest++; @@ -674,8 +671,7 @@ refresh window. */ void Draw_TileClear(int x, int y, int w, int h) { - int width, height, tileoffsetx, tileoffsety; - byte* psrc; + int height, tileoffsety; vrect_t vr; r_rectdesc.rect.x = x; @@ -690,7 +686,7 @@ void Draw_TileClear(int x, int y, int w, int h) while (height > 0) { vr.x = r_rectdesc.rect.x; - width = r_rectdesc.rect.width; + int width = r_rectdesc.rect.width; if (tileoffsety != 0) { vr.height = r_rectdesc.height - tileoffsety; @@ -702,7 +698,7 @@ void Draw_TileClear(int x, int y, int w, int h) vr.height = height; } - tileoffsetx = vr.x % r_rectdesc.width; + int tileoffsetx = vr.x % r_rectdesc.width; while (width > 0) { if (tileoffsetx != 0) { @@ -715,7 +711,7 @@ void Draw_TileClear(int x, int y, int w, int h) vr.width = width; } - psrc = r_rectdesc.ptexbytes + (tileoffsety * r_rectdesc.rowbytes) + tileoffsetx; + const byte* psrc = r_rectdesc.ptexbytes + (tileoffsety * r_rectdesc.rowbytes) + tileoffsetx; if (r_pixbytes == 1) { R_DrawRect8(&vr, r_rectdesc.rowbytes, psrc, 0); @@ -743,22 +739,19 @@ Fills a box of pixels with a single color */ void Draw_Fill(int x, int y, int w, int h, int c) { - byte* dest; - unsigned short* pusdest; - unsigned uc; int u, v; if (r_pixbytes == 1) { - dest = vid.buffer + y * vid.rowbytes + x; + byte* dest = vid.buffer + y * vid.rowbytes + x; for (v = 0; v < h; v++, dest += vid.rowbytes) { for (u = 0; u < w; u++) { dest[u] = static_cast(c); } } } else { - uc = d_8to16table[c]; + unsigned uc = d_8to16table[c]; - pusdest = (unsigned short*)vid.buffer + y * (vid.rowbytes >> 1) + x; + unsigned short* pusdest = reinterpret_cast(vid.buffer) + y * (vid.rowbytes >> 1) + x; for (v = 0; v < h; v++, pusdest += (vid.rowbytes >> 1)) { for (u = 0; u < w; u++) { pusdest[u] = static_cast(uc); @@ -778,7 +771,6 @@ Draw_FadeScreen void Draw_FadeScreen(void) { int x, y; - byte* pbuf; VID_UnlockBuffer(); S_ExtraUpdate(); @@ -787,7 +779,7 @@ void Draw_FadeScreen(void) for (y = 0; y < (int)vid.height; y++) { int t; - pbuf = (byte*)(vid.buffer + vid.rowbytes * y); + byte* pbuf = vid.buffer + vid.rowbytes * y; t = (y & 1) << 1; for (x = 0; x < (int)vid.width; x++) { diff --git a/src/draw.hpp b/src/draw.hpp index 27c7e9a..0b2c04f 100644 --- a/src/draw.hpp +++ b/src/draw.hpp @@ -8,9 +8,9 @@ extern qpic_t* draw_disc; void Draw_Init(void); void Draw_Character(int x, int y, int num); -void Draw_Pic(int x, int y, qpic_t* pic); -void Draw_TransPic(int x, int y, qpic_t* pic); -void Draw_TransPicTranslate(int x, int y, qpic_t* pic, byte* translation); +void Draw_Pic(int x, int y, const qpic_t* pic); +void Draw_TransPic(int x, int y, const qpic_t* pic); +void Draw_TransPicTranslate(int x, int y, const qpic_t* pic, const byte* translation); void Draw_ConsoleBackground(int lines); void Draw_BeginDisc(void); void Draw_EndDisc(void); diff --git a/src/host.cpp b/src/host.cpp index 941ef1a..ae34f20 100644 --- a/src/host.cpp +++ b/src/host.cpp @@ -77,7 +77,7 @@ Host_EndGame char string[1024]; va_start(argptr, message); - vsprintf_s(string, sizeof(string), message, argptr); + vsnprintf(string, sizeof(string), message, argptr); va_end(argptr); Con_DPrintf("Host_EndGame: %s\n", string); @@ -120,7 +120,7 @@ This shuts down both the client and server SCR_EndLoadingPlaque(); // reenable screen updates va_start(argptr, error); - vsprintf_s(string, sizeof(string), error, argptr); + vsnprintf(string, sizeof(string), error, argptr); va_end(argptr); Con_Printf("Host_Error: %s\n", string); @@ -187,7 +187,7 @@ void Host_FindMaxClients(void) svs.maxclientslimit = 4; } - svs.clients = (client_s *) Hunk_Alloc(svs.maxclientslimit * sizeof(client_t), "clients"); + svs.clients = static_cast(Hunk_Alloc(svs.maxclientslimit * sizeof(client_t), "clients")); if (svs.maxclients > 1) { Cvar::SetValue("deathmatch", 1.0); @@ -244,7 +244,7 @@ void Host_WriteConfiguration(void) // dedicated servers initialize the host but don't parse and set the // config.cfg cvars if (host_initialized & !isDedicated) { - fopen_s(&f, va("%s/config.cfg", com_gamedir), "w"); + f = fopen(va("%s/config.cfg", com_gamedir), "w"); if (!f) { Con_Printf("Couldn't write config.cfg.\n"); @@ -278,7 +278,7 @@ void SV_ClientPrintf(const char* fmt, ...) char string[1024]; va_start(argptr, fmt); - vsprintf_s(string, sizeof(string), fmt, argptr); + vsnprintf(string, sizeof(string), fmt, argptr); va_end(argptr); MSG_WriteByte(&host_client->message, svc_print); @@ -299,7 +299,7 @@ void SV_BroadcastPrintf(const char* fmt, ...) int i; va_start(argptr, fmt); - vsprintf_s(string, sizeof(string), fmt, argptr); + vsnprintf(string, sizeof(string), fmt, argptr); va_end(argptr); for (i = 0; i < svs.maxclients; i++) { @@ -322,7 +322,6 @@ if (crash = true), don't bother sending signofs */ void SV_DropClient(qboolean crash) { - int saveSelf; int i; client_t* client; @@ -336,7 +335,7 @@ void SV_DropClient(qboolean crash) if (host_client->edict && host_client->spawned) { // call the prog function for removing a client // this will set the body to a dead frame, among other things - saveSelf = pr_global_struct->self; + int saveSelf = pr_global_struct->self; pr_global_struct->self = static_cast(EDICT_TO_PROG(host_client->edict)); PR_ExecuteProgram(pr_global_struct->ClientDisconnect); pr_global_struct->self = saveSelf; @@ -390,7 +389,7 @@ void Host_ClientCommands(const char* fmt, ...) char string[1024]; va_start(argptr, fmt); - vsprintf_s(string, sizeof(string), fmt, argptr); + vsnprintf(string, sizeof(string), fmt, argptr); va_end(argptr); MSG_WriteByte(&host_client->message, svc_stufftext); @@ -409,7 +408,7 @@ void Host_ShutdownServer(qboolean crash) int i; int count; sizebuf_t buf; - char message[4]; + char message[4] = {}; double start; if (!sv.active) { @@ -445,7 +444,7 @@ void Host_ShutdownServer(qboolean crash) } while (count); // make sure all the clients know we're disconnecting - buf.data = (byte*)message; + buf.data = reinterpret_cast(message); buf.maxsize = 4; buf.cursize = 0; MSG_WriteByte(&buf, svc_disconnect); @@ -537,10 +536,8 @@ Add them exactly as if they had been typed at the console */ void Host_GetConsoleCommands(void) { - char* cmd; - while (1) { - cmd = Sys_ConsoleInput(); + char* cmd = Sys_ConsoleInput(); if (!cmd) { break; } @@ -640,14 +637,10 @@ Runs all active servers */ void _Host_Frame(float time) { - static double time1 = 0; - static double time2 = 0; - static double time3 = 0; - int pass1, pass2, pass3; try { // keep the random time dependent - rand(); + (void)rand(); // decide the simulation time if (!Host_FilterTime(time)) { @@ -703,12 +696,14 @@ void _Host_Frame(float time) } // update video + double time1 = 0; if (host_speeds.value) { time1 = Sys_FloatTime(); } SCR_UpdateScreen(); + double time2 = 0; if (host_speeds.value) { time2 = Sys_FloatTime(); } @@ -724,10 +719,11 @@ void _Host_Frame(float time) CDAudio_Update(); if (host_speeds.value) { - pass1 = static_cast((time1 - time3) * 1000); + static double time3 = 0; + int pass1 = static_cast((time1 - time3) * 1000); time3 = Sys_FloatTime(); - pass2 = static_cast((time2 - time1) * 1000); - pass3 = static_cast((time3 - time2) * 1000); + int pass2 = static_cast((time2 - time1) * 1000); + int pass3 = static_cast((time3 - time2) * 1000); Con_Printf("%3i tot %3i server %3i gfx %3i snd\n", pass1 + pass2 + pass3, pass1, pass2, pass3); } @@ -802,11 +798,11 @@ void Host_InitVCR(quakeparms_t* parms) } Sys_FileRead(vcrFile, &com_argc, sizeof(int)); - com_argv = (char**)malloc(com_argc * sizeof(char*)); + com_argv = static_cast(malloc(com_argc * sizeof(char*))); com_argv[0] = parms->argv[0]; for (i = 0; i < com_argc; i++) { Sys_FileRead(vcrFile, &len, sizeof(int)); - p = (char*)malloc(len); + p = static_cast(malloc(len)); Sys_FileRead(vcrFile, p, len); com_argv[i + 1] = p; } @@ -890,12 +886,12 @@ void Host_Init(quakeparms_t* parms) R_InitTextures(); // needed even for dedicated servers if (cls.state != ca_dedicated) { - host_basepal = (byte*)COM_LoadHunkFile("gfx/palette.lmp"); + host_basepal = COM_LoadHunkFile("gfx/palette.lmp"); if (!host_basepal) { Sys_Error("Couldn't load gfx/palette.lmp"); } - host_colormap = (byte*)COM_LoadHunkFile("gfx/colormap.lmp"); + host_colormap = COM_LoadHunkFile("gfx/colormap.lmp"); if (!host_colormap) { Sys_Error("Couldn't load gfx/colormap.lmp"); } diff --git a/src/host_cmd.cpp b/src/host_cmd.cpp index cd318bc..a0036e3 100644 --- a/src/host_cmd.cpp +++ b/src/host_cmd.cpp @@ -288,7 +288,7 @@ void Host_Map_f(void) Q_strcat(cls.mapstring, Cmd::Argv(i)); Q_strcat(cls.mapstring, " "); } - strcat_s(cls.mapstring, sizeof(cls.mapstring), "\n"); + strlcat(cls.mapstring, "\n", sizeof(cls.mapstring)); svs.serverflags = 0; // haven't completed an episode yet Q_strcpy(name, Cmd::Argv(1)); @@ -298,7 +298,7 @@ void Host_Map_f(void) } if (cls.state != ca_dedicated) { - strcpy_s(cls.spawnparms, sizeof(cls.spawnparms), ""); + strlcpy(cls.spawnparms, "", sizeof(cls.spawnparms)); for (i = 2; i < Cmd::Argc(); i++) { Q_strcat(cls.spawnparms, Cmd::Argv(i)); @@ -356,7 +356,7 @@ void Host_Restart_f(void) return; } - strcpy_s(mapname, sizeof(mapname), sv.name); // must copy out, because it gets cleared + strlcpy(mapname, sv.name, sizeof(mapname)); // must copy out, because it gets cleared // in sv_spawnserver SV_SpawnServer(mapname); } @@ -423,7 +423,7 @@ void Host_SavegameComment(char* text) text[i] = ' '; } memcpy(text, cl.levelname, strlen(cl.levelname)); - sprintf_s(kills, sizeof(kills), "kills:%3i/%3i", cl.stats[STAT_MONSTERS], + snprintf(kills, sizeof(kills), "kills:%3i/%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); memcpy(text + 22, kills, strlen(kills)); // convert space to _ to make stdio happy @@ -489,11 +489,11 @@ void Host_Savegame_f(void) } } - sprintf_s(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); + snprintf(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); COM_DefaultExtension(name, ".sav"); Con_Printf("Saving game to %s...\n", name); - fopen_s(&f, name, "w"); + f = fopen(name, "w"); if (!f) { Con_Printf("ERROR: couldn't open.\n"); @@ -540,8 +540,8 @@ void Host_Loadgame_f(void) FILE* f; char mapname[MAX_QPATH]; float time, tfloat; - char str[32768], *start; - int i, r; + char str[32768]; + int i; edict_t* ent; int entnum; int version; @@ -559,7 +559,7 @@ void Host_Loadgame_f(void) cls.demonum = -1; // stop demo loop in case this fails - sprintf_s(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); + snprintf(name, sizeof(name), "%s/%s", com_gamedir, std::string(Cmd::Argv(1)).c_str()); COM_DefaultExtension(name, ".sav"); // we can't call SCR_BeginLoadingPlaque, because too much stack space has @@ -567,14 +567,14 @@ void Host_Loadgame_f(void) // SCR_BeginLoadingPlaque (); Con_Printf("Loading game from %s...\n", name); - fopen_s(&f, name, "r"); + f = fopen(name, "r"); if (!f) { Con_Printf("ERROR: couldn't open.\n"); return; } - fscanf_s(f, "%i\n", &version); + fscanf(f, "%i\n", &version); if (version != SAVEGAME_VERSION) { fclose(f); Con_Printf("Savegame is version %i, not %i\n", version, SAVEGAME_VERSION); @@ -582,18 +582,18 @@ void Host_Loadgame_f(void) return; } - fscanf_s(f, "%s\n", str, (unsigned)sizeof(str)); + fscanf(f, "%s\n", str); for (i = 0; i < NUM_SPAWN_PARMS; i++) { - fscanf_s(f, "%f\n", &spawn_parms[i]); + fscanf(f, "%f\n", &spawn_parms[i]); } // this silliness is so we can load 1.06 save files, which have float skill values - fscanf_s(f, "%f\n", &tfloat); + fscanf(f, "%f\n", &tfloat); current_skill = (int)(tfloat + 0.1); Cvar::SetValue("skill", (float)current_skill); - fscanf_s(f, "%s\n", mapname, (unsigned)sizeof(mapname)); - fscanf_s(f, "%f\n", &time); + fscanf(f, "%s\n", mapname); + fscanf(f, "%f\n", &time); CL_Disconnect_f(); @@ -610,16 +610,16 @@ void Host_Loadgame_f(void) // load the light styles for (i = 0; i < MAX_LIGHTSTYLES; i++) { - fscanf_s(f, "%s\n", str, (unsigned)sizeof(str)); + fscanf(f, "%s\n", str); sv.lightstyles[i] = (char *) Hunk_Alloc((int)strlen(str) + 1); - strcpy_s(sv.lightstyles[i], strlen(str) + 1, str); + strlcpy(sv.lightstyles[i], str, strlen(str) + 1); } // load the edicts out of the savegame file entnum = -1; // -1 is the globals while (!feof(f)) { for (i = 0; i < static_cast(sizeof(str) - 1); i++) { - r = fgetc(f); + int r = fgetc(f); if (r == EOF || !r) { break; } @@ -635,7 +635,7 @@ void Host_Loadgame_f(void) } str[i] = 0; - start = COM_Parse(str); + const char* start = COM_Parse(str); if (!com_token[0]) { break; // end of file } @@ -645,13 +645,13 @@ void Host_Loadgame_f(void) } if (entnum == -1) { // parse the global vars - ED_ParseGlobals(start); + ED_ParseGlobals(const_cast(start)); } else { // parse an edict ent = EDICT_NUM(entnum); std::memset(reinterpret_cast(&ent->v), 0, static_cast(progs->entityfields) * 4); ent->free = false; - ED_ParseEdict(start, ent); + ED_ParseEdict(const_cast(start), ent); // link it into the bsp tree if (!ent->free) { @@ -778,19 +778,19 @@ void Host_Say(qboolean teamonly) // turn on color set 1 if (!fromServer) { - sprintf_s((char*)text, sizeof(text), "%c%s: ", 1, save->name); + snprintf((char*)text, sizeof(text), "%c%s: ", 1, save->name); } else { - sprintf_s((char*)text, sizeof(text), "%c<%s> ", 1, hostname.string); + snprintf((char*)text, sizeof(text), "%c<%s> ", 1, hostname.string); } - j = sizeof(text) - 2 - Q_strlen((char*)text); // -2 for /n and null terminator + j = sizeof(text) - 2 - Q_strlen(reinterpret_cast(text)); // -2 for /n and null terminator if (arg_str.length() > (size_t)j) { arg_str.resize(j); } const char* p = arg_str.c_str(); - strcat_s((char*)text, sizeof(text), p); - strcat_s((char*)text, sizeof(text), "\n"); + strlcat((char*)text, p, sizeof(text)); + strlcat((char*)text, "\n", sizeof(text)); for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { if (!client || !client->active || !client->spawned) { @@ -846,8 +846,8 @@ void Host_Tell_f(void) } const char* p = arg_str.c_str(); - strcat_s(text, sizeof(text), p); - strcat_s(text, sizeof(text), "\n"); + strlcat(text, p, sizeof(text)); + strlcat(text, "\n", sizeof(text)); save = host_client; for (j = 0, client = svs.clients; j < svs.maxclients; j++, client++) { @@ -1151,8 +1151,6 @@ Kicks a user off of the server */ void Host_Kick_f(void) { - const char* who; - const char* message = NULL; client_t* save; int i; qboolean byNumber = false; @@ -1196,6 +1194,8 @@ void Host_Kick_f(void) } if (i < svs.maxclients) { + const char* who; + const char* message = nullptr; if (Cmd::state.source == Cmd::Source::Command) { if (cls.state == ca_dedicated) { who = "Console"; @@ -1222,7 +1222,7 @@ void Host_Kick_f(void) message += Cmd::Argv(2).length(); // skip the number } - while (*message && *message == ' ') { + while (*message == ' ') { message++; } } @@ -1461,7 +1461,7 @@ void Host_Viewframe_f(void) return; } - m = cl.model_precache[(int)e->v.modelindex]; + m = cl.model_precache[static_cast(e->v.modelindex)]; f = Q_atoi(Cmd::Argv(1)); if (f >= m->numframes) { @@ -1476,7 +1476,7 @@ void PrintFrameName(model_t* m, int frame) aliashdr_t* hdr; maliasframedesc_t* pframedesc; - hdr = (aliashdr_t*)Mod_Extradata(m); + hdr = static_cast(Mod_Extradata(m)); if (!hdr) { return; } diff --git a/src/keys.cpp b/src/keys.cpp index 6bd5bb0..04d8833 100644 --- a/src/keys.cpp +++ b/src/keys.cpp @@ -378,13 +378,13 @@ FIXME: handle quote special (general escape sequence?) const char* Key_KeynumToString(int keynum) { keyname_t* kn; - static char tinystr[2]; if (keynum == -1) { return ""; } if (keynum > 32 && keynum < 127) { // printable ascii + static char tinystr[2]; tinystr[0] = static_cast(keynum); tinystr[1] = 0; @@ -422,7 +422,7 @@ void Key_SetBinding(int keynum, const char* binding) // allocate memory for new binding l = Q_strlen(binding); - new_binding = (char*)Z_Malloc(l + 1); + new_binding = static_cast(Z_Malloc(l + 1)); Q_strcpy(new_binding, binding); new_binding[l] = 0; keybindings[keynum] = new_binding; @@ -687,14 +687,14 @@ void Key_Event(int key, qboolean down) if (!down) { kb = keybindings[key]; if (kb && kb[0] == '+') { - sprintf_s(cmd, sizeof(cmd), "-%s %i\n", kb + 1, key); + snprintf(cmd, sizeof(cmd), "-%s %i\n", kb + 1, key); Cmd::BufferAddText(cmd); } if (keyshift[key] != key) { kb = keybindings[keyshift[key]]; if (kb && kb[0] == '+') { - sprintf_s(cmd, sizeof(cmd), "-%s %i\n", kb + 1, key); + snprintf(cmd, sizeof(cmd), "-%s %i\n", kb + 1, key); Cmd::BufferAddText(cmd); } } @@ -705,7 +705,7 @@ void Key_Event(int key, qboolean down) // // during demo playback, most keys bring up the main menu // - if (cls.demoplayback && down && consolekeys[key] && key_dest == key_game) { + if (cls.demoplayback && consolekeys[key] && key_dest == key_game) { M_ToggleMenu_f(); return; @@ -718,7 +718,7 @@ void Key_Event(int key, qboolean down) kb = keybindings[key]; if (kb) { if (kb[0] == '+') { // button commands add keynum as a parm - sprintf_s(cmd, sizeof(cmd), "%s %i\n", kb, key); + snprintf(cmd, sizeof(cmd), "%s %i\n", kb, key); Cmd::BufferAddText(cmd); } else { Cmd::BufferAddText(kb); diff --git a/src/mathlib.cpp b/src/mathlib.cpp index f9787d4..8dc1060 100644 --- a/src/mathlib.cpp +++ b/src/mathlib.cpp @@ -63,7 +63,7 @@ void BOPS_Error(void) R_ConcatRotations ================ */ -void R_ConcatRotations(float in1[3][3], float in2[3][3], float out[3][3]) +void R_ConcatRotations(const float in1[3][3], const float in2[3][3], float out[3][3]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; @@ -81,7 +81,7 @@ void R_ConcatRotations(float in1[3][3], float in2[3][3], float out[3][3]) R_ConcatTransforms ================ */ -void R_ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]) +void R_ConcatTransforms(const float in1[3][4], const float in2[3][4], float out[3][4]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; diff --git a/src/mathlib.hpp b/src/mathlib.hpp index b016ffc..dbfdcc2 100644 --- a/src/mathlib.hpp +++ b/src/mathlib.hpp @@ -13,10 +13,10 @@ struct Vector3 { // Array subscript operators constexpr float operator[](size_t index) const { - return (&x)[index]; + return (index == 0) ? x : ((index == 1) ? y : z); } constexpr float& operator[](size_t index) { - return (&x)[index]; + return (index == 0) ? x : ((index == 1) ? y : z); } // Implicit conversions to raw pointers @@ -105,7 +105,7 @@ typedef int fixed16_t; struct mplane_s; -#define IS_NAN(x) (((*(int*)&x) & nanmask) == nanmask) +#define IS_NAN(x) std::isnan(x) // Modern C++ template functions replacing legacy macros template @@ -185,8 +185,8 @@ inline void VectorScale(const T& in, vec_t scale, U&& out) { out[2] = in[2] * scale; } -void R_ConcatRotations(float in1[3][3], float in2[3][3], float out[3][3]); -void R_ConcatTransforms(float in1[3][4], float in2[3][4], float out[3][4]); +void R_ConcatRotations(const float in1[3][3], const float in2[3][3], float out[3][3]); +void R_ConcatTransforms(const float in1[3][4], const float in2[3][4], float out[3][4]); void FloorDivMod(double numer, double denom, int* quotient, int* rem); int GreatestCommonDivisor(int i1, int i2); diff --git a/src/menu.cpp b/src/menu.cpp index 4f553b7..d748f7f 100644 --- a/src/menu.cpp +++ b/src/menu.cpp @@ -166,7 +166,7 @@ inline void M_DrawTransPic(int x, int y, qpic_t* pic) Draw_TransPic(x + ((vid.width - 320) >> 1), y, pic); } -void M_DrawPic(int x, int y, qpic_t* pic) +void M_DrawPic(int x, int y, const qpic_t* pic) { Draw_Pic(x + ((vid.width - 320) >> 1), y, pic); } @@ -486,17 +486,17 @@ void M_ScanSaves(void) int version; for (i = 0; i < MAX_SAVEGAMES; i++) { - strcpy_s(m_filenames[i], sizeof(m_filenames[i]), "--- UNUSED SLOT ---"); + strlcpy(m_filenames[i], "--- UNUSED SLOT ---", sizeof(m_filenames[i])); loadable[i] = false; - sprintf_s(name, sizeof(name), "%s/s%i.sav", com_gamedir, i); - fopen_s(&f, name, "r"); + snprintf(name, sizeof(name), "%s/s%i.sav", com_gamedir, i); + f = fopen(name, "r"); if (!f) { continue; } - fscanf_s(f, "%i\n", &version); - fscanf_s(f, "%79s\n", name, (unsigned)sizeof(name)); - strncpy_s(m_filenames[i], sizeof(m_filenames[i]), name, sizeof(m_filenames[i]) - 1); + fscanf(f, "%i\n", &version); + fscanf(f, "%79s\n", name); + strlcpy(m_filenames[i], name, sizeof(m_filenames[i]) - 1); // change _ back to space for (j = 0; j < SAVEGAME_COMMENT_LENGTH; j++) { @@ -1510,7 +1510,7 @@ void M_Keys_Key(int k) if (k == K_ESCAPE) { bind_grab = false; } else if (k != '`') { - sprintf_s(cmd, sizeof(cmd), "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), + snprintf(cmd, sizeof(cmd), "bind \"%s\" \"%s\"\n", Key_KeynumToString(k), bindnames[keys_cursor][0]); Cmd::BufferInsertText(cmd); } @@ -2177,7 +2177,7 @@ void M_Menu_LanConfig_f(void) } lanConfig_port = DEFAULTnet_hostport; - sprintf_s(lanConfig_portname, sizeof(lanConfig_portname), "%u", lanConfig_port); + snprintf(lanConfig_portname, sizeof(lanConfig_portname), "%u", lanConfig_port); m_return_onerror = false; m_return_reason[0] = 0; @@ -2360,7 +2360,7 @@ void M_LanConfig_Key(int key) lanConfig_port = l; } - sprintf_s(lanConfig_portname, sizeof(lanConfig_portname), "%u", lanConfig_port); + snprintf(lanConfig_portname, sizeof(lanConfig_portname), "%u", lanConfig_port); } //============================================================================= @@ -2965,10 +2965,10 @@ void M_ServerList_Draw(void) M_DrawPic((320 - p->width) / 2, 4, p); for (n = 0; n < hostCacheCount; n++) { if (hostcache[n].maxusers) { - sprintf_s(string, sizeof(string), "%-15.15s %-15.15s %2u/%2u\n", hostcache[n].name, + snprintf(string, sizeof(string), "%-15.15s %-15.15s %2u/%2u\n", hostcache[n].name, hostcache[n].map, hostcache[n].users, hostcache[n].maxusers); } else { - sprintf_s(string, sizeof(string), "%-15.15s %-15.15s\n", hostcache[n].name, + snprintf(string, sizeof(string), "%-15.15s %-15.15s\n", hostcache[n].name, hostcache[n].map); } diff --git a/src/menu.hpp b/src/menu.hpp index 913445a..3a4fac4 100644 --- a/src/menu.hpp +++ b/src/menu.hpp @@ -14,7 +14,7 @@ void M_ToggleMenu_f(void); void M_Menu_Main_f(void); void M_Menu_Quit_f(void); -void M_DrawPic(int x, int y, qpic_t* pic); +void M_DrawPic(int x, int y, const qpic_t* pic); extern int m_state; extern int m_return_state; diff --git a/src/model.cpp b/src/model.cpp index ed0290a..8d97b1d 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -237,7 +237,7 @@ model_t* Mod_FindName(const char* name) mod_numknown++; } - strcpy_s(mod->name, sizeof(mod->name), name); + strlcpy(mod->name, name, sizeof(mod->name)); mod->needload = NL_NEEDS_LOADED; } @@ -1247,10 +1247,10 @@ void Mod_LoadBrushModel(model_t* mod, void* buffer) if (i < mod->numsubmodels - 1) { // duplicate the basic information char name[10]; - sprintf_s(name, sizeof(name), "*%i", i + 1); + snprintf(name, sizeof(name), "*%i", i + 1); loadmodel = Mod_FindName(name); *loadmodel = *mod; - strcpy_s(loadmodel->name, sizeof(loadmodel->name), name); + strlcpy(loadmodel->name, name, sizeof(loadmodel->name)); mod = loadmodel; } } @@ -1283,7 +1283,7 @@ void* Mod_LoadAliasFrame(void* pin, pdaliasframe = (daliasframe_t*)pin; - strcpy_s(name, 16, pdaliasframe->name); + strlcpy(name, pdaliasframe->name, 16); for (i = 0; i < 3; i++) { // these are byte values, so we don't have to worry about diff --git a/src/model.hpp b/src/model.hpp index 85547d3..3b196ee 100644 --- a/src/model.hpp +++ b/src/model.hpp @@ -38,10 +38,10 @@ typedef struct { // !!! if this is changed, it must be changed in asm_i386.h too !!! typedef struct mplane_s { Vector3 normal; - float dist; - byte type; // for texture axis selection and fast side tests - byte signbits; // signx + signy<<1 + signz<<1 - byte pad[2]; + float dist = 0.0f; + byte type = 0; // for texture axis selection and fast side tests + byte signbits = 0; // signx + signy<<1 + signz<<1 + byte pad[2] = {}; } mplane_t; typedef struct texture_s { @@ -75,28 +75,28 @@ typedef struct { } mtexinfo_t; typedef struct msurface_s { - int visframe; // should be drawn when node is crossed + int visframe = 0; // should be drawn when node is crossed - int dlightframe; - int dlightbits; + int dlightframe = 0; + int dlightbits = 0; - mplane_t* plane; - int flags; + mplane_t* plane = nullptr; + int flags = 0; - int firstedge; // look up in model->surfedges[], negative numbers - int numedges; // are backwards edges + int firstedge = 0; // look up in model->surfedges[], negative numbers + int numedges = 0; // are backwards edges // surface generation data - struct surfcache_s* cachespots[MIPLEVELS]; + struct surfcache_s* cachespots[MIPLEVELS] = {}; - short texturemins[2]; - short extents[2]; + short texturemins[2] = {}; + short extents[2] = {}; - mtexinfo_t* texinfo; + mtexinfo_t* texinfo = nullptr; // lighting info - byte styles[MAXLIGHTMAPS]; - byte* samples; // [numstyles*surfsize] + byte styles[MAXLIGHTMAPS] = {}; + byte* samples = nullptr; // [numstyles*surfsize] } msurface_t; typedef struct mnode_s { @@ -118,29 +118,29 @@ typedef struct mnode_s { typedef struct mleaf_s { // common with node - int contents; // wil be a negative contents number - int visframe; // node needs to be traversed if current + int contents = 0; // wil be a negative contents number + int visframe = 0; // node needs to be traversed if current - short minmaxs[6]; // for bounding box culling + short minmaxs[6] = {}; // for bounding box culling - struct mnode_s* parent; + struct mnode_s* parent = nullptr; // leaf specific - byte* compressed_vis; - efrag_t* efrags; + byte* compressed_vis = nullptr; + efrag_t* efrags = nullptr; - msurface_t** firstmarksurface; - int nummarksurfaces; - int key; // BSP sequence number for leaf's contents - byte ambient_sound_level[NUM_AMBIENTS]; + msurface_t** firstmarksurface = nullptr; + int nummarksurfaces = 0; + int key = 0; // BSP sequence number for leaf's contents + byte ambient_sound_level[NUM_AMBIENTS] = {}; } mleaf_t; // !!! if this is changed, it must be changed in asm_i386.h too !!! -typedef struct { - dclipnode_t* clipnodes; - mplane_t* planes; - int firstclipnode; - int lastclipnode; +typedef struct hull_s { + dclipnode_t* clipnodes = nullptr; + mplane_t* planes = nullptr; + int firstclipnode = 0; + int lastclipnode = 0; Vector3 clip_mins; Vector3 clip_maxs; } hull_t; @@ -155,17 +155,17 @@ SPRITE MODELS // FIXME: shorten these? typedef struct mspriteframe_s { - int width; - int height; - void* pcachespot; // remove? - float up, down, left, right; - byte pixels[4]; + int width = 0; + int height = 0; + void* pcachespot = nullptr; // remove? + float up = 0.0f, down = 0.0f, left = 0.0f, right = 0.0f; + byte pixels[4] = {}; } mspriteframe_t; -typedef struct { - int numframes; - float* intervals; - mspriteframe_t* frames[1]; +typedef struct mspritegroup_s { + int numframes = 0; + float* intervals = nullptr; + mspriteframe_t* frames[1] = {}; } mspritegroup_t; typedef struct { @@ -192,12 +192,12 @@ Alias models are position independent, so the cache manager can move them. ============================================================================== */ -typedef struct { - aliasframetype_t type; - trivertx_t bboxmin; - trivertx_t bboxmax; - int frame; - char name[16]; +typedef struct maliasframedesc_s { + aliasframetype_t type = {}; + trivertx_t bboxmin = {}; + trivertx_t bboxmax = {}; + int frame = 0; + char name[16] = {}; } maliasframedesc_t; typedef struct { @@ -206,16 +206,16 @@ typedef struct { int skin; } maliasskindesc_t; -typedef struct { - trivertx_t bboxmin; - trivertx_t bboxmax; - int frame; +typedef struct maliasgroupframedesc_s { + trivertx_t bboxmin = {}; + trivertx_t bboxmax = {}; + int frame = 0; } maliasgroupframedesc_t; -typedef struct { - int numframes; - int intervals; - maliasgroupframedesc_t frames[1]; +typedef struct maliasgroup_s { + int numframes = 0; + int intervals = 0; + maliasgroupframedesc_t frames[1] = {}; } maliasgroup_t; typedef struct { @@ -230,12 +230,12 @@ typedef struct mtriangle_s { int vertindex[3]; } mtriangle_t; -typedef struct { - int model; - int stverts; - int skindesc; - int triangles; - maliasframedesc_t frames[1]; +typedef struct aliashdr_s { + int model = 0; + int stverts = 0; + int skindesc = 0; + int triangles = 0; + maliasframedesc_t frames[1] = {}; } aliashdr_t; //=================================================================== @@ -258,72 +258,72 @@ typedef enum { mod_brush, #define EF_TRACER3 128 // purple trail typedef struct model_s { - char name[MAX_QPATH]; - int needload; // bmodels and sprites don't cache normally + char name[MAX_QPATH] = {}; + int needload = 0; // bmodels and sprites don't cache normally - modtype_t type; - int numframes; - synctype_t synctype; + modtype_t type = {}; + int numframes = 0; + synctype_t synctype = {}; - int flags; + int flags = 0; // // volume occupied by the model // Vector3 mins, maxs; - float radius; + float radius = 0.0f; // // brush model // - int firstmodelsurface, nummodelsurfaces; + int firstmodelsurface = 0, nummodelsurfaces = 0; - int numsubmodels; - dmodel_t* submodels; + int numsubmodels = 0; + dmodel_t* submodels = nullptr; - int numplanes; - mplane_t* planes; + int numplanes = 0; + mplane_t* planes = nullptr; - int numleafs; // number of visible leafs, not counting 0 - mleaf_t* leafs; + int numleafs = 0; // number of visible leafs, not counting 0 + mleaf_t* leafs = nullptr; - int numvertexes; - mvertex_t* vertexes; + int numvertexes = 0; + mvertex_t* vertexes = nullptr; - int numedges; - medge_t* edges; + int numedges = 0; + medge_t* edges = nullptr; - int numnodes; - mnode_t* nodes; + int numnodes = 0; + mnode_t* nodes = nullptr; - int numtexinfo; - mtexinfo_t* texinfo; + int numtexinfo = 0; + mtexinfo_t* texinfo = nullptr; - int numsurfaces; - msurface_t* surfaces; + int numsurfaces = 0; + msurface_t* surfaces = nullptr; - int numsurfedges; - int* surfedges; + int numsurfedges = 0; + int* surfedges = nullptr; - int numclipnodes; - dclipnode_t* clipnodes; + int numclipnodes = 0; + dclipnode_t* clipnodes = nullptr; - int nummarksurfaces; - msurface_t** marksurfaces; + int nummarksurfaces = 0; + msurface_t** marksurfaces = nullptr; - hull_t hulls[MAX_MAP_HULLS]; + hull_t hulls[MAX_MAP_HULLS] = {}; - int numtextures; - texture_t** textures; + int numtextures = 0; + texture_t** textures = nullptr; - byte* visdata; - byte* lightdata; - char* entities; + byte* visdata = nullptr; + byte* lightdata = nullptr; + char* entities = nullptr; // // additional model data // - cache_user_t cache; // only access through Mod_Extradata + cache_user_t cache = {}; // only access through Mod_Extradata } model_t; diff --git a/src/network.cpp b/src/network.cpp index 90bc1b2..7e92dd1 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -27,8 +27,8 @@ using namespace Wad; using namespace Cvar; using namespace Cmd; - -#include +#include +#include #ifdef _WIN32 #include @@ -45,10 +45,18 @@ using namespace Cmd; #undef errno #define errno WSAGetLastError() typedef int socklen_t; +#else +#include +#include +#include +#include +#include +#include +#endif + #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 256 #endif -#endif // VCR op constants #define VCR_OP_CONNECT 1 @@ -572,7 +580,7 @@ static int PartialIPAddress(const char* in, struct qsockaddr* hostaddr) buff[0] = '.'; b = buff; - strcpy_s(buff + 1, sizeof(buff) - 1, in); + strlcpy(buff + 1, in, sizeof(buff) - 1); if (buff[1] == '.') { b++; } @@ -646,7 +654,7 @@ int UDP_CheckNewConnections(void) int UDP_Read(int socket, byte* buf, int len, struct qsockaddr* addr) { - int addrlen = sizeof(struct qsockaddr); + socklen_t addrlen = sizeof(struct qsockaddr); int ret; ret = recvfrom(socket, (char*)buf, len, 0, (struct sockaddr*)addr, &addrlen); @@ -718,7 +726,7 @@ char* UDP_AddrToString(struct qsockaddr* addr) int haddr; haddr = ntohl(((struct sockaddr_in*)addr)->sin_addr.s_addr); - sprintf_s(buffer, sizeof(buffer), "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, + snprintf(buffer, sizeof(buffer), "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, ntohs(((struct sockaddr_in*)addr)->sin_port)); @@ -732,7 +740,7 @@ int UDP_StringToAddr(const char* string, struct qsockaddr* addr) int ha1, ha2, ha3, ha4, hp; int ipaddr; - sscanf_s(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp); + sscanf(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp); ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4; addr->sa_family = AF_INET; @@ -746,7 +754,7 @@ int UDP_StringToAddr(const char* string, struct qsockaddr* addr) int UDP_GetSocketAddr(int socket, struct qsockaddr* addr) { - int addrlen = sizeof(struct qsockaddr); + socklen_t addrlen = sizeof(struct qsockaddr); unsigned int a; Q_memset(addr, 0, sizeof(struct qsockaddr)); @@ -887,7 +895,7 @@ char* StrAddr(struct qsockaddr* addr) int n; for (n = 0; n < 16; n++) { - sprintf_s(buf + n * 2, sizeof(buf) - n * 2, "%02x", *p++); + snprintf(buf + n * 2, sizeof(buf) - n * 2, "%02x", *p++); } return buf; diff --git a/src/quakedef.hpp b/src/quakedef.hpp index 8721a6b..e99b313 100644 --- a/src/quakedef.hpp +++ b/src/quakedef.hpp @@ -13,11 +13,12 @@ #define GAMENAME "id1" -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include #include #include #include "core_types.hpp" @@ -168,14 +169,14 @@ inline void VID_UnlockBuffer(void) {} #include "zone.hpp" #include "mathlib.hpp" -typedef struct { +typedef struct entity_state_s { Vector3 origin; Vector3 angles; - int modelindex; - int frame; - int colormap; - int skin; - int effects; + int modelindex = 0; + int frame = 0; + int colormap = 0; + int skin = 0; + int effects = 0; } entity_state_t; #include "wad.hpp" diff --git a/src/renderer.cpp b/src/renderer.cpp index f547907..239a0b3 100644 --- a/src/renderer.cpp +++ b/src/renderer.cpp @@ -732,7 +732,7 @@ void R_ReadPointFile_f(void) particle_t* p; char name[MAX_OSPATH]; - sprintf_s(name, sizeof(name), "maps/%s.pts", sv.name); + snprintf(name, sizeof(name), "maps/%s.pts", sv.name); COM_FOpenFile(name, &f); if (!f) { @@ -744,7 +744,7 @@ void R_ReadPointFile_f(void) Con_Printf("Reading %s...\n", name); c = 0; for (;;) { - r = fscanf_s(f, "%f %f %f\n", &org[0], &org[1], &org[2]); + r = fscanf(f, "%f %f %f\n", &org[0], &org[1], &org[2]); if (r != 3) { break; } diff --git a/src/renderer.hpp b/src/renderer.hpp index 675368e..edaba37 100644 --- a/src/renderer.hpp +++ b/src/renderer.hpp @@ -16,65 +16,65 @@ typedef struct efrag_s { } efrag_t; typedef struct entity_s { - qboolean forcelink; // model changed + qboolean forcelink = false; // model changed - int update_type; + int update_type = 0; - entity_state_t baseline; // to fill in defaults in updates + entity_state_t baseline = {}; // to fill in defaults in updates - double msgtime; // time of last update + double msgtime = 0.0; // time of last update Vector3 msg_origins[2]; // last two updates (0 is newest) Vector3 origin; Vector3 msg_angles[2]; // last two updates (0 is newest) Vector3 angles; - struct model_s* model; // NULL = no model - struct efrag_s* efrag; // linked list of efrags - int frame; - float syncbase; // for client-side animations - byte* colormap; - int effects; // light, particals, etc - int skinnum; // for Alias models - int visframe; // last frame this entity was + struct model_s* model = nullptr; // NULL = no model + struct efrag_s* efrag = nullptr; // linked list of efrags + int frame = 0; + float syncbase = 0.0f; // for client-side animations + byte* colormap = nullptr; + int effects = 0; // light, particals, etc + int skinnum = 0; // for Alias models + int visframe = 0; // last frame this entity was // found in an active leaf - int dlightframe; // dynamic lighting - int dlightbits; + int dlightframe = 0; // dynamic lighting + int dlightbits = 0; // FIXME: could turn these into a union - int trivial_accept; - struct mnode_s* topnode; // for bmodels, first world node + int trivial_accept = 0; + struct mnode_s* topnode = nullptr; // for bmodels, first world node // that splits bmodel, or NULL if // not split } entity_t; // !!! if this is changed, it must be changed in asm_draw.h too !!! -typedef struct { - vrect_t vrect; // subwindow in video for refresh +typedef struct refdef_s { + vrect_t vrect = {}; // subwindow in video for refresh // FIXME: not need vrect next field here? - vrect_t aliasvrect; // scaled Alias version - int vrectright, vrectbottom; // right & bottom screen coords - int aliasvrectright, aliasvrectbottom; // scaled Alias versions - float vrectrightedge; // rightmost right edge we care about, + vrect_t aliasvrect = {}; // scaled Alias version + int vrectright = 0, vrectbottom = 0; // right & bottom screen coords + int aliasvrectright = 0, aliasvrectbottom = 0; // scaled Alias versions + float vrectrightedge = 0.0f; // rightmost right edge we care about, // for use in edge list - float fvrectx, fvrecty; // for floating-point compares - float fvrectx_adj, fvrecty_adj; // left and top edges, for clamping - int64_t vrect_x_adj_shift20; // (vrect.x + 0.5 - epsilon) << 20 - int64_t vrectright_adj_shift20; // (vrectright + 0.5 - epsilon) << 20 - float fvrectright_adj, fvrectbottom_adj; + float fvrectx = 0.0f, fvrecty = 0.0f; // for floating-point compares + float fvrectx_adj = 0.0f, fvrecty_adj = 0.0f; // left and top edges, for clamping + int64_t vrect_x_adj_shift20 = 0; // (vrect.x + 0.5 - epsilon) << 20 + int64_t vrectright_adj_shift20 = 0; // (vrectright + 0.5 - epsilon) << 20 + float fvrectright_adj = 0.0f, fvrectbottom_adj = 0.0f; // right and bottom edges, for clamping - float fvrectright; // rightmost edge, for Alias clamping - float fvrectbottom; // bottommost edge, for Alias clamping - float horizontalFieldOfView; // at Z = 1.0, this many X is visible + float fvrectright = 0.0f; // rightmost edge, for Alias clamping + float fvrectbottom = 0.0f; // bottommost edge, for Alias clamping + float horizontalFieldOfView = 0.0f; // at Z = 1.0, this many X is visible // 2.0 = 90 degrees - float xOrigin; // should probably allways be 0.5 - float yOrigin; // between be around 0.3 to 0.5 + float xOrigin = 0.0f; // should probably allways be 0.5 + float yOrigin = 0.0f; // between be around 0.3 to 0.5 Vector3 vieworg; Vector3 viewangles; - float fov_x, fov_y; + float fov_x = 0.0f, fov_y = 0.0f; - int ambientlight; + int ambientlight = 0; } refdef_t; struct texture_s; @@ -124,6 +124,6 @@ int D_SurfaceCacheForRes(int width, int height); void D_FlushCaches(void); void D_DeleteSurfaceCache(void); void D_InitCaches(void* buffer, int size); -void R_SetVrect(vrect_t* pvrect, vrect_t* pvrectin, int lineadj); +void R_SetVrect(vrect_t* pvrectin, vrect_t* pvrect, int lineadj); } // namespace Render diff --git a/src/sbar.cpp b/src/sbar.cpp index abdd764..6cf83e2 100644 --- a/src/sbar.cpp +++ b/src/sbar.cpp @@ -260,7 +260,7 @@ void Sbar_Init(void) Sbar_DrawPic ============= */ -void Sbar_DrawPic(int x, int y, qpic_t* pic) +void Sbar_DrawPic(int x, int y, const qpic_t* pic) { if (cl.gametype == GAME_DEATHMATCH) { Draw_Pic(x /* + ((vid.width - 320)>>1)*/, y + (vid.height - SBAR_HEIGHT), @@ -275,7 +275,7 @@ void Sbar_DrawPic(int x, int y, qpic_t* pic) Sbar_DrawTransPic ============= */ -void Sbar_DrawTransPic(int x, int y, qpic_t* pic) +void Sbar_DrawTransPic(int x, int y, const qpic_t* pic) { if (cl.gametype == GAME_DEATHMATCH) { Draw_TransPic(x /*+ ((vid.width - 320)>>1)*/, @@ -309,7 +309,7 @@ void Sbar_DrawCharacter(int x, int y, int num) Sbar_DrawString ================ */ -void Sbar_DrawString(int x, int y, char* str) +void Sbar_DrawString(int x, int y, const char* str) { if (cl.gametype == GAME_DEATHMATCH) { Draw_String(x /*+ ((vid.width - 320)>>1)*/, y + vid.height - SBAR_HEIGHT, @@ -329,7 +329,6 @@ int Sbar_itoa(int num, char* buf) { char* str; int pow10; - int dig; str = buf; @@ -344,7 +343,7 @@ int Sbar_itoa(int num, char* buf) do { pow10 /= 10; - dig = num / pow10; + int dig = num / pow10; *str++ = static_cast('0' + dig); num -= dig * pow10; } while (pow10 != 1); @@ -405,7 +404,7 @@ Sbar_SortFrags */ void Sbar_SortFrags(void) { - int i, j, k; + int i, j; // sort by frags scoreboardlines = 0; @@ -419,7 +418,7 @@ void Sbar_SortFrags(void) for (i = 0; i < scoreboardlines; i++) { for (j = 0; j < scoreboardlines - 1 - i; j++) { if (cl.scores[fragsort[j]].frags < cl.scores[fragsort[j + 1]].frags) { - k = fragsort[j]; + int k = fragsort[j]; fragsort[j] = fragsort[j + 1]; fragsort[j + 1] = k; } @@ -429,7 +428,7 @@ void Sbar_SortFrags(void) int Sbar_ColorForMap(int m) { - return m < 128 ? m + 8 : m + 8; + return m + 8; } /* @@ -443,11 +442,11 @@ void Sbar_SoloScoreboard(void) int minutes, seconds, tens, units; int l; - sprintf_s(str, sizeof(str), "Monsters:%3i /%3i", cl.stats[STAT_MONSTERS], + snprintf(str, sizeof(str), "Monsters:%3i /%3i", cl.stats[STAT_MONSTERS], cl.stats[STAT_TOTALMONSTERS]); Sbar_DrawString(8, 4, str); - sprintf_s(str, sizeof(str), "Secrets :%3i /%3i", cl.stats[STAT_SECRETS], + snprintf(str, sizeof(str), "Secrets :%3i /%3i", cl.stats[STAT_SECRETS], cl.stats[STAT_TOTALSECRETS]); Sbar_DrawString(8, 12, str); @@ -456,7 +455,7 @@ void Sbar_SoloScoreboard(void) seconds = static_cast(cl.time - 60 * minutes); tens = seconds / 10; units = seconds - 10 * tens; - sprintf_s(str, sizeof(str), "Time :%3i:%i%i", minutes, tens, units); + snprintf(str, sizeof(str), "Time :%3i:%i%i", minutes, tens, units); Sbar_DrawString(184, 4, str); // draw level name @@ -584,7 +583,7 @@ flashon = static_cast((cl.time - time) * 10); // ammo counts for (i = 0; i < 4; i++) { - sprintf_s(num, sizeof(num), "%3i", cl.stats[STAT_SHELLS + i]); + snprintf(num, sizeof(num), "%3i", cl.stats[STAT_SHELLS + i]); if (num[0] != ' ') { Sbar_DrawCharacter((6 * i + 1) * 8 - 2, -24, 18 + num[0] - '0'); } @@ -598,7 +597,7 @@ flashon = static_cast((cl.time - time) * 10); } } - flashon = 0; + flashon = (cl.time < 0.0f) ? 1 : 0; // items for (i = 0; i < 6; i++) { if (cl.items & (1 << (17 + i))) { @@ -656,7 +655,7 @@ flashon = static_cast((cl.time - time) * 10); } else { // sigils for (i = 0; i < 4; i++) { - if (cl.items & (1 << (28 + i))) { + if (cl.items & (1U << (28 + i))) { time = cl.item_gettime[28 + i]; if (time && time > cl.time - 2 && flashon) { // flash frame sb_updates = 0; @@ -681,12 +680,11 @@ Sbar_DrawFrags */ void Sbar_DrawFrags(void) { - int i, k, l; + int i, l; int top, bottom; int x, y, f; int xofs; char num[12]; - scoreboard_t* s; Sbar_SortFrags(); @@ -703,8 +701,8 @@ void Sbar_DrawFrags(void) y = vid.height - SBAR_HEIGHT - 23; for (i = 0; i < l; i++) { - k = fragsort[i]; - s = &cl.scores[k]; + int k = fragsort[i]; + const scoreboard_t* s = &cl.scores[k]; if (!s->name[0]) { continue; } @@ -720,7 +718,7 @@ void Sbar_DrawFrags(void) // draw number f = s->frags; - sprintf_s(num, sizeof(num), "%3i", f); + snprintf(num, sizeof(num), "%3i", f); Sbar_DrawCharacter((x + 1) * 8, -24, num[0]); Sbar_DrawCharacter((x + 2) * 8, -24, num[1]); @@ -773,7 +771,7 @@ void Sbar_DrawFace(void) // draw number f = s->frags; - sprintf_s(num, sizeof(num), "%3i", f); + snprintf(num, sizeof(num), "%3i", f); if (top == 8) { if (num[0] != ' ') { @@ -1005,12 +1003,11 @@ Sbar_DeathmatchOverlay */ void Sbar_DeathmatchOverlay(void) { - qpic_t* pic; - int i, k, l; + const qpic_t* pic; + int i, l; int top, bottom; int x, y, f; char num[12]; - scoreboard_t* s; scr_copyeverything = 1; scr_fullupdate = 0; @@ -1027,8 +1024,8 @@ void Sbar_DeathmatchOverlay(void) x = 80 + ((vid.width - 320) >> 1); y = 40; for (i = 0; i < l; i++) { - k = fragsort[i]; - s = &cl.scores[k]; + int k = fragsort[i]; + const scoreboard_t* s = &cl.scores[k]; if (!s->name[0]) { continue; } @@ -1044,7 +1041,7 @@ void Sbar_DeathmatchOverlay(void) // draw number f = s->frags; - sprintf_s(num, sizeof(num), "%3i", f); + snprintf(num, sizeof(num), "%3i", f); Draw_Character(x + 8, y, num[0]); Draw_Character(x + 16, y, num[1]); @@ -1069,11 +1066,10 @@ Sbar_DeathmatchOverlay */ void Sbar_MiniDeathmatchOverlay(void) { - int i, k; + int i; int top, bottom; int x, y, f; char num[12]; - scoreboard_t* s; int numlines; if (vid.width < 512 || !sb_lines) { @@ -1116,8 +1112,8 @@ void Sbar_MiniDeathmatchOverlay(void) x = 324; for (/* */; i < scoreboardlines && y < static_cast(vid.height) - 8; i++) { - k = fragsort[i]; - s = &cl.scores[k]; + int k = fragsort[i]; + const scoreboard_t* s = &cl.scores[k]; if (!s->name[0]) { continue; } @@ -1133,7 +1129,7 @@ void Sbar_MiniDeathmatchOverlay(void) // draw number f = s->frags; - sprintf_s(num, sizeof(num), "%3i", f); + snprintf(num, sizeof(num), "%3i", f); Draw_Character(x + 8, y, num[0]); Draw_Character(x + 16, y, num[1]); @@ -1159,7 +1155,7 @@ Sbar_IntermissionOverlay */ void Sbar_IntermissionOverlay(void) { - qpic_t* pic; + const qpic_t* pic; int dig; int num; @@ -1203,7 +1199,7 @@ Sbar_FinaleOverlay */ void Sbar_FinaleOverlay(void) { - qpic_t* pic; + const qpic_t* pic; scr_copyeverything = 1; diff --git a/src/screen.cpp b/src/screen.cpp index 14a203c..32712c4 100644 --- a/src/screen.cpp +++ b/src/screen.cpp @@ -95,7 +95,7 @@ for a few moments */ void SCR_CenterPrint(const char* str) { - strncpy_s(scr_centerstring, sizeof(scr_centerstring), str, sizeof(scr_centerstring) - 1); + strlcpy(scr_centerstring, str, sizeof(scr_centerstring) - 1); scr_centertime_off = scr_centertime.value; scr_centertime_start = static_cast(cl.time); @@ -132,10 +132,10 @@ void SCR_EraseCenterString(void) void SCR_DrawCenterString(void) { - char* start; + const char* start; int l; int j; - int x, y; + int y; int remaining; // the finale prints the characters one at a time @@ -161,7 +161,7 @@ void SCR_DrawCenterString(void) break; } } - x = (vid.width - l * 8) / 2; + int x = (vid.width - l * 8) / 2; for (j = 0; j < l; j++, x += 8) { Draw_Character(x, y, start[j]); if (!remaining--) { @@ -432,7 +432,7 @@ DrawPause */ void SCR_DrawPause(void) { - qpic_t* pic; + const qpic_t* pic; if (!scr_showpause.value) { // turn off for screenshots return; @@ -454,7 +454,7 @@ SCR_DrawLoading */ void SCR_DrawLoading(void) { - qpic_t* pic; + const qpic_t* pic; if (!scr_drawloading) { return; @@ -565,18 +565,18 @@ typedef struct { WritePCXfile ============== */ -void WritePCXfile(char* filename, +void WritePCXfile(const char* filename, byte* data, int width, int height, int rowbytes, - byte* palette) + const byte* palette) { int i, j, length; pcx_t* pcx; byte* pack; - pcx = (pcx_t *) Hunk_TempAlloc(width * height * 2 + 1000); + pcx = static_cast(Hunk_TempAlloc(width * height * 2 + 1000)); if (pcx == NULL) { Con_Printf("SCR_ScreenShot_f: not enough memory\n"); @@ -622,7 +622,7 @@ void WritePCXfile(char* filename, } // write output file - length = static_cast(pack - (byte*)pcx); + length = static_cast(pack - reinterpret_cast(pcx)); COM_WriteFile(filename, pcx, length); } @@ -640,12 +640,12 @@ void SCR_ScreenShot_f(void) // // find a file name to save it to // - strcpy_s(pcxname, sizeof(pcxname), "quake00.pcx"); + strlcpy(pcxname, "quake00.pcx", sizeof(pcxname)); for (i = 0; i <= 99; i++) { pcxname[5] = static_cast(i / 10 + '0'); pcxname[6] = static_cast(i % 10 + '0'); - sprintf_s(checkname, sizeof(checkname), "%s/%s", com_gamedir, pcxname); + snprintf(checkname, sizeof(checkname), "%s/%s", com_gamedir, pcxname); if (Sys_FileTime(checkname) == -1) { break; // file doesn't exist } @@ -730,7 +730,7 @@ void SCR_DrawNotifyString(void) const char* start; int l; int j; - int x, y; + int y; start = scr_notifystring; @@ -743,7 +743,7 @@ void SCR_DrawNotifyString(void) break; } } - x = (vid.width - l * 8) / 2; + int x = (vid.width - l * 8) / 2; for (j = 0; j < l; j++, x += 8) { Draw_Character(x, y, start[j]); } diff --git a/src/server.cpp b/src/server.cpp index 9aad8da..547848a 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -104,7 +104,7 @@ void SV_Init(void) Cvar::Register(&sv_nostep); for (i = 0; i < MAX_MODELS; i++) { - sprintf_s(localmodels[i], sizeof(localmodels[i]), "*%i", i); + snprintf(localmodels[i], sizeof(localmodels[i]), "*%i", i); } } @@ -117,7 +117,7 @@ Make sure the event gets sent to all clients */ void SV_StartParticle(const Vector3& org, const Vector3& dir, int color, int count) { - int i, v; + int i; if (sv.datagram.cursize > MAX_DATAGRAM - 16) { return; @@ -128,7 +128,7 @@ void SV_StartParticle(const Vector3& org, const Vector3& dir, int color, int cou MSG_WriteCoord(&sv.datagram, org[1]); MSG_WriteCoord(&sv.datagram, org[2]); for (i = 0; i < 3; i++) { - v = static_cast(dir[i] * 16); + int v = static_cast(dir[i] * 16); if (v > 127) { v = 127; } else if (v < -128) { @@ -244,7 +244,7 @@ void SV_SendServerinfo(client_t* client) char message[2048]; MSG_WriteByte(&client->message, svc_print); - sprintf_s(message, sizeof(message), "%c\nVERSION %4.2f SERVER (%i CRC)", 2, VERSION, pr_crc); + snprintf(message, sizeof(message), "%c\nVERSION %4.2f SERVER (%i CRC)", 2, VERSION, pr_crc); MSG_WriteString(&client->message, message); MSG_WriteByte(&client->message, svc_serverinfo); @@ -257,7 +257,7 @@ void SV_SendServerinfo(client_t* client) MSG_WriteByte(&client->message, GAME_COOP); } - sprintf_s(message, sizeof(message), "%s", PR_GetString(sv.edicts->v.message)); + snprintf(message, sizeof(message), "%s", PR_GetString(sv.edicts->v.message)); MSG_WriteString(&client->message, message); @@ -301,7 +301,6 @@ void SV_ConnectClient(int clientnum) client_t* client; int edictnum; struct qsocket_s* netconnection; - int i; float spawn_parms[NUM_SPAWN_PARMS]; client = svs.clients + clientnum; @@ -319,10 +318,10 @@ void SV_ConnectClient(int clientnum) memcpy(spawn_parms, client->spawn_parms, sizeof(spawn_parms)); } - memset(client, 0, sizeof(*client)); + *client = client_t{}; client->netconnection = netconnection; - strcpy_s(client->name, sizeof(client->name), "unconnected"); + strlcpy(client->name, "unconnected", sizeof(client->name)); client->active = true; client->spawned = false; client->edict = ent; @@ -337,7 +336,7 @@ void SV_ConnectClient(int clientnum) } else { // call the progs to get default spawn parms for the new client PR_ExecuteProgram(pr_global_struct->SetNewParms); - for (i = 0; i < NUM_SPAWN_PARMS; i++) { + for (int i = 0; i < NUM_SPAWN_PARMS; i++) { client->spawn_parms[i] = (&pr_global_struct->parm1)[i]; } } @@ -390,17 +389,12 @@ void SV_CheckForNewClients(void) void SV_AddToFatPVS(const Vector3& org, mnode_t* node) { - int i; - byte* pvs; - mplane_t* plane; - float d; - while (1) { // if this is a leaf, accumulate the pvs bits if (node->contents < 0) { if (node->contents != CONTENTS_SOLID) { - pvs = Mod_LeafPVS((mleaf_t*)node, sv.worldmodel); - for (i = 0; i < fatbytes; i++) { + byte* pvs = Mod_LeafPVS(reinterpret_cast(node), sv.worldmodel); + for (int i = 0; i < fatbytes; i++) { fatpvs[i] |= pvs[i]; } } @@ -408,8 +402,8 @@ void SV_AddToFatPVS(const Vector3& org, mnode_t* node) return; } - plane = node->plane; - d = org.dot(plane->normal) - plane->dist; + const mplane_t* plane = node->plane; + float d = org.dot(plane->normal) - plane->dist; if (d > 8) { node = node->children[0]; } else if (d < -8) { @@ -630,7 +624,6 @@ void SV_WriteClientdataToMessage(edict_t* ent, sizebuf_t* msg) { int bits; int i; - edict_t* other; int items; eval_t* val; @@ -638,7 +631,7 @@ void SV_WriteClientdataToMessage(edict_t* ent, sizebuf_t* msg) // send a damage message // if (ent->v.dmg_take || ent->v.dmg_save) { - other = PROG_TO_EDICT(ent->v.dmg_inflictor); + edict_t* other = PROG_TO_EDICT(ent->v.dmg_inflictor); MSG_WriteByte(msg, svc_damage); MSG_WriteByte(msg, static_cast(ent->v.dmg_save)); MSG_WriteByte(msg, static_cast(ent->v.dmg_take)); @@ -1046,7 +1039,7 @@ void SV_SendReconnect(void) char data[128]; sizebuf_t msg; - msg.data = (byte*)data; + msg.data = reinterpret_cast(data); msg.cursize = 0; msg.maxsize = sizeof(data); @@ -1141,9 +1134,9 @@ void SV_SpawnServer(char* server) // Host_ClearMemory(); - memset(&sv, 0, sizeof(sv)); + sv = server_t{}; - strcpy_s(sv.name, sizeof(sv.name), server); + strlcpy(sv.name, server, sizeof(sv.name)); // load progs to get entity field count PR_LoadProgs(); @@ -1151,7 +1144,7 @@ void SV_SpawnServer(char* server) // allocate server memory sv.max_edicts = MAX_EDICTS; - sv.edicts = (edict_t *) Hunk_Alloc(sv.max_edicts * pr_edict_size, "edicts"); + sv.edicts = static_cast(Hunk_Alloc(sv.max_edicts * pr_edict_size, "edicts")); sv.datagram.maxsize = sizeof(sv.datagram_buf); sv.datagram.cursize = 0; @@ -1177,8 +1170,8 @@ void SV_SpawnServer(char* server) sv.time = 1.0; - strcpy_s(sv.name, sizeof(sv.name), server); - sprintf_s(sv.modelname, sizeof(sv.modelname), "maps/%s.bsp", server); + strlcpy(sv.name, server, sizeof(sv.name)); + snprintf(sv.modelname, sizeof(sv.modelname), "maps/%s.bsp", server); sv.worldmodel = Mod_ForName(sv.modelname, false); if (!sv.worldmodel) { Con_Printf("Couldn't spawn server %s\n", sv.modelname); @@ -1424,13 +1417,10 @@ If steptrace is not NULL, the trace of any vertical wall hit will be stored int SV_FlyMove(edict_t* ent, float time, trace_t* steptrace) { int bumpcount, numbumps; - Vector3 dir; - float d; int numplanes; Vector3 planes[MAX_CLIP_PLANES]; Vector3 primal_velocity, original_velocity, new_velocity; int i, j; - trace_t trace; Vector3 end; float time_left; int blocked; @@ -1451,7 +1441,7 @@ int SV_FlyMove(edict_t* ent, float time, trace_t* steptrace) end = ent->v.origin + ent->v.velocity * time_left; - trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); + trace_t trace = SV_Move(ent->v.origin, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) { // entity is trapped in another solid ent->v.velocity = vec3_origin; @@ -1535,8 +1525,8 @@ int SV_FlyMove(edict_t* ent, float time, trace_t* steptrace) return 7; } - dir = planes[0].cross(planes[1]); - d = dir.dot(ent->v.velocity); + Vector3 dir = planes[0].cross(planes[1]); + float d = dir.dot(ent->v.velocity); ent->v.velocity = dir * d; } @@ -3251,7 +3241,7 @@ Returns false if the client should be killed */ qboolean SV_ReadClientMessage(void) { - int ret; + int ret = 1; int msg_cmd; char* s; diff --git a/src/server.hpp b/src/server.hpp index 703e282..afc27a6 100644 --- a/src/server.hpp +++ b/src/server.hpp @@ -1,12 +1,12 @@ // server.h -- server state and entity management structures #pragma once -typedef struct { - int maxclients; - int maxclientslimit; - struct client_s* clients; // [maxclients] - int serverflags; // episode completion information - qboolean changelevel_issued; // cleared when at SV_SpawnServer +typedef struct server_static_s { + int maxclients = 0; + int maxclientslimit = 0; + struct client_s* clients = nullptr; // [maxclients] + int serverflags = 0; // episode completion information + qboolean changelevel_issued = false; // cleared when at SV_SpawnServer } server_static_t; //============================================================================= @@ -14,74 +14,74 @@ typedef struct { typedef enum { ss_loading, ss_active } server_state_t; -typedef struct { - qboolean active; // false if only a net client +typedef struct server_s { + qboolean active = false; // false if only a net client - qboolean paused; - qboolean loadgame; // handle connections specially + qboolean paused = false; + qboolean loadgame = false; // handle connections specially - double time; + double time = 0.0; - int lastcheck; // used by PF_checkclient - double lastchecktime; + int lastcheck = 0; // used by PF_checkclient + double lastchecktime = 0.0; - char name[64]; // map name - char modelname[64]; // maps/.bsp, for model_precache[0] - struct model_s* worldmodel; - char* model_precache[MAX_MODELS]; // NULL terminated - struct model_s* models[MAX_MODELS]; - char* sound_precache[MAX_SOUNDS]; // NULL terminated - char* lightstyles[MAX_LIGHTSTYLES]; - int num_edicts; - int max_edicts; - edict_t* edicts; // can NOT be array indexed, because + char name[64] = {}; // map name + char modelname[64] = {}; // maps/.bsp, for model_precache[0] + struct model_s* worldmodel = nullptr; + char* model_precache[MAX_MODELS] = {}; // NULL terminated + struct model_s* models[MAX_MODELS] = {}; + char* sound_precache[MAX_SOUNDS] = {}; // NULL terminated + char* lightstyles[MAX_LIGHTSTYLES] = {}; + int num_edicts = 0; + int max_edicts = 0; + edict_t* edicts = nullptr; // can NOT be array indexed, because // edict_t is variable sized, but can // be used to reference the world ent - server_state_t state; // some actions are only valid during load + server_state_t state = ss_loading; // some actions are only valid during load - sizebuf_t datagram; - byte datagram_buf[MAX_DATAGRAM]; + sizebuf_t datagram = {}; + byte datagram_buf[MAX_DATAGRAM] = {}; - sizebuf_t reliable_datagram; // copied to all clients at end of frame - byte reliable_datagram_buf[MAX_DATAGRAM]; + sizebuf_t reliable_datagram = {}; // copied to all clients at end of frame + byte reliable_datagram_buf[MAX_DATAGRAM] = {}; - sizebuf_t signon; - byte signon_buf[8192]; + sizebuf_t signon = {}; + byte signon_buf[8192] = {}; } server_t; #define NUM_PING_TIMES 16 #define NUM_SPAWN_PARMS 16 typedef struct client_s { - qboolean active; // false = client is free - qboolean spawned; // false = don't send datagrams - qboolean dropasap; // has been told to go to another level - qboolean privileged; // can execute any host command - qboolean sendsignon; // only valid before spawned + qboolean active = false; // false = client is free + qboolean spawned = false; // false = don't send datagrams + qboolean dropasap = false; // has been told to go to another level + qboolean privileged = false; // can execute any host command + qboolean sendsignon = false; // only valid before spawned - double last_message; // reliable messages must be sent + double last_message = 0.0; // reliable messages must be sent // periodically - struct qsocket_s* netconnection; // communications handle + struct qsocket_s* netconnection = nullptr; // communications handle - usercmd_t cmd; // movement + usercmd_t cmd = {}; // movement Vector3 wishdir; // intended motion calced from cmd - sizebuf_t message; // can be added to at any time, + sizebuf_t message = {}; // can be added to at any time, // copied and clear once per frame - byte msgbuf[MAX_MSGLEN]; - edict_t* edict; // EDICT_NUM(clientnum+1) - char name[32]; // for printing to other people - int colors; + byte msgbuf[MAX_MSGLEN] = {}; + edict_t* edict = nullptr; // EDICT_NUM(clientnum+1) + char name[32] = {}; // for printing to other people + int colors = 0; - float ping_times[NUM_PING_TIMES]; - int num_pings; // ping_times[num_pings%NUM_PING_TIMES] + float ping_times[NUM_PING_TIMES] = {}; + int num_pings = 0; // ping_times[num_pings%NUM_PING_TIMES] // spawn parms are carried from level to level - float spawn_parms[NUM_SPAWN_PARMS]; + float spawn_parms[NUM_SPAWN_PARMS] = {}; // client known data for deltas - int old_frags; + int old_frags = 0; } client_t; //============================================================================= @@ -159,6 +159,7 @@ extern cvar_t sv_gravity; class ServerSubsystem { public: + ServerSubsystem() = default; server_static_t& GetStaticState() { return svs_; } const server_static_t& GetStaticState() const { return svs_; } diff --git a/src/sys_sdl.cpp b/src/sys_sdl.cpp index e1dad1b..9d920bb 100644 --- a/src/sys_sdl.cpp +++ b/src/sys_sdl.cpp @@ -56,7 +56,7 @@ void Sys_Printf(const char* fmt, ...) char text[1024]; va_start(argptr, fmt); - vsprintf_s(text, sizeof(text), fmt, argptr); + vsnprintf(text, sizeof(text), fmt, argptr); va_end(argptr); fprintf(stderr, "%s", text); @@ -99,7 +99,7 @@ void Sys_HighFPPrecision(void) char string[1024]; va_start(argptr, error); - vsprintf_s(string, sizeof(string), error, argptr); + vsnprintf(string, sizeof(string), error, argptr); va_end(argptr); fprintf(stderr, "Error: %s\n", string); @@ -155,7 +155,7 @@ int Sys_FileOpenRead(const char* path, int* hndl) i = findhandle(); - if (fopen_s(&f, path, "rb") != 0) { + if ((f = fopen(path, "rb")) == NULL) { *hndl = -1; return -1; @@ -174,9 +174,9 @@ int Sys_FileOpenWrite(const char* path) i = findhandle(); - if (fopen_s(&f, path, "wb") != 0) { + if ((f = fopen(path, "wb")) == NULL) { char errbuf[256]; - strerror_s(errbuf, sizeof(errbuf), errno); + strerror_r(errno, errbuf, sizeof(errbuf)); Sys_Error("Error opening %s: %s", path, errbuf); } @@ -202,14 +202,11 @@ void Sys_FileSeek(int handle, int position) int Sys_FileRead(int handle, void* dst, int count) { - char* data; - int size, done; - - size = 0; + int size = 0; if (handle >= 0) { - data = (char*)dst; + char* data = static_cast(dst); while (count > 0) { - done = (int)fread(data, 1, count, sys_handles[handle]); + int done = static_cast(fread(data, 1, count, sys_handles[handle])); if (done == 0) { break; } @@ -225,14 +222,11 @@ int Sys_FileRead(int handle, void* dst, int count) int Sys_FileWrite(int handle, const void* src, int count) { - const char* data; - int size, done; - - size = 0; + int size = 0; if (handle >= 0) { - data = (const char*)src; + const char* data = static_cast(src); while (count > 0) { - done = (int)fwrite(data, 1, count, sys_handles[handle]); + int done = static_cast(fwrite(data, 1, count, sys_handles[handle])); if (done == 0) { break; } @@ -250,7 +244,7 @@ int Sys_FileTime(const char* path) { FILE* f; - if (fopen_s(&f, path, "rb") == 0) { + if ((f = fopen(path, "rb")) != NULL) { fclose(f); return 1; @@ -286,7 +280,6 @@ void moncontrol() int main(int c, char** v) { - double time, oldtime, newtime; quakeparms_t parms; extern int vcrFile; extern qboolean recording; @@ -312,11 +305,11 @@ int main(int c, char** v) Cvar::Register(&sys_nostdout); - oldtime = Sys_FloatTime() - 0.1; + double oldtime = Sys_FloatTime() - 0.1; while (1) { // find time spent rendering last frame - newtime = Sys_FloatTime(); - time = newtime - oldtime; + double newtime = Sys_FloatTime(); + double time = newtime - oldtime; if (cls.state == ca_dedicated) { // play vcrfiles at max speed if (time < sys_ticrate.value && (vcrFile == -1 || recording)) { diff --git a/src/vid.hpp b/src/vid.hpp index 978ded0..5171933 100644 --- a/src/vid.hpp +++ b/src/vid.hpp @@ -41,18 +41,18 @@ extern unsigned d_8to24table[256]; extern void (*vid_menudrawfn)(void); extern void (*vid_menukeyfn)(int key); -void VID_SetPalette(unsigned char* palette); +void VID_SetPalette(const unsigned char* palette); -inline void VID_ShiftPalette(unsigned char* palette) +inline void VID_ShiftPalette(const unsigned char* palette) { VID_SetPalette(palette); } -void VID_Init(unsigned char* palette); +void VID_Init(const unsigned char* palette); void VID_Shutdown(void); -void VID_Update(vrect_t* rects); +void VID_Update(const vrect_t* rects); int VID_SetMode(int modenum, unsigned char* palette); diff --git a/src/vid_sdl.cpp b/src/vid_sdl.cpp index 3bf13a4..70dc9c0 100644 --- a/src/vid_sdl.cpp +++ b/src/vid_sdl.cpp @@ -2,6 +2,7 @@ #include "SDL.h" #include "quakedef.hpp" +#include using namespace CDAudio; using namespace Client; @@ -27,7 +28,10 @@ using namespace Wad; using namespace Cvar; using namespace Cmd; #include "d_local.hpp" + +#ifdef _WIN32 #include "winquake.hpp" +#endif cvar_t _windowed_mouse = {"_windowed_mouse", "1", {}, {}, {}, {}}; @@ -55,7 +59,7 @@ static qboolean mouse_avail; static float mouse_x, mouse_y; static int mouse_oldbuttonstate = 0; -void VID_SetPalette(unsigned char* palette) +void VID_SetPalette(const unsigned char* palette) { int i; SDL_Color colors[256]; @@ -71,7 +75,7 @@ void VID_SetPalette(unsigned char* palette) } } -void VID_Init(unsigned char* palette) +void VID_Init(const unsigned char* palette) { int pnum, chunk; byte* cache; @@ -151,8 +155,8 @@ void VID_Init(unsigned char* palette) vid.aspect = static_cast(((float)vid.height / (float)vid.width) * (320.0 / 240.0)); vid.numpages = 1; vid.colormap = host_colormap; - vid.fullbright = 256 - LittleLong(*((int*)vid.colormap + 2048)); - VGA_pagebase = vid.buffer = (pixel_t*)screen->pixels; + vid.fullbright = 256 - LittleLong(reinterpret_cast(vid.colormap)[2048]); + VGA_pagebase = vid.buffer = static_cast(screen->pixels); VGA_rowbytes = vid.rowbytes = screen->pitch; vid.conbuffer = vid.buffer; vid.conrowbytes = vid.rowbytes; @@ -162,13 +166,13 @@ void VID_Init(unsigned char* palette) chunk = vid.width * vid.height * sizeof(*d_pzbuffer); cachesize = D_SurfaceCacheForRes(vid.width, vid.height); chunk += cachesize; - d_pzbuffer = (short *) Hunk_HighAllocName(chunk, "video"); + d_pzbuffer = static_cast(Hunk_HighAllocName(chunk, "video")); if (d_pzbuffer == NULL) { Sys_Error("Not enough memory for video mode\n"); } // Initialize the cache memory - cache = (byte*)d_pzbuffer + vid.width * vid.height * sizeof(*d_pzbuffer); + cache = reinterpret_cast(d_pzbuffer) + vid.width * vid.height * sizeof(*d_pzbuffer); D_InitCaches(cache, cachesize); // Initialize the mouse @@ -185,11 +189,10 @@ void VID_Shutdown(void) SDL_Quit(); } -void VID_Update(vrect_t* rects) +void VID_Update(const vrect_t* rects) { - SDL_Rect* sdlrects; - int n, i; - vrect_t* rect; + int n; + const vrect_t* rect; // Two-pass system, since Quake doesn't do it the SDL way... @@ -200,11 +203,9 @@ void VID_Update(vrect_t* rects) } // Second, copy them to SDL rectangles and update - if (!(sdlrects = (SDL_Rect*)alloca(n * sizeof(*sdlrects)))) { - Sys_Error("Out of memory"); - } + std::vector sdlrects(n); - i = 0; + int i = 0; for (rect = rects; rect; rect = rect->pnext) { sdlrects[i].x = rect->x; sdlrects[i].y = rect->y; @@ -217,9 +218,9 @@ void VID_Update(vrect_t* rects) SDL_Surface* window_surface = SDL_GetWindowSurface(window); if (screen != window_surface) { SDL_BlitSurface(screen, NULL, window_surface, NULL); - SDL_UpdateWindowSurfaceRects(window, sdlrects, n); + SDL_UpdateWindowSurfaceRects(window, sdlrects.data(), n); } else { - SDL_UpdateWindowSurfaceRects(window, sdlrects, n); + SDL_UpdateWindowSurfaceRects(window, sdlrects.data(), n); } } @@ -240,7 +241,7 @@ void D_BeginDirectRect(int x, int y, byte* pbitmap, int width, int height) x = screen->w + x - 1; } - offset = (Uint8*)screen->pixels + y * screen->pitch + x; + offset = static_cast(screen->pixels) + y * screen->pitch + x; while (height--) { memcpy(offset, pbitmap, width); offset += screen->pitch; diff --git a/src/view.cpp b/src/view.cpp index 490481d..053d1d3 100644 --- a/src/view.cpp +++ b/src/view.cpp @@ -259,18 +259,8 @@ byte gammatable[256]; // palette is sent through this void BuildGammaTable(float g) { - int i, inf; - - if (g == 1.0) { - for (i = 0; i < 256; i++) { - gammatable[i] = static_cast(i); - } - - return; - } - - for (i = 0; i < 256; i++) { - inf = static_cast(255 * pow((i + 0.5) / 255.5, g) + 0.5); + for (int i = 0; i < 256; i++) { + int inf = static_cast(255 * pow((i + 0.5) / 255.5, g) + 0.5); if (inf < 0) { inf = 0; } @@ -475,7 +465,6 @@ void V_UpdatePalette(void) qboolean new_shift; byte *basepal, *newpal; byte pal[768]; - int r, g, b; qboolean force; V_CalcPowerupCshift(); @@ -517,15 +506,15 @@ void V_UpdatePalette(void) newpal = pal; for (i = 0; i < 256; i++) { - r = basepal[0]; - g = basepal[1]; - b = basepal[2]; + int r = basepal[0]; + int g = basepal[1]; + int b = basepal[2]; basepal += 3; - for (j = 0; j < NUM_CSHIFTS; j++) { - r += (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[0] - r)) >> 8; - g += (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[1] - g)) >> 8; - b += (cl.cshifts[j].percent * (cl.cshifts[j].destcolor[2] - b)) >> 8; + for (int k = 0; k < NUM_CSHIFTS; k++) { + r += (cl.cshifts[k].percent * (cl.cshifts[k].destcolor[0] - r)) >> 8; + g += (cl.cshifts[k].percent * (cl.cshifts[k].destcolor[1] - g)) >> 8; + b += (cl.cshifts[k].percent * (cl.cshifts[k].destcolor[2] - b)) >> 8; } newpal[0] = gammatable[r]; @@ -626,7 +615,7 @@ V_BoundOffsets */ void V_BoundOffsets(void) { - entity_t* ent; + const entity_t* ent; ent = &cl_entities[cl.viewentity]; diff --git a/src/vm.cpp b/src/vm.cpp index 948376f..c9b2f7b 100644 --- a/src/vm.cpp +++ b/src/vm.cpp @@ -276,7 +276,7 @@ eval_t* GetEdictFieldValue(edict_t* ed, const char* field) if (strlen(field) < MAX_FIELD_LEN) { gefvCache[rep].pcache = def; - strcpy_s(gefvCache[rep].field, sizeof(gefvCache[rep].field), field); + strlcpy(gefvCache[rep].field, field, sizeof(gefvCache[rep].field)); rep ^= 1; } @@ -305,34 +305,34 @@ char* PR_ValueString(etype_t type, eval_t* val) switch (type) { case ev_string: - sprintf_s(line, sizeof(line), "%s", PR_GetString(val->string)); + snprintf(line, sizeof(line), "%s", PR_GetString(val->string)); break; case ev_entity: - sprintf_s(line, sizeof(line), "entity %i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); + snprintf(line, sizeof(line), "entity %i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); break; case ev_function: f = pr_functions + val->function; - sprintf_s(line, sizeof(line), "%s()", PR_GetString(f->s_name)); + snprintf(line, sizeof(line), "%s()", PR_GetString(f->s_name)); break; case ev_field: def = ED_FieldAtOfs(val->_int); - sprintf_s(line, sizeof(line), ".%s", PR_GetString(def->s_name)); + snprintf(line, sizeof(line), ".%s", PR_GetString(def->s_name)); break; case ev_void: - sprintf_s(line, sizeof(line), "void"); + snprintf(line, sizeof(line), "void"); break; case ev_float: - sprintf_s(line, sizeof(line), "%5.1f", val->_float); + snprintf(line, sizeof(line), "%5.1f", val->_float); break; case ev_vector: - sprintf_s(line, sizeof(line), "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], + snprintf(line, sizeof(line), "'%5.1f %5.1f %5.1f'", val->vector[0], val->vector[1], val->vector[2]); break; case ev_pointer: - sprintf_s(line, sizeof(line), "pointer"); + snprintf(line, sizeof(line), "pointer"); break; default: - sprintf_s(line, sizeof(line), "bad type %i", type); + snprintf(line, sizeof(line), "bad type %i", type); break; } @@ -357,30 +357,30 @@ char* PR_UglyValueString(etype_t type, eval_t* val) switch (type) { case ev_string: - sprintf_s(line, sizeof(line), "%s", PR_GetString(val->string)); + snprintf(line, sizeof(line), "%s", PR_GetString(val->string)); break; case ev_entity: - sprintf_s(line, sizeof(line), "%i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); + snprintf(line, sizeof(line), "%i", NUM_FOR_EDICT(PROG_TO_EDICT(val->edict))); break; case ev_function: f = pr_functions + val->function; - sprintf_s(line, sizeof(line), "%s", PR_GetString(f->s_name)); + snprintf(line, sizeof(line), "%s", PR_GetString(f->s_name)); break; case ev_field: def = ED_FieldAtOfs(val->_int); - sprintf_s(line, sizeof(line), "%s", PR_GetString(def->s_name)); + snprintf(line, sizeof(line), "%s", PR_GetString(def->s_name)); break; case ev_void: - sprintf_s(line, sizeof(line), "void"); + snprintf(line, sizeof(line), "void"); break; case ev_float: - sprintf_s(line, sizeof(line), "%f", val->_float); + snprintf(line, sizeof(line), "%f", val->_float); break; case ev_vector: - sprintf_s(line, sizeof(line), "%f %f %f", val->vector[0], val->vector[1], val->vector[2]); + snprintf(line, sizeof(line), "%f %f %f", val->vector[0], val->vector[1], val->vector[2]); break; default: - sprintf_s(line, sizeof(line), "bad type %i", type); + snprintf(line, sizeof(line), "bad type %i", type); break; } @@ -406,17 +406,17 @@ char* PR_GlobalString(int ofs) val = (void*)&pr_globals[ofs]; def = ED_GlobalAtOfs(ofs); if (!def) { - sprintf_s(line, sizeof(line), "%i(??? unknown)", ofs); + snprintf(line, sizeof(line), "%i(??? unknown)", ofs); } else { s = PR_ValueString((etype_t)def->type, (eval_t*)val); - sprintf_s(line, sizeof(line), "%i(%s)%s", ofs, PR_GetString(def->s_name), s); + snprintf(line, sizeof(line), "%i(%s)%s", ofs, PR_GetString(def->s_name), s); } i = (int)strlen(line); for (; i < 20; i++) { - strcat_s(line, sizeof(line), " "); + strlcat(line, " ", sizeof(line)); } - strcat_s(line, sizeof(line), " "); + strlcat(line, " ", sizeof(line)); return line; } @@ -429,16 +429,16 @@ char* PR_GlobalStringNoContents(int ofs) def = ED_GlobalAtOfs(ofs); if (!def) { - sprintf_s(line, sizeof(line), "%i(???)", ofs); + snprintf(line, sizeof(line), "%i(???)", ofs); } else { - sprintf_s(line, sizeof(line), "%i(%s)", ofs, PR_GetString(def->s_name)); + snprintf(line, sizeof(line), "%i(%s)", ofs, PR_GetString(def->s_name)); } i = (int)strlen(line); for (; i < 20; i++) { - strcat_s(line, sizeof(line), " "); + strlcat(line, " ", sizeof(line)); } - strcat_s(line, sizeof(line), " "); + strlcat(line, " ", sizeof(line)); return line; } @@ -695,7 +695,7 @@ void ED_ParseGlobals(char* data) Sys_Error("ED_ParseEntity: EOF without closing brace"); } - strcpy_s(keyname, sizeof(keyname), com_token); + strlcpy(keyname, com_token, sizeof(keyname)); // parse value data = COM_Parse(data); @@ -783,7 +783,7 @@ qboolean ED_ParseEpair(void* base, ddef_t* key, char* s) break; case ev_vector: - strcpy_s(string, sizeof(string), s); + strlcpy(string, s, sizeof(string)); v = string; w = string; for (i = 0; i < 3; i++) { @@ -868,7 +868,7 @@ char* ED_ParseEdict(char* data, edict_t* ent) // anglehack is to allow QuakeEd to write single scalar angles // and allow them to be turned into vectors. (FIXME...) if (!strcmp(com_token, "angle")) { - strcpy_s(com_token, sizeof(com_token), "angles"); + strlcpy(com_token, "angles", sizeof(com_token)); anglehack = true; } else { anglehack = false; @@ -876,10 +876,10 @@ char* ED_ParseEdict(char* data, edict_t* ent) // FIXME: change light to _light to get rid of this hack if (!strcmp(com_token, "light")) { - strcpy_s(com_token, sizeof(com_token), "light_lev"); // hack for single light def + strlcpy(com_token, "light_lev", sizeof(com_token)); // hack for single light def } - strcpy_s(keyname, sizeof(keyname), com_token); + strlcpy(keyname, com_token, sizeof(keyname)); // another hack to fix heynames with trailing spaces n = (int)strlen(keyname); @@ -914,8 +914,8 @@ char* ED_ParseEdict(char* data, edict_t* ent) if (anglehack) { char temp[32]; - strcpy_s(temp, sizeof(temp), com_token); - sprintf_s(com_token, sizeof(com_token), "0 %s 0", temp); + strlcpy(temp, com_token, sizeof(temp)); + snprintf(com_token, sizeof(com_token), "0 %s 0", temp); } if (!ED_ParseEpair((void*)&ent->v, key, com_token)) { @@ -1505,7 +1505,7 @@ Aborts the currently executing function char string[1024]; va_start(argptr, error); - vsprintf_s(string, sizeof(string), error, argptr); + vsnprintf(string, sizeof(string), error, argptr); va_end(argptr); PR_PrintStatement(pr_statements + pr_xstatement); @@ -1936,7 +1936,7 @@ char* PF_VarString(int first) out[0] = 0; for (i = first; i < pr_argc; i++) { - strcat_s(out, sizeof(out), G_STRING((OFS_PARM0 + i * 3))); + strlcat(out, G_STRING((OFS_PARM0 + i * 3)), sizeof(out)); } return out; @@ -2487,7 +2487,7 @@ break() void PF_break(void) { Con_Printf("break statement\n"); - *(int*)-4 = 0; // dump to debugger + *reinterpret_cast(-4) = 0; // dump to debugger // PR_RunError ("break statement"); } @@ -2794,9 +2794,9 @@ void PF_ftos(void) v = G_FLOAT(OFS_PARM0); if (v == (int)v) { - sprintf_s(pr_string_temp, sizeof(pr_string_temp), "%d", (int)v); + snprintf(pr_string_temp, sizeof(pr_string_temp), "%d", (int)v); } else { - sprintf_s(pr_string_temp, sizeof(pr_string_temp), "%5.1f", v); + snprintf(pr_string_temp, sizeof(pr_string_temp), "%5.1f", v); } G_INT(OFS_RETURN) = PR_SetString(pr_string_temp); @@ -2811,7 +2811,7 @@ void PF_fabs(void) void PF_vtos(void) { - sprintf_s(pr_string_temp, sizeof(pr_string_temp), "'%5.1f %5.1f %5.1f'", G_VECTOR(OFS_PARM0)[0], + snprintf(pr_string_temp, sizeof(pr_string_temp), "'%5.1f %5.1f %5.1f'", G_VECTOR(OFS_PARM0)[0], G_VECTOR(OFS_PARM0)[1], G_VECTOR(OFS_PARM0)[2]); G_INT(OFS_RETURN) = PR_SetString(pr_string_temp); } diff --git a/src/vm.hpp b/src/vm.hpp index ac704aa..a6e7e29 100644 --- a/src/vm.hpp +++ b/src/vm.hpp @@ -76,10 +76,10 @@ void ED_LoadFromFile(char* data); edict_t* EDICT_NUM(int n); int NUM_FOR_EDICT(edict_t* e); -#define NEXT_EDICT(e) ((edict_t*)((byte*)e + pr_edict_size)) +#define NEXT_EDICT(e) (reinterpret_cast(reinterpret_cast(e) + pr_edict_size)) -#define EDICT_TO_PROG(e) ((byte*)e - (byte*)sv.edicts) -#define PROG_TO_EDICT(e) ((edict_t*)((byte*)sv.edicts + e)) +#define EDICT_TO_PROG(e) (reinterpret_cast(e) - reinterpret_cast(sv.edicts)) +#define PROG_TO_EDICT(e) (reinterpret_cast(reinterpret_cast(sv.edicts) + e)) //============================================================================ diff --git a/src/wad.cpp b/src/wad.cpp index 5af95db..8b0b61b 100644 --- a/src/wad.cpp +++ b/src/wad.cpp @@ -49,10 +49,9 @@ Can safely be performed in place. void W_CleanupName(const char* in, char* out) { int i; - int c; for (i = 0; i < 16; i++) { - c = in[i]; + int c = in[i]; if (!c) { break; } @@ -86,7 +85,7 @@ void W_LoadWadFile(const char* filename) Sys_Error("W_LoadWadFile: couldn't load %s", filename); } - header = (wadinfo_t*)wad_base; + header = reinterpret_cast(wad_base); if (header->identification[0] != 'W' || header->identification[1] != 'A' || header->identification[2] != 'D' || header->identification[3] != '2') { Sys_Error("Wad file %s doesn't have WAD2 id\n", filename); @@ -94,14 +93,14 @@ void W_LoadWadFile(const char* filename) wad_numlumps = LittleLong(header->numlumps); infotableofs = LittleLong(header->infotableofs); - wad_lumps = (lumpinfo_t*)(wad_base + infotableofs); + wad_lumps = reinterpret_cast(wad_base + infotableofs); for (i = 0, lump_p = wad_lumps; i < (unsigned)wad_numlumps; i++, lump_p++) { lump_p->filepos = LittleLong(lump_p->filepos); lump_p->size = LittleLong(lump_p->size); W_CleanupName(lump_p->name, lump_p->name); if (lump_p->type == TYP_QPIC) { - SwapPic((qpic_t*)(wad_base + lump_p->filepos)); + SwapPic(reinterpret_cast(wad_base + lump_p->filepos)); } } } @@ -130,11 +129,9 @@ lumpinfo_t* W_GetLumpinfo(const char* name) void* W_GetLumpName(const char* name) { - lumpinfo_t* lump; + const lumpinfo_t* lump = W_GetLumpinfo(name); - lump = W_GetLumpinfo(name); - - return (void*)(wad_base + lump->filepos); + return static_cast(wad_base + lump->filepos); } /* diff --git a/src/wad.hpp b/src/wad.hpp index b7789f7..d29b734 100644 --- a/src/wad.hpp +++ b/src/wad.hpp @@ -18,9 +18,9 @@ #define TYP_SOUND 67 #define TYP_MIPTEX 68 -typedef struct { - int width, height; - byte data[4]; // variably sized +typedef struct qpic_s { + int width = 0, height = 0; + byte data[4] = {}; // variably sized } qpic_t; typedef struct { diff --git a/src/world.cpp b/src/world.cpp index 88575bd..dbcd213 100644 --- a/src/world.cpp +++ b/src/world.cpp @@ -37,17 +37,17 @@ line of sight checks trace->crosscontent, but bullets don't */ -typedef struct { - Vector3 boxmins, boxmaxs; // enclose the test object along entire move - Vector3 mins, maxs; // size of the moving object - Vector3 mins2, maxs2; // size when clipping against mosnters - Vector3 start, end; - trace_t trace; - int type; - edict_t* passedict; +typedef struct moveclip_s { + Vector3 boxmins = {}, boxmaxs = {}; // enclose the test object along entire move + Vector3 mins = {}, maxs = {}; // size of the moving object + Vector3 mins2 = {}, maxs2 = {}; // size when clipping against mosnters + Vector3 start = {}, end = {}; + trace_t trace = {}; + int type = 0; + edict_t* passedict = nullptr; } moveclip_t; -int SV_HullPointContents(hull_t* hull, int num, const Vector3& p); +int SV_HullPointContents(const hull_t* hull, int num, const Vector3& p); /* =============================================================================== @@ -72,7 +72,6 @@ can just be stored out and get a proper hull_t structure. void SV_InitBoxHull(void) { int i; - int side; box_hull.clipnodes = box_clipnodes; box_hull.planes = box_planes; @@ -82,7 +81,7 @@ void SV_InitBoxHull(void) for (i = 0; i < 6; i++) { box_clipnodes[i].planenum = i; - side = i & 1; + int side = i & 1; box_clipnodes[i].children[side] = CONTENTS_EMPTY; if (i != 5) { @@ -132,8 +131,6 @@ hull_t* SV_HullForEntity(edict_t* ent, Vector3& offset) { model_t* model; - Vector3 size; - Vector3 hullmins, hullmaxs; hull_t* hull; // decide which clipping hull to use, based on the size @@ -148,7 +145,7 @@ hull_t* SV_HullForEntity(edict_t* ent, Sys_Error("MOVETYPE_PUSH with a non bsp model"); } - size = maxs - mins; + Vector3 size = maxs - mins; if (size.x < 3) { hull = &model->hulls[0]; } else if (size.x <= 32) { @@ -162,8 +159,8 @@ hull_t* SV_HullForEntity(edict_t* ent, offset += ent->v.origin; } else { // create a temp hull from bounding box sizes - hullmins = ent->v.mins - maxs; - hullmaxs = ent->v.maxs - mins; + Vector3 hullmins = ent->v.mins - maxs; + Vector3 hullmaxs = ent->v.maxs - mins; hull = SV_HullForBox(hullmins, hullmaxs); offset = ent->v.origin; @@ -181,11 +178,11 @@ ENTITY AREA CHECKING */ typedef struct areanode_s { - int axis; // -1 = leaf node - float dist; - struct areanode_s* children[2]; - link_t trigger_edicts; - link_t solid_edicts; + int axis = 0; // -1 = leaf node + float dist = 0.0f; + struct areanode_s* children[2] = { nullptr, nullptr }; + link_t trigger_edicts = {}; + link_t solid_edicts = {}; } areanode_t; #define AREA_DEPTH 4 @@ -250,7 +247,9 @@ void SV_ClearWorld(void) { SV_InitBoxHull(); - memset(sv_areanodes, 0, sizeof(sv_areanodes)); + for (auto& node : sv_areanodes) { + node = areanode_t{}; + } sv_numareanodes = 0; SV_CreateAreaNode(0, sv.worldmodel->mins, sv.worldmodel->maxs); } @@ -279,13 +278,12 @@ SV_TouchLinks void SV_TouchLinks(edict_t* ent, areanode_t* node) { link_t *l, *next; - edict_t* touch; int old_self, old_other; // touch linked edicts for (l = node->trigger_edicts.next; l != &node->trigger_edicts; l = next) { next = l->next; - touch = EDICT_FROM_AREA(l); + edict_t* touch = EDICT_FROM_AREA(l); if (touch == ent) { continue; } @@ -333,9 +331,7 @@ SV_FindTouchedLeafs void SV_FindTouchedLeafs(edict_t* ent, mnode_t* node) { mplane_t* splitplane; - mleaf_t* leaf; int sides; - int leafnum; if (node->contents == CONTENTS_SOLID) { return; @@ -348,8 +344,8 @@ void SV_FindTouchedLeafs(edict_t* ent, mnode_t* node) return; } - leaf = (mleaf_t*)node; - leafnum = static_cast(leaf - sv.worldmodel->leafs - 1); + const mleaf_t* leaf = reinterpret_cast(node); + int leafnum = static_cast(leaf - sv.worldmodel->leafs - 1); ent->leafnums[ent->num_leafs] = static_cast(leafnum); ent->num_leafs++; @@ -474,19 +470,17 @@ SV_HullPointContents ================== */ -int SV_HullPointContents(hull_t* hull, int num, const Vector3& p) +int SV_HullPointContents(const hull_t* hull, int num, const Vector3& p) { float d; - dclipnode_t* node; - mplane_t* plane; while (num >= 0) { if (num < hull->firstclipnode || num > hull->lastclipnode) { Sys_Error("SV_HullPointContents: bad node number"); } - node = hull->clipnodes + num; - plane = hull->planes + node->planenum; + const dclipnode_t* node = hull->clipnodes + num; + const mplane_t* plane = hull->planes + node->planenum; if (plane->type < 3) { d = p[plane->type] - plane->dist; @@ -561,7 +555,7 @@ SV_RecursiveHullCheck ================== */ -qboolean SV_RecursiveHullCheck(hull_t* hull, +qboolean SV_RecursiveHullCheck(const hull_t* hull, int num, float p1f, float p2f, @@ -569,8 +563,6 @@ qboolean SV_RecursiveHullCheck(hull_t* hull, const Vector3& p2, trace_t* trace) { - dclipnode_t* node; - mplane_t* plane; float t1, t2; float frac; Vector3 mid; @@ -600,8 +592,8 @@ qboolean SV_RecursiveHullCheck(hull_t* hull, // // find the point distances // - node = hull->clipnodes + num; - plane = hull->planes + node->planenum; + const dclipnode_t* node = hull->clipnodes + num; + const mplane_t* plane = hull->planes + node->planenum; if (plane->type < 3) { t1 = p1[plane->type] - plane->dist; @@ -731,7 +723,7 @@ trace_t SV_ClipMoveToEntity(edict_t* ent, hull_t* hull; // fill in a default trace - memset(&trace, 0, sizeof(trace_t)); + trace = trace_t{}; trace.fraction = 1; trace.allsolid = true; trace.endpos = end; diff --git a/src/world.hpp b/src/world.hpp index 37f1a8e..950d947 100644 --- a/src/world.hpp +++ b/src/world.hpp @@ -1,19 +1,19 @@ // world.h -- collision detection structures (trace, plane, hull) #pragma once -typedef struct { - Vector3 normal; - float dist; +typedef struct plane_s { + Vector3 normal = {}; + float dist = 0.0f; } plane_t; -typedef struct { - qboolean allsolid; // if true, plane is not valid - qboolean startsolid; // if true, the initial point was in a solid area - qboolean inopen, inwater; - float fraction; // time completed, 1.0 = didn't hit anything - Vector3 endpos; // final position - plane_t plane; // surface normal at impact - edict_t* ent; // entity the surface is on +typedef struct trace_s { + qboolean allsolid = false; // if true, plane is not valid + qboolean startsolid = false; // if true, the initial point was in a solid area + qboolean inopen = false, inwater = false; + float fraction = 1.0f; // time completed, 1.0 = didn't hit anything + Vector3 endpos = {}; // final position + plane_t plane = {}; // surface normal at impact + edict_t* ent = nullptr; // entity the surface is on } trace_t; #define MOVE_NORMAL 0 @@ -60,6 +60,6 @@ trace_t SV_Move(const Vector3& start, // shouldn't be considered solid objects // passedict is explicitly excluded from clipping checks (normally NULL) -qboolean SV_RecursiveHullCheck(hull_t* hull, int num, float p1f, float p2f, const Vector3& p1, const Vector3& p2, trace_t* trace); +qboolean SV_RecursiveHullCheck(const hull_t* hull, int num, float p1f, float p2f, const Vector3& p1, const Vector3& p2, trace_t* trace); } // namespace Server diff --git a/src/zone.cpp b/src/zone.cpp index 36df0ab..53d8404 100644 --- a/src/zone.cpp +++ b/src/zone.cpp @@ -83,7 +83,7 @@ void Z_ClearZone(memzone_t* zone, int size) // set the entire zone to one free block - zone->blocklist.next = zone->blocklist.prev = block = (memblock_t*)((byte*)zone + sizeof(memzone_t)); + zone->blocklist.next = zone->blocklist.prev = block = reinterpret_cast(reinterpret_cast(zone) + sizeof(memzone_t)); zone->blocklist.tag = 1; // in use block zone->blocklist.id = 0; zone->blocklist.size = 0; @@ -108,7 +108,7 @@ void Z_Free(void* ptr) Sys_Error("Z_Free: NULL pointer"); } - block = (memblock_t*)((byte*)ptr - sizeof(memblock_t)); + block = reinterpret_cast(reinterpret_cast(ptr) - sizeof(memblock_t)); if (block->id != ZONEID) { Sys_Error("Z_Free: freed a pointer without ZONEID"); } @@ -169,7 +169,7 @@ void* Z_Realloc(void* ptr, int new_size) } // Validate the existing block - memblock_t* block = (memblock_t*)((byte*)ptr - sizeof(memblock_t)); + const memblock_t* block = reinterpret_cast(reinterpret_cast(ptr) - sizeof(memblock_t)); if (block->id != ZONEID) { Sys_Error("Z_Realloc: pointer missing ZONEID"); } @@ -215,7 +215,7 @@ void* Z_Realloc(void* ptr, int new_size) } // Zero-fill the newly expanded space - Q_memset((char*)new_ptr + usable_old_size, 0, new_size - usable_old_size); + Q_memset(static_cast(new_ptr) + usable_old_size, 0, new_size - usable_old_size); return new_ptr; } @@ -223,7 +223,7 @@ void* Z_Realloc(void* ptr, int new_size) void* Z_TagMalloc(int size, int tag) { int extra; - memblock_t *start, *rover, *new_block, *base; + memblock_t *new_block, *base; if (!tag) { Sys_Error("Z_TagMalloc: tried to use a 0 tag"); @@ -237,8 +237,9 @@ void* Z_TagMalloc(int size, int tag) size += 4; // space for memory trash tester size = (size + 7) & ~7; // align to 8-byte boundary - base = rover = mainzone->rover; - start = base->prev; + base = mainzone->rover; + const memblock_t* rover = base; + const memblock_t* start = base->prev; do { if (rover == start) { // scaned all the way around the list @@ -246,7 +247,8 @@ void* Z_TagMalloc(int size, int tag) } if (rover->tag) { - base = rover = rover->next; + base = rover->next; + rover = base; } else { rover = rover->next; } @@ -257,7 +259,7 @@ void* Z_TagMalloc(int size, int tag) // extra = base->size - size; if (extra > MINFRAGMENT) { // there will be a free fragment after the allocated block - new_block = (memblock_t*)((byte*)base + size); + new_block = reinterpret_cast(reinterpret_cast(base) + size); new_block->size = extra; new_block->tag = 0; // free block new_block->prev = base; @@ -275,9 +277,9 @@ void* Z_TagMalloc(int size, int tag) base->id = ZONEID; // marker for memory trash testing - *(int*)((byte*)base + base->size - 4) = ZONEID; + *reinterpret_cast(reinterpret_cast(base) + base->size - 4) = ZONEID; - return (void*)((byte*)base + sizeof(memblock_t)); + return reinterpret_cast(base) + sizeof(memblock_t); } /* @@ -287,14 +289,12 @@ Z_CheckHeap */ void Z_CheckHeap(void) { - memblock_t* block; - - for (block = mainzone->blocklist.next;; block = block->next) { + for (const memblock_t* block = mainzone->blocklist.next;; block = block->next) { if (block->next == &mainzone->blocklist) { break; // all blocks have been hit } - if ((byte*)block + block->size != (byte*)block->next) { + if (reinterpret_cast(block) + block->size != reinterpret_cast(block->next)) { Sys_Error("Z_CheckHeap: block size does not touch the next block\n"); } @@ -338,18 +338,18 @@ Run consistancy and sentinal trahing checks */ void Hunk_Check(void) { - hunk_t* h; + const hunk_t* h; - for (h = (hunk_t*)hunk_base; (byte*)h != hunk_base + hunk_low_used;) { + for (h = reinterpret_cast(hunk_base); reinterpret_cast(h) != hunk_base + hunk_low_used;) { if (h->sentinal != HUNK_SENTINAL) { Sys_Error("Hunk_Check: trahsed sentinal"); } - if (h->size < 16 || h->size + (byte*)h - hunk_base > hunk_size) { + if (h->size < 16 || h->size + reinterpret_cast(h) - hunk_base > hunk_size) { Sys_Error("Hunk_Check: bad size"); } - h = (hunk_t*)((byte*)h + h->size); + h = reinterpret_cast(reinterpret_cast(h) + h->size); } } @@ -376,7 +376,7 @@ void* Hunk_Alloc(int size, const char* name) Sys_Error("Hunk_Alloc: failed on %i bytes", size); } - h = (hunk_t*)(hunk_base + hunk_low_used); + h = reinterpret_cast(hunk_base + hunk_low_used); hunk_low_used += size; Cache_FreeLow(hunk_low_used); @@ -463,7 +463,7 @@ void* Hunk_HighAllocName(int size, const char* name) hunk_high_used += size; Cache_FreeHigh(hunk_high_used); - h = (hunk_t*)(hunk_base + hunk_size - hunk_high_used); + h = reinterpret_cast(hunk_base + hunk_size - hunk_high_used); memset(h, 0, size); h->size = size; @@ -538,7 +538,7 @@ void Cache_Move(cache_system_t* c) new_cs->user = c->user; Q_memcpy(new_cs->name, c->name, sizeof(new_cs->name)); Cache_Free(c->user); - new_cs->user->data = (void*)(new_cs + 1); + new_cs->user->data = new_cs + 1; } else { // Con_Printf ("cache_move failed\n"); @@ -555,15 +555,13 @@ Throw things out until the hunk can be expanded to the given point */ void Cache_FreeLow(int new_low_hunk) { - cache_system_t* c; - while (1) { - c = cache_head.next; + cache_system_t* c = cache_head.next; if (c == &cache_head) { return; // nothing in cache at all } - if ((byte*)c >= hunk_base + new_low_hunk) { + if (reinterpret_cast(c) >= hunk_base + new_low_hunk) { return; // there is space to grow the hunk } @@ -580,16 +578,14 @@ Throw things out until the hunk can be expanded to the given point */ void Cache_FreeHigh(int new_high_hunk) { - cache_system_t *c, *prev; - - prev = NULL; + cache_system_t* prev = NULL; while (1) { - c = cache_head.prev; + cache_system_t* c = cache_head.prev; if (c == &cache_head) { return; // nothing in cache at all } - if ((byte*)c + c->size <= hunk_base + hunk_size - new_high_hunk) { + if (reinterpret_cast(c) + c->size <= hunk_base + hunk_size - new_high_hunk) { return; // there is space to grow the hunk } @@ -645,7 +641,7 @@ cache_system_t* Cache_TryAlloc(int size, qboolean nobottom) Sys_Error("Cache_TryAlloc: %i is greater then free hunk", size); } - new_cs = (cache_system_t*)(hunk_base + hunk_low_used); + new_cs = reinterpret_cast(hunk_base + hunk_low_used); memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; @@ -659,12 +655,12 @@ cache_system_t* Cache_TryAlloc(int size, qboolean nobottom) // search from the bottom up for space - new_cs = (cache_system_t*)(hunk_base + hunk_low_used); + new_cs = reinterpret_cast(hunk_base + hunk_low_used); cs = cache_head.next; do { if (!nobottom || cs != cache_head.next) { - if ((byte*)cs - (byte*)new_cs >= size) { // found space + if (reinterpret_cast(cs) - reinterpret_cast(new_cs) >= size) { // found space memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; @@ -680,12 +676,12 @@ cache_system_t* Cache_TryAlloc(int size, qboolean nobottom) } // continue looking - new_cs = (cache_system_t*)((byte*)cs + cs->size); + new_cs = reinterpret_cast(reinterpret_cast(cs) + cs->size); // FIX: If the block we just checked was below the new Hunk boundary, // clamp new_cs back up to the Hunk boundary to prevent overlapping! - if ((byte*)new_cs < hunk_base + hunk_low_used) { - new_cs = (cache_system_t*)(hunk_base + hunk_low_used); + if (reinterpret_cast(new_cs) < hunk_base + hunk_low_used) { + new_cs = reinterpret_cast(hunk_base + hunk_low_used); } cs = cs->next; @@ -693,7 +689,7 @@ cache_system_t* Cache_TryAlloc(int size, qboolean nobottom) } while (cs != &cache_head); // try to allocate one at the very end - if (hunk_base + hunk_size - hunk_high_used - (byte*)new_cs >= size) { + if (hunk_base + hunk_size - hunk_high_used - reinterpret_cast(new_cs) >= size) { memset(new_cs, 0, sizeof(*new_cs)); new_cs->size = size; @@ -766,7 +762,7 @@ void Cache_Free(cache_user_t* c) Sys_Error("Cache_Free: not allocated"); } - cs = ((cache_system_t*)c->data) - 1; + cs = reinterpret_cast(c->data) - 1; cs->prev->next = cs->next; cs->next->prev = cs->prev; @@ -790,7 +786,7 @@ void* Cache_Check(cache_user_t* c) return NULL; } - cs = ((cache_system_t*)c->data) - 1; + cs = reinterpret_cast(c->data) - 1; // move to head of LRU Cache_UnlinkLRU(cs); @@ -806,8 +802,6 @@ Cache_Alloc */ void* Cache_Alloc(cache_user_t* c, int size, const char* name) { - cache_system_t* cs; - if (c->data) { Sys_Error("Cache_Alloc: allready allocated"); } @@ -820,9 +814,9 @@ void* Cache_Alloc(cache_user_t* c, int size, const char* name) // find memory for it while (1) { - cs = Cache_TryAlloc(size, false); + cache_system_t* cs = Cache_TryAlloc(size, false); if (cs) { - strncpy_s(cs->name, sizeof(cs->name), name, sizeof(cs->name) - 1); + strlcpy(cs->name, name, sizeof(cs->name) - 1); c->data = (void*)(cs + 1); cs->user = c; break; @@ -852,7 +846,7 @@ void Memory_Init(void* buf, int size) int p; int zonesize = DYNAMIC_SIZE; - hunk_base = (byte*)buf; // C++ Fix: Explicitly cast void* to byte* + hunk_base = static_cast(buf); // C++ Fix: Explicitly cast void* to byte* hunk_size = size; hunk_low_used = 0; hunk_high_used = 0; @@ -868,7 +862,7 @@ void Memory_Init(void* buf, int size) } // C++ Fix: Explicitly cast void* returned from Hunk_AllocName - mainzone = (memzone_t*)Hunk_Alloc(zonesize, "zone"); + mainzone = static_cast(Hunk_Alloc(zonesize, "zone")); Z_ClearZone(mainzone, zonesize); }