diff --git a/StepmaniaCore.cmake b/StepmaniaCore.cmake index 5b0389d486..e656e6350e 100644 --- a/StepmaniaCore.cmake +++ b/StepmaniaCore.cmake @@ -155,14 +155,6 @@ if(WIN32) endif() endif() -include(TestBigEndian) -test_big_endian(BIGENDIAN) -if(${BIGENDIAN}) - set(ENDIAN_BIG 1) -else() - set(ENDIAN_LITTLE 1) -endif() - check_compile_features("${SM_CMAKE_DIR}/TestCode" "${SM_CMAKE_DIR}/TestCode/test_external.c" "Checking for external name shortening requirements" diff --git a/src/Actor.cpp b/src/Actor.cpp index 77d103287e..6f3fc2fa22 100644 --- a/src/Actor.cpp +++ b/src/Actor.cpp @@ -1118,7 +1118,7 @@ void Actor::SetEffectClockString( const RString &s ) } else { - this->SetEffectClock(static_cast(cl + CLOCK_LIGHT_1)); + this->SetEffectClock(static_cast(Enum::to_integral(cl) + CLOCK_LIGHT_1)); } } } diff --git a/src/Actor.h b/src/Actor.h index 918d25c8da..5fdfe69002 100644 --- a/src/Actor.h +++ b/src/Actor.h @@ -477,7 +477,7 @@ public: float GetAux() const { return m_current.aux; } virtual void BeginTweening( float time, ITween *pInterp ); - void BeginTweening( float time, TweenType tt = TWEEN_LINEAR ); + virtual void BeginTweening( float time, TweenType tt = TWEEN_LINEAR ); virtual void StopTweening(); void Sleep( float time ); void QueueCommand( const RString& sCommandName ); diff --git a/src/ActorMultiVertex.cpp b/src/ActorMultiVertex.cpp index 45bcf1c392..2fc005a134 100644 --- a/src/ActorMultiVertex.cpp +++ b/src/ActorMultiVertex.cpp @@ -401,9 +401,9 @@ CubicSplineN* ActorMultiVertex::GetSpline(size_t i) return &(_splines[i]); } -void ActorMultiVertex::SetState(size_t i) +void ActorMultiVertex::SetState(int i) { - ASSERT(i < _states.size()); + ASSERT(i >= 0 and static_cast(i) < _states.size()); _cur_state= i; _secs_into_state= 0.0f; } @@ -1002,7 +1002,7 @@ public: static size_t ValidStateIndex(T* p, lua_State *L, int pos) { int index= IArg(pos)-1; - if(index < 0 || static_cast(index) >= p->GetNumStates()) + if(index < 0 || index >= p->GetNumStates()) { luaL_error(L, "Invalid state index %d.", index+1); } diff --git a/src/ActorMultiVertex.h b/src/ActorMultiVertex.h index 42c8db9523..0e8967df80 100644 --- a/src/ActorMultiVertex.h +++ b/src/ActorMultiVertex.h @@ -130,7 +130,7 @@ public: { ASSERT(i < _states.size()); _states[i]= s; } void SetStateProperties(const std::vector& new_states) { _states= new_states; SetState(0); } - void SetState(size_t i); + void SetState(int i); void SetAllStateDelays(float delay); float GetAnimationLengthSeconds() const; void SetSecondsIntoAnimation(float seconds); diff --git a/src/ArrowEffects.cpp b/src/ArrowEffects.cpp index 2dfb3fe937..9c725e9e01 100644 --- a/src/ArrowEffects.cpp +++ b/src/ArrowEffects.cpp @@ -319,9 +319,8 @@ void ArrowEffects::Update() const Style::ColumnInfo* pCols = pStyle->m_ColumnInfo[pn]; const SongPosition &position = GAMESTATE->m_bIsUsingStepTiming ? GAMESTATE->m_pPlayerState[pn]->m_Position : GAMESTATE->m_Position; - const float field_zoom= GAMESTATE->m_pPlayerState[pn]->m_NotefieldZoom; - const float* effects= GAMESTATE->m_pPlayerState[pn]->m_PlayerOptions.GetCurrent().m_fEffects; - const float* accels= GAMESTATE->m_pPlayerState[pn]->m_PlayerOptions.GetCurrent().m_fAccels; + const auto& effects= GAMESTATE->m_pPlayerState[pn]->m_PlayerOptions.GetCurrent().m_fEffects; + const auto& accels= GAMESTATE->m_pPlayerState[pn]->m_PlayerOptions.GetCurrent().m_fAccels; PerPlayerData &data = g_EffectData[pn]; @@ -515,8 +514,8 @@ float ArrowEffects::GetYOffset( const PlayerState* pPlayerState, int iCol, float return fYOffset * fScrollSpeed; } - const float* fAccels = curr_options->m_fAccels; - const float* fEffects = curr_options->m_fEffects; + const auto& fAccels = curr_options->m_fAccels; + const auto& fEffects = curr_options->m_fEffects; // TODO: Don't index by PlayerNumber. PerPlayerData &data = g_EffectData[pPlayerState->m_PlayerNumber]; @@ -637,7 +636,7 @@ float ArrowEffects::GetYPos( const PlayerState* pPlayerState, int iCol, float fY // TODO: Don't index by PlayerNumber. const Style* pStyle = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber); const Style::ColumnInfo* pCols = pStyle->m_ColumnInfo[pPlayerState->m_PlayerNumber]; - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; // Doing the math with a precalculated result of 0 should be faster than // checking whether tipsy is on. -Kyz @@ -670,7 +669,7 @@ float ArrowEffects::GetYOffsetFromYPos(int iCol, float YPos, float fYReverseOffs { float f = YPos; - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; // Doing the math with a precalculated result of 0 should be faster than // checking whether tipsy is on. -Kyz // TODO: Don't index by PlayerNumber. @@ -695,7 +694,7 @@ float ArrowEffects::GetXPos( const PlayerState* pPlayerState, int iColNum, float float fPixelOffsetFromCenter = 0; // fill this in below const Style* pStyle = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber); - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; // TODO: Don't index by PlayerNumber. const Style::ColumnInfo* pCols = pStyle->m_ColumnInfo[pPlayerState->m_PlayerNumber]; @@ -865,7 +864,7 @@ float ArrowEffects::GetXPos( const PlayerState* pPlayerState, int iColNum, float float ArrowEffects::GetRotationX(const PlayerState* pPlayerState, float fYOffset, bool bIsHoldCap, int iCol) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( fEffects[PlayerOptions::EFFECT_CONFUSION_X] != 0 || fEffects[PlayerOptions::EFFECT_CONFUSION_X_OFFSET] != 0 || curr_options->m_fConfusionX[iCol] != 0 @@ -880,7 +879,7 @@ float ArrowEffects::GetRotationX(const PlayerState* pPlayerState, float fYOffset float ArrowEffects::GetRotationY(const PlayerState* pPlayerState, float fYOffset, int iCol) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( fEffects[PlayerOptions::EFFECT_CONFUSION_Y] != 0 || fEffects[PlayerOptions::EFFECT_CONFUSION_Y_OFFSET] != 0 || curr_options->m_fConfusionY[iCol] != 0 @@ -895,7 +894,7 @@ float ArrowEffects::GetRotationY(const PlayerState* pPlayerState, float fYOffset float ArrowEffects::GetRotationZ( const PlayerState* pPlayerState, float fNoteBeat, bool bIsHoldHead, int iCol ) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( fEffects[PlayerOptions::EFFECT_CONFUSION] != 0 || fEffects[PlayerOptions::EFFECT_CONFUSION_OFFSET] != 0 || curr_options->m_fConfusionZ[iCol] != 0 @@ -917,7 +916,7 @@ float ArrowEffects::GetRotationZ( const PlayerState* pPlayerState, float fNoteBe float ArrowEffects::ReceptorGetRotationZ( const PlayerState* pPlayerState, int iCol ) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( curr_options->m_fConfusionZ[iCol] != 0 ) @@ -940,7 +939,7 @@ float ArrowEffects::ReceptorGetRotationZ( const PlayerState* pPlayerState, int i float ArrowEffects::ReceptorGetRotationX( const PlayerState* pPlayerState, int iCol ) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( curr_options->m_fConfusionX[iCol] != 0 ) @@ -963,7 +962,7 @@ float ArrowEffects::ReceptorGetRotationX( const PlayerState* pPlayerState, int i float ArrowEffects::ReceptorGetRotationY( const PlayerState* pPlayerState, int iCol ) { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; float fRotation = 0; if( curr_options->m_fConfusionY[iCol] != 0 ) @@ -986,7 +985,7 @@ float ArrowEffects::ReceptorGetRotationY( const PlayerState* pPlayerState, int i float ArrowEffects::GetMoveX(int iCol) { - const float* fMoves = curr_options->m_fMovesX; + const auto& fMoves = curr_options->m_fMovesX; float f = 0; if( fMoves[iCol] != 0 ) f += ARROW_SIZE * fMoves[iCol]; @@ -995,7 +994,7 @@ float ArrowEffects::GetMoveX(int iCol) float ArrowEffects::GetMoveY(int iCol) { - const float* fMoves = curr_options->m_fMovesY; + const auto& fMoves = curr_options->m_fMovesY; float f = 0; if( fMoves[iCol] != 0 ) f += ARROW_SIZE * fMoves[iCol]; @@ -1004,7 +1003,7 @@ float ArrowEffects::GetMoveY(int iCol) float ArrowEffects::GetMoveZ(int iCol) { - const float* fMoves = curr_options->m_fMovesZ; + const auto& fMoves = curr_options->m_fMovesZ; float f = 0; if( fMoves[iCol] != 0 ) f += ARROW_SIZE * fMoves[iCol]; @@ -1025,7 +1024,7 @@ static float GetCenterLine() static float GetHiddenSudden() { - const float* fAppearances = curr_options->m_fAppearances; + const auto& fAppearances = curr_options->m_fAppearances; return fAppearances[PlayerOptions::APPEARANCE_HIDDEN] * fAppearances[PlayerOptions::APPEARANCE_SUDDEN]; } @@ -1085,7 +1084,7 @@ float ArrowGetPercentVisible(float fYPosWithoutReverse, int iCol, float fYOffset if( fYPos < 0 && curr_options->m_bStealthPastReceptors == false) // past Gray Arrows return 1; // totally visible - const float* fAppearances = curr_options->m_fAppearances; + const auto& fAppearances = curr_options->m_fAppearances; float fVisibleAdjust = 0; @@ -1174,7 +1173,7 @@ float ArrowEffects::GetBrightness( const PlayerState* pPlayerState, float fNoteB float ArrowEffects::GetZPos( const PlayerState* pPlayerState, int iCol, float fYOffset) { float fZPos=0; - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; const Style* pStyle = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber); // TODO: Don't index by PlayerNumber. @@ -1296,7 +1295,7 @@ float ArrowEffects::GetZPos( const PlayerState* pPlayerState, int iCol, float fY bool ArrowEffects::NeedZBuffer() { - const float* fEffects = curr_options->m_fEffects; + const auto& fEffects = curr_options->m_fEffects; // We also need to use the Z buffer if twirl is in play, because of // hold modulation. -vyhd (OpenITG r623) if( fEffects[PlayerOptions::EFFECT_BUMPY] != 0 || diff --git a/src/Background.cpp b/src/Background.cpp index 79afcbf6c0..6b53695651 100644 --- a/src/Background.cpp +++ b/src/Background.cpp @@ -669,11 +669,11 @@ void BackgroundImpl::LoadFromSong( const Song* pSong ) // Look for the random file marker, and replace the segment with LoadFromRandom. for( unsigned i=0; iGetLastBeat(); if( i+1 < mainlayer.m_aBGChanges.size() ) fEndBeat = mainlayer.m_aBGChanges[i+1].m_fStartBeat; @@ -681,7 +681,7 @@ void BackgroundImpl::LoadFromSong( const Song* pSong ) mainlayer.m_aBGChanges.erase( mainlayer.m_aBGChanges.begin()+i ); --i; - LoadFromRandom( fStartBeat, fEndBeat, change ); + LoadFromRandom( fStartBeat, fEndBeat, bgChange); } // At this point, we shouldn't have any BGChanges to "". "" is an invalid name. diff --git a/src/BitmapText.cpp b/src/BitmapText.cpp index fc629daa4d..ccac111d11 100644 --- a/src/BitmapText.cpp +++ b/src/BitmapText.cpp @@ -647,7 +647,7 @@ void BitmapText::CropLineToWidth(size_t l, int width) { int used_width= width; std::wstring& line= m_wTextLines[l]; - int fit= m_pFont->GetGlyphsThatFit(line, &used_width); + const auto fit= m_pFont->GetGlyphsThatFit(line, &used_width); if(fit < line.size()) { line.erase(line.begin()+fit, line.end()); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 124a629ae9..145565f638 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -118,6 +118,25 @@ target_compile_definitions("${SM_EXE_NAME}" PRIVATE $<$:MINSI target_compile_definitions("${SM_EXE_NAME}" PRIVATE $<$:RELWITHDEBINFO>) +# For Apple Clang, CMAKE__COMPILER_ID will be set to AppleClang instead of Clang. +if (POLICY CMP0025) + cmake_policy(SET CMP0025 NEW) +endif() + +# COMPILE_WARNING_AS_ERROR is only supported starting with cmake 3.24. +# Continue using -Werror and /WX to treat warnings as errors until cmake >= 3.24 is required. +set_property(TARGET "${SM_EXE_NAME}" PROPERTY COMPILE_WARNING_AS_ERROR ON) +target_compile_options("${SM_EXE_NAME}" PRIVATE + $<$: + -Werror -Wall -Wextra -Wno-unused -Wno-unused-parameter -Wno-unknown-pragmas> + $<$: + -Werror -Wall -Wextra -Wno-unused -Wno-unused-parameter -Wno-unknown-pragmas -Wno-undefined-var-template> + $<$: + -Werror -Wall -Wextra -Wno-unused -Wno-unused-parameter -Wno-unknown-pragmas -Wno-undefined-var-template -Wno-deprecated-declarations -Wno-unused-command-line-argument> + $<$: + /WX /W4 /wd4100 /wd4189 /wd4244 /wd4267 /wd4702> +) + set(SM_COMPILE_FLAGS "") if(WITH_SSE2) @@ -176,7 +195,10 @@ if(WIN32) COMMENT "Generating file to allow for easier stack traces.") endif() elseif(APPLE) + # TODO should we set CRASH_HANDLER and other things like LINUX does below? Why is that logic specfic to LINUX? target_compile_definitions("${SM_EXE_NAME}" PRIVATE BACKTRACE_METHOD_X86_DARWIN) + target_compile_definitions("${SM_EXE_NAME}" PRIVATE BACKTRACE_LOOKUP_METHOD_TEXT="dladdr") + target_compile_definitions("${SM_EXE_NAME}" PRIVATE BACKTRACE_LOOKUP_METHOD_DLADDR) target_compile_definitions("${SM_EXE_NAME}" PRIVATE MACOSX) set_target_properties( "${SM_EXE_NAME}" diff --git a/src/CharacterManager.cpp b/src/CharacterManager.cpp index 655fc542c1..0eca050bf5 100644 --- a/src/CharacterManager.cpp +++ b/src/CharacterManager.cpp @@ -90,7 +90,6 @@ Character* CharacterManager::GetDefaultCharacter() /* We always have the default character. */ FAIL_M("There must be a default character available!"); - return nullptr; } void CharacterManager::DemandGraphics() diff --git a/src/Course.cpp b/src/Course.cpp index 1d83b27a7d..ba367f78a3 100644 --- a/src/Course.cpp +++ b/src/Course.cpp @@ -657,7 +657,7 @@ void Course::GetTrailUnsortedEndless( const std::vector &entries, T typedef std::vector StepsVector; std::set alreadySelected; - Song* lastSongSelected; + Song* lastSongSelected = nullptr; std::vector vSongAndSteps; for (auto e = entries.begin(); e != entries.end(); ++e) { @@ -743,7 +743,7 @@ void Course::GetTrailUnsortedEndless( const std::vector &entries, T ASSERT(e->iChooseIndex >= 0); // If we're trying to pick BEST100 when only 99 songs exist, // we have a problem, so bail out - if (e->iChooseIndex >= vpSongs.size()) { + if (static_cast(e->iChooseIndex) >= vpSongs.size()) { continue; } @@ -1029,7 +1029,6 @@ RageColor Course::GetColor() const else return SORT_LEVEL4_COLOR; default: FAIL_M( ssprintf("Invalid course sort %d.", int(PREFSMAN->m_CourseSortOrder)) ); - return RageColor(1,1,1,1); // white; should never reach here } } diff --git a/src/Course.h b/src/Course.h index 7f8246d5eb..67841b3f31 100644 --- a/src/Course.h +++ b/src/Course.h @@ -17,8 +17,16 @@ struct Game; const int MAX_EDIT_COURSE_TITLE_LENGTH = 16; -inline PlayMode CourseTypeToPlayMode( CourseType ct ) { return (PlayMode)(PLAY_MODE_NONSTOP+ct); } -inline CourseType PlayModeToCourseType( PlayMode pm ) { return (CourseType)(pm-PLAY_MODE_NONSTOP); } +inline PlayMode CourseTypeToPlayMode( CourseType ct ) { + switch (ct) { + case COURSE_TYPE_NONSTOP: return PLAY_MODE_NONSTOP; + case COURSE_TYPE_ONI: return PLAY_MODE_ONI; + case COURSE_TYPE_ENDLESS: return PLAY_MODE_ENDLESS; + case COURSE_TYPE_SURVIVAL: return PLAY_MODE_BATTLE; + default: break; + } + return PlayMode_Invalid; +} enum SongSort { diff --git a/src/CreateZip.cpp b/src/CreateZip.cpp index 5ad22d36f4..6c2d1734fd 100644 --- a/src/CreateZip.cpp +++ b/src/CreateZip.cpp @@ -543,29 +543,25 @@ ulg crc32(ulg crc, const uch *buf, size_t len) class TZip { public: - TZip() : pfout(nullptr),ooffset(0),oerr(false),writ(0),hasputcen(false),zfis(0),hfin(0) - { - } - ~TZip() - { - } + TZip() = default; + ~TZip() = default; // These variables say about the file we're writing into // We can write to pipe, file-by-handle, file-by-name, memory-to-memmapfile - RageFile *pfout; // if valid, we'll write here (for files or pipes) - unsigned ooffset; // for pfout, this is where the pointer was initially - ZRESULT oerr; // did a write operation give rise to an error? - unsigned writ; // how have we written. This is maintained by Add, not write(), to avoid confusion over seeks - unsigned int opos; // current pos in the mmap - unsigned int mapsize; // the size of the map we created - bool hasputcen; // have we yet placed the central directory? + RageFile *pfout{nullptr}; // if valid, we'll write here (for files or pipes) + unsigned ooffset{0}; // for pfout, this is where the pointer was initially + ZRESULT oerr{false}; // did a write operation give rise to an error? + unsigned writ{0}; // how have we written. This is maintained by Add, not write(), to avoid confusion over seeks + unsigned int opos{0}; // current pos in the mmap + unsigned int mapsize{0}; // the size of the map we created + bool hasputcen{false}; // have we yet placed the central directory? // - TZipFileInfo *zfis; // each file gets added onto this list, for writing the table at the end + TZipFileInfo *zfis{nullptr}; // each file gets added onto this list, for writing the table at the end ZRESULT Start(RageFile *f); static unsigned sflush(void *param,const char *buf, unsigned *size); static unsigned swrite(void *param,const char *buf, unsigned size); - unsigned int write(const char *buf,unsigned int size); + unsigned int write(const char *srcbuf,unsigned int size); bool oseek(unsigned int pos); ZRESULT Close(); @@ -575,7 +571,7 @@ public: ulg attr; iztimes times; ulg timestamp; // all open_* methods set these long isize,ired; // size is not set until close() on pips ulg crc; // crc is not set until close(). iwrit is cumulative - RageFile *hfin; // for input files and pipes + RageFile *hfin{nullptr}; // for input files and pipes const char *bufin; unsigned int lenin,posin; // for memory // and a variable for what we've done with the input: (i.e. compressed it!) ulg csize; // compressed size, set by the compression routines @@ -586,7 +582,7 @@ public: ZRESULT open_file(const TCHAR *fn); ZRESULT open_dir(); ZRESULT set_times(); - unsigned read(char *buf, unsigned size); + unsigned read(char *srcbuf, unsigned size); ZRESULT iclose(); ZRESULT ideflate(TZipFileInfo *zfi); @@ -628,13 +624,11 @@ unsigned TZip::swrite(void *param,const char *buf, unsigned size) TZip *zip=(TZip*)param; return zip->write(buf,size); } -unsigned int TZip::write(const char *buf,unsigned int size) +unsigned int TZip::write(const char *srcbuf,unsigned int size) { - const char *srcbuf=buf; if (pfout != nullptr) { - unsigned long writ = pfout->Write( srcbuf, size ); - return writ; + return pfout->Write( srcbuf, size ); } oerr=ZR_NOTINITED; return 0; @@ -724,7 +718,7 @@ ZRESULT TZip::set_times() return ZR_OK; } -unsigned TZip::read(char *buf, unsigned size) +unsigned TZip::read(char *srcbuf, unsigned size) { if (bufin!=0) { @@ -732,19 +726,19 @@ unsigned TZip::read(char *buf, unsigned size) ulg red = lenin-posin; if (red>size) red=size; - memcpy(buf, bufin+posin, red); + memcpy(srcbuf, bufin+posin, red); posin += red; ired += red; - crc = crc32(crc, (uch*)buf, red); + crc = crc32(crc, (uch*)srcbuf, red); return red; } else if (hfin!=0) { - int red = hfin->Read(buf,size); + int red = hfin->Read(srcbuf,size); if (red <= 0) return 0; ired += red; - crc = crc32(crc, (uch*)buf, red); + crc = crc32(crc, (uch*)srcbuf, red); return red; } else diff --git a/src/CryptHelpers.h b/src/CryptHelpers.h index c09daf8824..8628d21872 100644 --- a/src/CryptHelpers.h +++ b/src/CryptHelpers.h @@ -3,7 +3,11 @@ #if !defined(DISABLE_CRYPTO) +// tomcrypt_cfg.h redefines malloc, realloc, calloc +#pragma warning( push ) +#pragma warning( disable : 4565 ) #include +#pragma warning ( pop ) class PRNGWrapper { diff --git a/src/CryptManager.cpp b/src/CryptManager.cpp index 63072fb674..5e6e5ab8a1 100644 --- a/src/CryptManager.cpp +++ b/src/CryptManager.cpp @@ -1,6 +1,10 @@ #include "global.h" +// tomcrypt_cfg.h redefines malloc, realloc, calloc +#pragma warning( push ) +#pragma warning( disable : 4565 ) #include +#pragma warning ( pop ) #include "CryptManager.h" #include "RageUtil.h" diff --git a/src/CubicSpline.cpp b/src/CubicSpline.cpp index fe66fa8ea2..d2613faa32 100644 --- a/src/CubicSpline.cpp +++ b/src/CubicSpline.cpp @@ -226,9 +226,9 @@ float loop_space_difference(float a, float b, float spatial_extent) if(spatial_extent == 0.0f) { return norm_diff; } const float plus_diff= a - (b + spatial_extent); const float minus_diff= a - (b - spatial_extent); - const float abs_norm_diff= abs(norm_diff); - const float abs_plus_diff= abs(plus_diff); - const float abs_minus_diff= abs(minus_diff); + const float abs_norm_diff= std::abs(norm_diff); + const float abs_plus_diff= std::abs(plus_diff); + const float abs_minus_diff= std::abs(minus_diff); if(abs_norm_diff < abs_plus_diff) { if(abs_norm_diff < abs_minus_diff) diff --git a/src/Difficulty.h b/src/Difficulty.h index 2d48263a21..868f9aab99 100644 --- a/src/Difficulty.h +++ b/src/Difficulty.h @@ -7,7 +7,7 @@ class Steps; class Trail; // Player number stuff -enum Difficulty +enum Difficulty { Difficulty_Beginner, Difficulty_Easy, diff --git a/src/DifficultyList.cpp b/src/DifficultyList.cpp index e2b2923636..44b7186371 100644 --- a/src/DifficultyList.cpp +++ b/src/DifficultyList.cpp @@ -14,7 +14,7 @@ /** @brief Specifies the max number of charts available for a song. * * This includes autogenned charts. */ -#define MAX_METERS (NUM_Difficulty * NUM_StepsType) + MAX_EDITS_PER_SONG +inline constexpr auto MAX_METERS = (Enum::to_integral(NUM_Difficulty) * Enum::to_integral(NUM_StepsType)) + MAX_EDITS_PER_SONG; REGISTER_ACTOR_CLASS( StepsDisplayList ); @@ -24,8 +24,8 @@ StepsDisplayList::StepsDisplayList() FOREACH_ENUM( PlayerNumber, pn ) { - SubscribeToMessage( (MessageID)(Message_CurrentStepsP1Changed+pn) ); - SubscribeToMessage( (MessageID)(Message_CurrentTrailP1Changed+pn) ); + SubscribeToMessage( (MessageID)(Message_CurrentStepsP1Changed+Enum::to_integral(pn)) ); + SubscribeToMessage( (MessageID)(Message_CurrentTrailP1Changed+Enum::to_integral(pn)) ); } } @@ -213,13 +213,13 @@ void StepsDisplayList::UpdatePositions() void StepsDisplayList::PositionItems() { - for( int i = 0; i < MAX_METERS; ++i ) + for( size_t i = 0; i < MAX_METERS; ++i ) { - bool bUnused = ( i >= (int)m_Rows.size() ); + bool bUnused = ( i >= m_Rows.size() ); m_Lines[i].m_Meter.SetVisible( !bUnused ); } - for( int m = 0; m < (int)m_Rows.size(); ++m ) + for( size_t m = 0; m < m_Rows.size(); ++m ) { Row &row = m_Rows[m]; bool bHidden = row.m_bHidden; @@ -237,10 +237,10 @@ void StepsDisplayList::PositionItems() m_Lines[m].m_Meter.SetY( row.m_fY ); } - for( int m=0; m < MAX_METERS; ++m ) + for( size_t m=0; m < MAX_METERS; ++m ) { bool bHidden = true; - if( m_bShown && m < (int)m_Rows.size() ) + if( m_bShown && m < m_Rows.size() ) bHidden = m_Rows[m].m_bHidden; float fDiffuseAlpha = bHidden?0.0f:1.0f; @@ -303,7 +303,7 @@ void StepsDisplayList::SetFromGameState() UpdatePositions(); PositionItems(); - for( int m = 0; m < MAX_METERS; ++m ) + for( size_t m = 0; m < MAX_METERS; ++m ) m_Lines[m].m_Meter.FinishTweening(); } @@ -323,7 +323,7 @@ void StepsDisplayList::TweenOnScreen() FOREACH_HumanPlayer( pn ) ON_COMMAND( m_Cursors[pn] ); - for( int m = 0; m < MAX_METERS; ++m ) + for( size_t m = 0; m < MAX_METERS; ++m ) ON_COMMAND( m_Lines[m].m_Meter ); this->SetHibernate( 0.5f ); @@ -373,8 +373,8 @@ void StepsDisplayList::HandleMessage( const Message &msg ) { FOREACH_ENUM( PlayerNumber, pn ) { - if( msg.GetName() == MessageIDToString((MessageID)(Message_CurrentStepsP1Changed+pn)) || - msg.GetName() == MessageIDToString((MessageID)(Message_CurrentTrailP1Changed+pn)) ) + if( msg.GetName() == MessageIDToString((MessageID)(Message_CurrentStepsP1Changed+Enum::to_integral(pn))) || + msg.GetName() == MessageIDToString((MessageID)(Message_CurrentTrailP1Changed+Enum::to_integral(pn))) ) SetFromGameState(); } diff --git a/src/DisplaySpec.h b/src/DisplaySpec.h index 546988cded..e434c0cbf8 100644 --- a/src/DisplaySpec.h +++ b/src/DisplaySpec.h @@ -89,14 +89,15 @@ public: } // Create a specification for a display supporting a single (and currently active) mode - DisplaySpec(std::string id, std::string name, DisplayMode mode) : m_sId( id ), m_sName( name ), m_bIsVirtual( false ), - m_bCurModeActive( true ), m_CurMode( mode ) + DisplaySpec(std::string id, std::string name, DisplayMode mode) : m_sId( id ), m_sName( name ), + m_bCurModeActive( true ), m_CurMode( mode ), m_bIsVirtual( false ) { m_sModes.insert( mode ); m_rectBounds = RectI( 0, 0, mode.width, mode.height ); } DisplaySpec( const DisplaySpec &other ) = default; + DisplaySpec& operator=(const DisplaySpec& other) = default; std::string name() const { diff --git a/src/EnumHelper.h b/src/EnumHelper.h index 222cf76ec7..6de115163a 100644 --- a/src/EnumHelper.h +++ b/src/EnumHelper.h @@ -68,6 +68,12 @@ namespace Enum } void SetMetatable( lua_State *L, LuaReference &EnumTable, LuaReference &EnumIndexTable, const char *szName ); + + template + constexpr auto to_integral(E e) + { + return static_cast::type>(e); + } }; const RString &EnumToString( int iVal, int iMax, const char **szNameArray, std::unique_ptr *pNameCache ); // XToString helper diff --git a/src/Font.cpp b/src/Font.cpp index 279ed18e7b..316301360b 100644 --- a/src/Font.cpp +++ b/src/Font.cpp @@ -254,7 +254,7 @@ int Font::GetLineHeightInSourcePixels( const std::wstring &szLine ) const } // width is a pointer so that we can return the used width through it. -int Font::GetGlyphsThatFit(const std::wstring& line, int* width) const +size_t Font::GetGlyphsThatFit(const std::wstring& line, int* width) const { if(*width == 0) { @@ -262,7 +262,7 @@ int Font::GetGlyphsThatFit(const std::wstring& line, int* width) const return line.size(); } int curr_width= 0; - unsigned int i= 0; + size_t i= 0; for(i= 0; i < line.size() && curr_width < *width; ++i) { curr_width+= GetGlyph(line[i]).m_iHadvance; @@ -507,7 +507,7 @@ void Font::LoadFontPageSettings( FontPageSettings &cfg, IniFile &ini, const RStr wchar_t c; if( sCodepoint.substr(0, 2) == "U+" && IsHexVal(sCodepoint.substr(2)) ) - sscanf( sCodepoint.substr(2).c_str(), "%x", &c ); + sscanf( sCodepoint.substr(2).c_str(), "%lc", &c ); else if( sCodepoint.size() > 0 && utf8_get_char_len(sCodepoint[0]) == int(sCodepoint.size()) ) { @@ -558,11 +558,11 @@ void Font::LoadFontPageSettings( FontPageSettings &cfg, IniFile &ini, const RStr } // We must have either 1 match (just the codeset) or 4 (the whole thing). int count = -1; - int first = 0; + unsigned int first = 0; if( !asMatches[2].empty() ) { sscanf( asMatches[2].c_str(), "%x", &first ); - int last; + unsigned int last; sscanf( asMatches[3].c_str(), "%x", &last ); if(last < first) { diff --git a/src/Font.h b/src/Font.h index 462ba73031..bdb79dd4d5 100644 --- a/src/Font.h +++ b/src/Font.h @@ -154,7 +154,7 @@ public: int GetLineWidthInSourcePixels( const std::wstring &szLine ) const; int GetLineHeightInSourcePixels( const std::wstring &szLine ) const; - int GetGlyphsThatFit(const std::wstring& line, int* width) const; + size_t GetGlyphsThatFit(const std::wstring& line, int* width) const; bool FontCompleteForString( const std::wstring &str ) const; diff --git a/src/FontManager.cpp b/src/FontManager.cpp index 8504b2d7b5..c2b48e0bc5 100644 --- a/src/FontManager.cpp +++ b/src/FontManager.cpp @@ -81,7 +81,7 @@ void FontManager::UnloadFont( Font *fp ) return; } - FAIL_M( ssprintf("Unloaded an unknown font (%p)", fp) ); + FAIL_M( ssprintf("Unloaded an unknown font (%p)", static_cast(fp)) ); } /* diff --git a/src/GameCommand.cpp b/src/GameCommand.cpp index aadd3253b2..09205ff431 100644 --- a/src/GameCommand.cpp +++ b/src/GameCommand.cpp @@ -543,8 +543,10 @@ static bool AreStyleAndPlayModeCompatible( const Style *style, PlayMode pm ) if( style->m_StyleType==StyleType_OnePlayerTwoSides || style->m_StyleType==StyleType_TwoPlayersSharedSides ) return false; - default: return true; + default: break; } + + return true; } bool GameCommand::IsPlayable( RString *why ) const diff --git a/src/GameManager.cpp b/src/GameManager.cpp index 8fa5b8c43f..ba24dee971 100644 --- a/src/GameManager.cpp +++ b/src/GameManager.cpp @@ -98,7 +98,7 @@ static const StepsTypeInfo g_StepsTypeInfos[] = { { "kickbox-insect", 6, true, StepsTypeCategory_Single }, { "kickbox-arachnid", 8, true, StepsTypeCategory_Single }, }; - +static_assert( ARRAYLEN(g_StepsTypeInfos) == NUM_StepsType, "ARRAYLEN(g_StepsTypeInfos) != NUM_StepsType" ); // Important: Every game must define the buttons: "Start", "Back", "MenuLeft", "Operator" and "MenuRight" static const AutoMappings g_AutoKeyMappings_Dance = AutoMappings ( @@ -3441,7 +3441,6 @@ bool GameManager::IsGameEnabled( const Game *pGame ) const StepsTypeInfo &GameManager::GetStepsTypeInfo( StepsType st ) { - ASSERT( ARRAYLEN(g_StepsTypeInfos) == NUM_StepsType ); ASSERT_M( st < NUM_StepsType, ssprintf("StepsType %d < NUM_StepsType (%d)", st, NUM_StepsType) ); return g_StepsTypeInfos[st]; } diff --git a/src/GameState.cpp b/src/GameState.cpp index 5f27a2809d..14e5b5c26c 100644 --- a/src/GameState.cpp +++ b/src/GameState.cpp @@ -1153,7 +1153,7 @@ void GameState::Update( float fDelta ) if( !m_bGoalComplete[p] && IsGoalComplete(p) ) { m_bGoalComplete[p] = true; - MESSAGEMAN->Broadcast( (MessageID)(Message_GoalCompleteP1+p) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_GoalCompleteP1+Enum::to_integral(p)) ); } } @@ -1844,7 +1844,7 @@ StageResult GameState::GetStageResult( PlayerNumber pn ) const { case PLAYER_1: return (m_fTugLifePercentP1>=0.5f)?RESULT_WIN:RESULT_LOSE; case PLAYER_2: return (m_fTugLifePercentP1<0.5f)?RESULT_WIN:RESULT_LOSE; - default: FAIL_M("Invalid player for battle! Aborting..."); return RESULT_LOSE; + default: FAIL_M("Invalid player for battle! Aborting..."); } default: break; } diff --git a/src/Grade.cpp b/src/Grade.cpp index 82a1de93be..5a58d771cb 100644 --- a/src/Grade.cpp +++ b/src/Grade.cpp @@ -53,7 +53,7 @@ Grade GradeToOldGrade( Grade g ) // There used to be 7 grades (plus fail) but grades can now be defined by themes. // So we need to re-scale the grade bands based on how many actual grades the theme defines. if( g < NUM_GRADE_TIERS_USED ) - g = (Grade)std::lround((double)g * Grade_Tier07 / (NUM_GRADE_TIERS_USED - 1)); + g = (Grade)std::lround((double)g * Enum::to_integral(Grade_Tier07) / (NUM_GRADE_TIERS_USED - 1)); return g; } diff --git a/src/IniFile.cpp b/src/IniFile.cpp index 27ec5063a1..a12e58bcdf 100644 --- a/src/IniFile.cpp +++ b/src/IniFile.cpp @@ -88,6 +88,7 @@ bool IniFile::ReadFile( RageFileBasic &f ) } break; } + [[fallthrough]]; default: keyvalue: if(keychild == nullptr) diff --git a/src/InputFilter.cpp b/src/InputFilter.cpp index 4dd0c10dab..4515a8b468 100644 --- a/src/InputFilter.cpp +++ b/src/InputFilter.cpp @@ -112,7 +112,7 @@ namespace * For pad play, a value of 20ms-50ms seems to result in a better experience. * For keyboard play, this is often set to 0. * */ -static Preference g_fInputDebounceTime( "InputDebounceTime", 0.02 ); +static Preference g_fInputDebounceTime( "InputDebounceTime", 0.02f ); InputFilter* INPUTFILTER = nullptr; // global and accessible from anywhere in our program diff --git a/src/LightsManager.cpp b/src/LightsManager.cpp index 2afb3807e4..a2f25f93a7 100644 --- a/src/LightsManager.cpp +++ b/src/LightsManager.cpp @@ -362,6 +362,7 @@ void LightsManager::Update( float fDeltaTime ) } // fall through to blink on button presses + [[fallthrough]]; } case LIGHTSMODE_DEMONSTRATION: @@ -383,6 +384,7 @@ void LightsManager::Update( float fDeltaTime ) } // fall through to blink on button presses + [[fallthrough]]; } case LIGHTSMODE_ATTRACT: diff --git a/src/LyricsLoader.cpp b/src/LyricsLoader.cpp index 1c8097ae9c..b45b8ae037 100644 --- a/src/LyricsLoader.cpp +++ b/src/LyricsLoader.cpp @@ -71,7 +71,7 @@ bool LyricsLoader::LoadFromLRCFile(const RString& sPath, Song& out) if( sValueName.EqualsNoCase("COLOUR") || sValueName.EqualsNoCase("COLOR") ) { // set color var here for this segment - int r, g, b; + unsigned int r, g, b; int result = sscanf( sValueData.c_str(), "0x%2x%2x%2x", &r, &g, &b ); // According to the Dance With Intensity readme, one can set up to // ten colors in a line and access them via "{cX}", where X is 0-9. diff --git a/src/MemoryCardManager.cpp b/src/MemoryCardManager.cpp index 766d8b2bfc..87ad5865ba 100644 --- a/src/MemoryCardManager.cpp +++ b/src/MemoryCardManager.cpp @@ -481,7 +481,7 @@ void MemoryCardManager::CheckStateChanges() if( LastState == MemoryCardState_Ready ) { m_soundDisconnect.Play(true, ¶ms); - MESSAGEMAN->Broadcast( (MessageID)(Message_CardRemovedP1+p) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_CardRemovedP1+Enum::to_integral(p)) ); } break; case MemoryCardState_Ready: diff --git a/src/ModIcon.cpp b/src/ModIcon.cpp index 4b14fab92f..758fc2478e 100644 --- a/src/ModIcon.cpp +++ b/src/ModIcon.cpp @@ -45,7 +45,7 @@ void ModIcon::Load( RString sMetricsGroup ) // stop words STOP_WORDS.Load( sMetricsGroup, "StopWords" ); - m_vStopWords.empty(); + // TODO should m_vStopWords be cleared? split(STOP_WORDS, ",", m_vStopWords); Set(""); diff --git a/src/ModIconRow.cpp b/src/ModIconRow.cpp index 6735de8c71..b0ef451e3c 100644 --- a/src/ModIconRow.cpp +++ b/src/ModIconRow.cpp @@ -152,10 +152,7 @@ void ModIconRow::SetFromGameState() { RString sOption = vsOptions[i]; int iPerferredCol = OptionToPreferredColumn( sOption ); - clamp( iPerferredCol, 0, (int)m_vpModIcon.size()-1 ); - - if( iPerferredCol == -1 ) - continue; // skip + iPerferredCol = clamp( iPerferredCol, 0, (int)m_vpModIcon.size()-1 ); // search for a vacant spot for( int j=iPerferredCol; j &from = getWheelItemsData(SORT_MODE_MENU); for( unsigned i=0; im_pAction != nullptr ); + ASSERT( !from[i]->m_pAction.isNull() ); if( from[i]->m_pAction->DescribesCurrentModeForAllPlayers() ) { m_sLastModeMenuItem = from[i]->m_pAction->m_sName; @@ -427,7 +430,7 @@ void MusicWheel::GetSongList( std::vector &arraySongs, SortOrder so ) apAllSongs = SONGMAN->GetSongs(GAMESTATE->m_sPreferredSongGroup); break; } - // otherwise fall through + [[fallthrough]]; default: apAllSongs = SONGMAN->GetAllSongs(); break; diff --git a/src/MusicWheelItem.cpp b/src/MusicWheelItem.cpp index 24f531cc2b..b60e216717 100644 --- a/src/MusicWheelItem.cpp +++ b/src/MusicWheelItem.cpp @@ -424,14 +424,14 @@ void MusicWheelItem::HandleMessage( const Message &msg ) break; } - Message msg( "Set" ); - msg.SetParam( "Song", pWID->m_pSong ); - msg.SetParam( "Course", pWID->m_pCourse ); - msg.SetParam( "Text", pWID->m_sText ); - msg.SetParam( "Type", MusicWheelItemTypeToString(type) ); - msg.SetParam( "Color", pWID->m_color ); - msg.SetParam( "Label", pWID->m_sLabel ); - this->HandleMessage( msg ); + Message tmpMsg( "Set" ); + tmpMsg.SetParam( "Song", pWID->m_pSong ); + tmpMsg.SetParam( "Course", pWID->m_pCourse ); + tmpMsg.SetParam( "Text", pWID->m_sText ); + tmpMsg.SetParam( "Type", MusicWheelItemTypeToString(type) ); + tmpMsg.SetParam( "Color", pWID->m_color ); + tmpMsg.SetParam( "Label", pWID->m_sLabel ); + this->HandleMessage( tmpMsg ); RefreshGrades(); } diff --git a/src/NoteData.cpp b/src/NoteData.cpp index ad84d908d6..0464d49dee 100644 --- a/src/NoteData.cpp +++ b/src/NoteData.cpp @@ -30,7 +30,7 @@ bool NoteData::IsComposite() const { for( int track = 0; track < GetNumTracks(); ++track ) { - for (std::pair const &tn : m_TapNotes[track]) + for (const auto& tn : m_TapNotes[track]) if( tn.second.pn != PLAYER_INVALID ) return true; } @@ -1340,12 +1340,24 @@ NoteData::_all_tracks_iterator::_all_tracks_iterator( const _all_t } template - NoteData::_all_tracks_iterator::~_all_tracks_iterator() +NoteData::_all_tracks_iterator &NoteData::_all_tracks_iterator::operator=( const _all_tracks_iterator &other ) { - if(m_pNoteData != nullptr) - { - m_pNoteData->RemoveATIFromList(this); - } + _all_tracks_iterator tmp (other); + +#define SWAP_OTHER( x ) std::swap( x, tmp.x ) + SWAP_OTHER( m_pNoteData ); + SWAP_OTHER( m_vBeginIters ); + SWAP_OTHER( m_vCurrentIters ); + SWAP_OTHER( m_vEndIters ); + SWAP_OTHER( m_iTrack ); + SWAP_OTHER( m_bReverse ); + SWAP_OTHER( m_PrevCurrentRows ); + SWAP_OTHER( m_StartRow ); + SWAP_OTHER( m_EndRow ); +#undef SWAP_OTHER + m_pNoteData->AddATIToList(this); + + return *this; } template diff --git a/src/NoteData.h b/src/NoteData.h index 5ffc864b25..306b7e01f6 100644 --- a/src/NoteData.h +++ b/src/NoteData.h @@ -81,7 +81,8 @@ public: public: _all_tracks_iterator( ND &nd, int iStartRow, int iEndRow, bool bReverse, bool bInclusive ); _all_tracks_iterator( const _all_tracks_iterator &other ); - ~_all_tracks_iterator(); + ~_all_tracks_iterator() { if(m_pNoteData != nullptr) { m_pNoteData->RemoveATIFromList(this); } } + _all_tracks_iterator &operator=( const _all_tracks_iterator &other ); _all_tracks_iterator &operator++(); // preincrement _all_tracks_iterator operator++( int dummy ); // postincrement //_all_tracks_iterator &operator--(); // predecrement diff --git a/src/NoteDataUtil.cpp b/src/NoteDataUtil.cpp index c379e0bf82..d87dc8f4bb 100644 --- a/src/NoteDataUtil.cpp +++ b/src/NoteDataUtil.cpp @@ -1514,6 +1514,7 @@ static void GetTrackMapping( StepsType st, NoteDataUtil::TrackMapping tt, int Nu } if (needsBackwards) break; } + [[fallthrough]]; case NoteDataUtil::mirror: { for( int t=0; t &vpSpr, // (step 2 of vector handling) RageVector3 render_left; - if(abs(render_forward.z) > 0.9f) // 0.9 arbitrariliy picked. + if(std::abs(render_forward.z) > 0.9f) // 0.9 arbitrariliy picked. { RageVec3Cross(&render_left, &pos_y_vec, &render_forward); } diff --git a/src/NoteField.cpp b/src/NoteField.cpp index 7a2fb94919..66fd2d1001 100644 --- a/src/NoteField.cpp +++ b/src/NoteField.cpp @@ -674,7 +674,7 @@ float FindLastDisplayedBeat( const PlayerState* pPlayerState, int iDrawDistanceB bool bBoomerang; { - const float* fAccels = pPlayerState->m_PlayerOptions.GetCurrent().m_fAccels; + const auto& fAccels = pPlayerState->m_PlayerOptions.GetCurrent().m_fAccels; bBoomerang = (fAccels[PlayerOptions::ACCEL_BOOMERANG] != 0); } @@ -794,13 +794,12 @@ void NoteField::DrawPrimitives() FOREACH_TimingSegmentType( tst ) segs[tst] = &(pTiming->GetTimingSegments(tst)); - unsigned i = 0; // Draw beat bars if( ( GAMESTATE->IsEditing() || SHOW_BEAT_BARS ) && pTiming != nullptr ) { const std::vector &tSigs = *segs[SEGMENT_TIME_SIG]; int iMeasureIndex = 0; - for (i = 0; i < tSigs.size(); i++) + for (size_t i = 0; i < tSigs.size(); i++) { const TimeSignatureSegment *ts = ToTimeSignature(tSigs[i]); int iSegmentEndRow = (i + 1 == tSigs.size()) ? m_FieldRenderArgs.last_row : tSigs[i+1]->GetRow(); @@ -848,7 +847,7 @@ void NoteField::DrawPrimitives() #define draw_all_segments(str_exp, name, caps_name) \ horiz_align= caps_name##_IS_LEFT_SIDE ? align_right : align_left; \ side_sign= caps_name##_IS_LEFT_SIDE ? -1 : 1; \ - for(unsigned int i= 0; i < segs[SEGMENT_##caps_name]->size(); ++i) \ + for(size_t i= 0; i < segs[SEGMENT_##caps_name]->size(); ++i) \ { \ const name##Segment* seg= To##name((*segs[SEGMENT_##caps_name])[i]); \ if(seg->GetRow() >= m_FieldRenderArgs.first_row && \ @@ -903,18 +902,14 @@ void NoteField::DrawPrimitives() AttackArray &attacks = GAMESTATE->m_bIsUsingStepTiming ? GAMESTATE->m_pCurSteps[PLAYER_1]->m_Attacks : GAMESTATE->m_pCurSong->m_Attacks; - // XXX: We're somehow getting here when attacks is null. Find the actual cause later. - if (&attacks) + for (Attack const &a : attacks) { - for (Attack const &a : attacks) + float fBeat = timing.GetBeatFromElapsedTime(a.fStartSecond); + if (BeatToNoteRow(fBeat) >= m_FieldRenderArgs.first_row && + BeatToNoteRow(fBeat) <= m_FieldRenderArgs.last_row && + IS_ON_SCREEN(fBeat)) { - float fBeat = timing.GetBeatFromElapsedTime(a.fStartSecond); - if (BeatToNoteRow(fBeat) >= m_FieldRenderArgs.first_row && - BeatToNoteRow(fBeat) <= m_FieldRenderArgs.last_row && - IS_ON_SCREEN(fBeat)) - { - this->DrawAttackText(fBeat, a, text_glow); - } + this->DrawAttackText(fBeat, a, text_glow); } } } diff --git a/src/NotesLoaderBMS.cpp b/src/NotesLoaderBMS.cpp index cae1c9ae17..6e694b8c8d 100644 --- a/src/NotesLoaderBMS.cpp +++ b/src/NotesLoaderBMS.cpp @@ -544,9 +544,8 @@ bool BMSChart::Load( const RString &chartPath ) std::vector lines; Tree.evaluateBMSTree(headers, lines); - for (std::vector::iterator i = lines.begin(); i != lines.end(); ++i) + for (const auto& line : lines) { - RString line = *i; RString data = line.substr(7); int measure = atoi(line.substr(1, 3).c_str()); int channel = atoi(line.substr(4, 2).c_str()); @@ -963,6 +962,8 @@ StepsType BMSChartReader::DetermineStepsType() case 4: return StepsType_dance_single; case 5: if( nonEmptyTracks.find(BMS_RAW_P2_KEY2) != nonEmptyTracks.end() ) return StepsType_popn_five; + + [[fallthrough]]; case 6: // FIXME: There's no way to distinguish between these types. // They use the same number of tracks. Assume it's a Beat @@ -1087,7 +1088,7 @@ bmFrac toFraction(double f) long long upper = 1LL, lower = 1LL; df = 1; - while (abs(df - f) > 0.000001) + while (std::abs(df - f) > 0.000001) { if (df < f) { @@ -1326,7 +1327,7 @@ bool BMSChartReader::ReadNoteData() if( channel == 3 ) // bpm change { - int bpm; + unsigned int bpm; if( sscanf(obj.value, "%x", &bpm) == 1 ) { if( bpm > 0 ) td.SetBPMAtRow( row, measureAdjust * (currentBPM = bpm) ); diff --git a/src/NotesLoaderJson.cpp b/src/NotesLoaderJson.cpp index 537255a959..125af404b7 100644 --- a/src/NotesLoaderJson.cpp +++ b/src/NotesLoaderJson.cpp @@ -89,22 +89,18 @@ static void Deserialize(BackgroundChange &o, const Json::Value &root ) static void Deserialize( TapNote &o, const Json::Value &root ) { - //if( o.type != TapNoteType_Tap ) - if( root.isInt() ) + if( root.isInt() ) { o.type = (TapNoteType)root["Type"].asInt(); - //if( o.type == TapNoteType_HoldHead ) - o.subType = (TapNoteSubType)root["SubType"].asInt(); - //root["Source"] = (int)source; - //if( !o.sAttackModifiers.empty() ) - o.sAttackModifiers = root["AttackModifiers"].asString(); - //if( o.fAttackDurationSeconds > 0 ) - o.fAttackDurationSeconds = (float)root["AttackDurationSeconds"].asDouble(); - //if( o.bKeysound ) - o.iKeysoundIndex = root["KeysoundIndex"].asInt(); - //if( o.iDuration > 0 ) - o.iDuration = root["Duration"].asInt(); - //if( o.pn != PLAYER_INVALID ) - o.pn = (PlayerNumber)root["PlayerNumber"].asInt(); + } + + // TODO should all of this also be within the if statement? + // It was not in the if statement previously, but that may have been unintentional. + o.subType = (TapNoteSubType)root["SubType"].asInt(); + o.sAttackModifiers = root["AttackModifiers"].asString(); + o.fAttackDurationSeconds = (float)root["AttackDurationSeconds"].asDouble(); + o.iKeysoundIndex = root["KeysoundIndex"].asInt(); + o.iDuration = root["Duration"].asInt(); + o.pn = (PlayerNumber)root["PlayerNumber"].asInt(); } static void Deserialize( StepsType st, NoteData &nd, const Json::Value &root ) diff --git a/src/NotesLoaderSM.cpp b/src/NotesLoaderSM.cpp index c6513b7d48..d81708ce22 100644 --- a/src/NotesLoaderSM.cpp +++ b/src/NotesLoaderSM.cpp @@ -952,10 +952,10 @@ bool SMLoader::LoadFromBGChangesVector( BackgroundChange &change, std::vector= 2; @@ -1461,6 +1460,7 @@ void SMLoader::ParseBGChangesString(const RString& _sChanges, std::vector &selected, const RSt sName.c_str(), num_selected, static_cast(selected.size())); for(unsigned int e= 0; e < selected.size(); ++e) { - if(selected[e] && e != first_selected) + if(selected[e] && (first_selected < 0 || e != static_cast(first_selected))) { selected[e]= false; } diff --git a/src/OptionsCursor.cpp b/src/OptionsCursor.cpp index b1a69a8c14..291d17aed1 100644 --- a/src/OptionsCursor.cpp +++ b/src/OptionsCursor.cpp @@ -91,7 +91,7 @@ void OptionsCursor::StopTweening() } } -void OptionsCursor::BeginTweening( float fSecs ) +void OptionsCursor::BeginTweening( float fSecs, TweenType tt ) { ActorFrame::BeginTweening( fSecs ); diff --git a/src/OptionsCursor.h b/src/OptionsCursor.h index 9f0652fe24..2a5bdf1da4 100644 --- a/src/OptionsCursor.h +++ b/src/OptionsCursor.h @@ -19,7 +19,7 @@ public: void Load( const RString &sMetricsGroup, bool bLoadCanGos ); void StopTweening(); - void BeginTweening( float fSecs ); + void BeginTweening( float fSecs, TweenType tt = TWEEN_LINEAR ); void SetBarWidth( int iWidth ); int GetBarWidth() const; void SetCanGo( bool bCanGoLeft, bool bCanGoRight ); diff --git a/src/Player.cpp b/src/Player.cpp index d07164e373..4a2d5e0d25 100644 --- a/src/Player.cpp +++ b/src/Player.cpp @@ -1136,8 +1136,8 @@ void Player::Update( float fDeltaTime ) * .5 before the row. Use a very slow song (around 2 BPM) as a test case: without * rounding, autoplay steps early. -glenn */ const float fPositionSeconds = m_pPlayerState->m_Position.m_fMusicSeconds - PREFSMAN->m_fPadStickSeconds; - const float fSongBeat = m_pPlayerState->GetDisplayedTiming().GetBeatFromElapsedTime( fPositionSeconds ); - const int iRowNow = BeatToNoteRowNotRounded( fSongBeat ); + const float fSongBeatTmp = m_pPlayerState->GetDisplayedTiming().GetBeatFromElapsedTime( fPositionSeconds ); + const int iRowNow = BeatToNoteRowNotRounded( fSongBeatTmp ); if( iRowNow >= 0 ) { @@ -2285,6 +2285,7 @@ void Player::Step( int col, int row, const RageTimer &tm, bool bHeld, bool bRele break; } // Fall through to default. + [[fallthrough]]; default: if( (pTN->type == TapNoteType_Lift) == bRelease ) { @@ -3213,22 +3214,22 @@ void Player::SetJudgment( int iRow, int iTrack, const TapNote &tn, TapNoteScore lua_createtable( L, 0, m_NoteData.GetNumTracks() ); // TapNotes this row lua_createtable( L, 0, m_NoteData.GetNumTracks() ); // HoldHeads of tracks held at this row. - for( int iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack ) + for( int iTrackTmp = 0; iTrackTmp < m_NoteData.GetNumTracks(); ++iTrackTmp ) { - NoteData::iterator tn = m_NoteData.FindTapNote(iTrack, iRow); - if( tn != m_NoteData.end(iTrack) ) + NoteData::iterator tnTmp = m_NoteData.FindTapNote(iTrackTmp, iRow); + if( tnTmp != m_NoteData.end(iTrackTmp) ) { - tn->second.PushSelf(L); - lua_rawseti(L, -3, iTrack + 1); + tnTmp->second.PushSelf(L); + lua_rawseti(L, -3, iTrackTmp + 1); } else { int iHeadRow; - if( m_NoteData.IsHoldNoteAtRow( iTrack, iRow, &iHeadRow ) ) + if( m_NoteData.IsHoldNoteAtRow( iTrackTmp, iRow, &iHeadRow ) ) { - NoteData::iterator hold = m_NoteData.FindTapNote(iTrack, iHeadRow); + NoteData::iterator hold = m_NoteData.FindTapNote(iTrackTmp, iHeadRow); hold->second.PushSelf(L); - lua_rawseti(L, -2, iTrack + 1); + lua_rawseti(L, -2, iTrackTmp + 1); } } } diff --git a/src/PlayerOptions.h b/src/PlayerOptions.h index d70252a25f..6b1e03c4cb 100644 --- a/src/PlayerOptions.h +++ b/src/PlayerOptions.h @@ -82,10 +82,11 @@ public: m_fModTimerOffset(0), m_SpeedfModTimerOffset(1.0f), m_fDrawSize(0), m_SpeedfDrawSize(1.0f), m_fDrawSizeBack(0), m_SpeedfDrawSizeBack(1.0f), - m_bMuteOnError(false), m_FailType(FailType_Immediate), + m_bMuteOnError(false), m_bStealthType(false), m_bStealthPastReceptors(false), m_bDizzyHolds(false), m_bZBuffer(false), m_bCosecant(false), + m_FailType(FailType_Immediate), m_MinTNSToHideNotes(PREFSMAN->m_MinTNSToHideNotes) { m_sNoteSkin = ""; @@ -132,6 +133,7 @@ public: bool operator==( const PlayerOptions &other ) const; bool operator!=( const PlayerOptions &other ) const { return !operator==(other); } PlayerOptions& operator=(PlayerOptions const& other); + PlayerOptions(const PlayerOptions& other) { operator=(other); } /** @brief The various acceleration mods. */ enum Accel { diff --git a/src/PlayerStageStats.cpp b/src/PlayerStageStats.cpp index 7a93993b12..190ba80da0 100644 --- a/src/PlayerStageStats.cpp +++ b/src/PlayerStageStats.cpp @@ -391,7 +391,7 @@ void PlayerStageStats::SetLifeRecordAt( float fLife, float fStepsSecond ) } m_fLifeRecord[fStepsSecond] = fLife; - Message msg(static_cast(Message_LifeMeterChangedP1+m_player_number)); + Message msg(static_cast(Message_LifeMeterChangedP1+Enum::to_integral(m_player_number))); msg.SetParam("Life", fLife); msg.SetParam("StepsSecond", fStepsSecond); MESSAGEMAN->Broadcast(msg); diff --git a/src/PrefsManager.cpp b/src/PrefsManager.cpp index 136148a069..5367cc8317 100644 --- a/src/PrefsManager.cpp +++ b/src/PrefsManager.cpp @@ -267,9 +267,6 @@ PrefsManager::PrefsManager() : m_sAdditionalCourseFoldersWritable( "AdditionalCourseFoldersWritable", "", nullptr, PreferenceType::Immutable ), m_sAdditionalFoldersReadOnly ( "AdditionalFoldersReadOnly", "", nullptr, PreferenceType::Immutable ), m_sAdditionalFoldersWritable ( "AdditionalFoldersWritable", "", nullptr, PreferenceType::Immutable ), - m_sAdditionalSongFolders ( "AdditionalSongFolders", "", nullptr, PreferenceType::Deprecated ), - m_sAdditionalCourseFolders ( "AdditionalCourseFolders", "", nullptr, PreferenceType::Deprecated ), - m_sAdditionalFolders ( "AdditionalFolders", "", nullptr, PreferenceType::Deprecated ), m_sDefaultTheme ( "DefaultTheme", "Simply Love" ), m_sLastSeenVideoDriver ( "LastSeenVideoDriver", "" ), m_sVideoRenderers ( "VideoRenderers", "" ), // StepMania.cpp sets these on first run: @@ -311,8 +308,10 @@ PrefsManager::PrefsManager() : m_bLogCheckpoints ( "LogCheckpoints", false ), m_bShowLoadingWindow ( "ShowLoadingWindow", true ), m_bPseudoLocalize ( "PseudoLocalize", false ), - m_show_theme_errors ( "ShowThemeErrors", false ) - + m_show_theme_errors ( "ShowThemeErrors", false ), + m_sAdditionalSongFolders ( "AdditionalSongFolders", "", nullptr, PreferenceType::Deprecated ), + m_sAdditionalCourseFolders ( "AdditionalCourseFolders", "", nullptr, PreferenceType::Deprecated ), + m_sAdditionalFolders ( "AdditionalFolders", "", nullptr, PreferenceType::Deprecated ) { Init(); ReadPrefsFromDisk(); diff --git a/src/Profile.cpp b/src/Profile.cpp index ef6cf9ed03..b0443b6c7c 100644 --- a/src/Profile.cpp +++ b/src/Profile.cpp @@ -96,7 +96,7 @@ void Profile::ClearSongs() int Profile::HighScoresForASong::GetNumTimesPlayed() const { int iCount = 0; - for (std::pair const &i : m_StepsHighScores) + for (const auto& i : m_StepsHighScores) { iCount += i.second.hsl.GetNumTimesPlayed(); } @@ -106,7 +106,7 @@ int Profile::HighScoresForASong::GetNumTimesPlayed() const int Profile::HighScoresForACourse::GetNumTimesPlayed() const { int iCount = 0; - for (std::pair const &i : m_TrailHighScores) + for (const auto& i : m_TrailHighScores) { iCount += i.second.hsl.GetNumTimesPlayed(); } @@ -394,7 +394,7 @@ float Profile::GetSongsActual( StepsType st, Difficulty dc ) const { Song* pSong = id.first.ToSong(); - CHECKPOINT_M( ssprintf("Profile::GetSongsActual: %p", pSong) ); + CHECKPOINT_M( ssprintf("Profile::GetSongsActual: %p", static_cast(pSong)) ); // If the Song isn't loaded on the current machine, then we can't // get radar values to compute dance points. @@ -411,7 +411,7 @@ float Profile::GetSongsActual( StepsType st, Difficulty dc ) const { const StepsID &sid = j.first; Steps* pSteps = sid.ToSteps( pSong, true ); - CHECKPOINT_M( ssprintf("Profile::GetSongsActual: song %p, steps %p", pSong, pSteps) ); + CHECKPOINT_M( ssprintf("Profile::GetSongsActual: song %p, steps %p", static_cast(pSong), static_cast(pSteps)) ); // If the Steps isn't loaded on the current machine, then we can't // get radar values to compute dance points. @@ -421,7 +421,7 @@ float Profile::GetSongsActual( StepsType st, Difficulty dc ) const if( pSteps->m_StepsType != st ) continue; - CHECKPOINT_M( ssprintf("Profile::GetSongsActual: n %s = %p", sid.ToString().c_str(), pSteps) ); + CHECKPOINT_M( ssprintf("Profile::GetSongsActual: n %s = %p", sid.ToString().c_str(), static_cast(pSteps)) ); if( pSteps->GetDifficulty() != dc ) { continue; // skip @@ -1605,7 +1605,7 @@ XNode* Profile::SaveGeneralDataCreateNode() const { XNode* pNumSongsPlayedByStyle = pGeneralDataNode->AppendChild("NumSongsPlayedByStyle"); - for (std::pair const iter : m_iNumSongsPlayedByStyle) + for (const auto& iter : m_iNumSongsPlayedByStyle) { const StyleID &s = iter.first; int iNumPlays = iter.second; diff --git a/src/RageDisplay.h b/src/RageDisplay.h index d2c23a7c46..81705604a7 100644 --- a/src/RageDisplay.h +++ b/src/RageDisplay.h @@ -112,44 +112,30 @@ public: PAL(PAL_), fDisplayAspectRatio(fDisplayAspectRatio_) {} - VideoModeParams(const VideoModeParams &other): - windowed(other.windowed), sDisplayId(other.sDisplayId), - width(other.width), height(other.height), - bpp(other.bpp), rate(other.rate), - vsync(other.vsync), interlaced(other.interlaced), - bSmoothLines(other.bSmoothLines), bTrilinearFiltering(other.bTrilinearFiltering), - bAnisotropicFiltering(other.bAnisotropicFiltering), bWindowIsFullscreenBorderless(other.bWindowIsFullscreenBorderless), - sWindowTitle(other.sWindowTitle), sIconFile(other.sIconFile), - PAL(other.PAL), fDisplayAspectRatio(other.fDisplayAspectRatio) - {} + VideoModeParams(const VideoModeParams &other) = default; - VideoModeParams(): windowed(false), width(0), height(0), - bpp(0), rate(0), vsync(false), interlaced(false), - bSmoothLines(false), bTrilinearFiltering(false), - bAnisotropicFiltering(false), bWindowIsFullscreenBorderless(false), - sWindowTitle(RString()), sIconFile(RString()), - PAL(false), fDisplayAspectRatio(0.0f) {} + VideoModeParams() = default; // Subclassing VideoModeParams in ActualVideoModeParams. Make destructor virtual just in case // someone tries to delete one of those through a pointer to base... - virtual ~VideoModeParams() {} + virtual ~VideoModeParams() = default; - bool windowed; - RString sDisplayId; - int width; - int height; - int bpp; - int rate; - bool vsync; - bool interlaced; - bool bSmoothLines; - bool bTrilinearFiltering; - bool bAnisotropicFiltering; - bool bWindowIsFullscreenBorderless; - RString sWindowTitle; - RString sIconFile; - bool PAL; - float fDisplayAspectRatio; + bool windowed{false}; + RString sDisplayId{}; + int width{0}; + int height{0}; + int bpp{0}; + int rate{0}; + bool vsync{false}; + bool interlaced{false}; + bool bSmoothLines{false}; + bool bTrilinearFiltering{false}; + bool bAnisotropicFiltering{false}; + bool bWindowIsFullscreenBorderless{false}; + RString sWindowTitle{}; + RString sIconFile{}; + bool PAL{false}; + float fDisplayAspectRatio{0.0f}; }; /** @@ -171,6 +157,8 @@ public: renderOffscreen( renderOffscreen ) { } ActualVideoModeParams (const ActualVideoModeParams &other) = default; + ActualVideoModeParams& operator=(const ActualVideoModeParams& other) = default; + // If bWindowIsFullscreenBorderless is true, // then these properties will differ from width/height (which describe the diff --git a/src/RageDisplay_D3D.cpp b/src/RageDisplay_D3D.cpp index 4015538082..c4a3aa345d 100644 --- a/src/RageDisplay_D3D.cpp +++ b/src/RageDisplay_D3D.cpp @@ -744,7 +744,7 @@ void RageDisplay_D3D::SendCurrentMatrices() 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 1.0f ); - g_pd3dDevice->SetTransform( (D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0+tu), (D3DMATRIX*)&tex ); + g_pd3dDevice->SetTransform( (D3DTRANSFORMSTATETYPE)(D3DTS_TEXTURE0+Enum::to_integral(tu)), (D3DMATRIX*)&tex ); // Tell D3D to use transformed reflection vectors as texture co-ordinate 0 // and then transform this coordinate by the specified texture matrix. @@ -765,7 +765,7 @@ void RageDisplay_D3D::SendCurrentMatrices() tex1.m[3][0], tex1.m[3][1], tex1.m[3][3], 0, 0, 0, 0, 0 ); - g_pd3dDevice->SetTransform( D3DTRANSFORMSTATETYPE(D3DTS_TEXTURE0+tu), (D3DMATRIX*)&tex2 ); + g_pd3dDevice->SetTransform( D3DTRANSFORMSTATETYPE(D3DTS_TEXTURE0+Enum::to_integral(tu)), (D3DMATRIX*)&tex2 ); g_pd3dDevice->SetTextureStageState( tu, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU ); } diff --git a/src/RageDisplay_D3D.h b/src/RageDisplay_D3D.h index 8a56441aeb..a3412132e3 100644 --- a/src/RageDisplay_D3D.h +++ b/src/RageDisplay_D3D.h @@ -3,6 +3,8 @@ #ifndef RAGE_DISPLAY_D3D_H #define RAGE_DISPLAY_D3D_H +#include "RageDisplay.h" + class RageDisplay_D3D: public RageDisplay { public: diff --git a/src/RageDisplay_GLES2.cpp b/src/RageDisplay_GLES2.cpp index 0e3e24c849..2f5c555f8e 100644 --- a/src/RageDisplay_GLES2.cpp +++ b/src/RageDisplay_GLES2.cpp @@ -169,7 +169,10 @@ namespace void FixLittleEndian() { -#if defined(ENDIAN_LITTLE) + if constexpr (!Endian::little) { + return; + } + static bool bInitialized = false; if (bInitialized) return; @@ -197,7 +200,6 @@ namespace pf.masks[mask] = m; } } -#endif } namespace Caps { diff --git a/src/RageDisplay_OGL.cpp b/src/RageDisplay_OGL.cpp index 2f428c57ce..22034e6c58 100644 --- a/src/RageDisplay_OGL.cpp +++ b/src/RageDisplay_OGL.cpp @@ -213,7 +213,10 @@ struct GLPixFmtInfo_t { static void FixLittleEndian() { -#if defined(ENDIAN_LITTLE) + if constexpr (!Endian::little) { + return; + } + static bool bInitialized = false; if (bInitialized) return; @@ -241,7 +244,6 @@ static void FixLittleEndian() pf.masks[mask] = m; } } -#endif } static void TurnOffHardwareVBO() @@ -2213,7 +2215,7 @@ uintptr_t RageDisplay_Legacy::CreateTexture( /* If the image is paletted, but we're not sending it to a paletted image, * set up glPixelMap. */ - SetPixelMapForSurface( glImageFormat, glTexFormat, pImg->format->palette ); + SetPixelMapForSurface( glImageFormat, glTexFormat, pImg->format->palette.get() ); // HACK: OpenGL 1.2 types aren't available in GLU 1.3. Don't call GLU for mip // mapping if we're using an OGL 1.2 type and don't have >= GLU 1.3. @@ -2433,7 +2435,7 @@ void RageDisplay_Legacy::UpdateTexture( { GLenum glTexFormat = 0; glGetTexLevelParameteriv( GL_PROXY_TEXTURE_2D, 0, GLenum(GL_TEXTURE_INTERNAL_FORMAT), (GLint *) &glTexFormat ); - SetPixelMapForSurface( glImageFormat, glTexFormat, pImg->format->palette ); + SetPixelMapForSurface( glImageFormat, glTexFormat, pImg->format->palette.get() ); } glTexSubImage2D( GL_TEXTURE_2D, 0, @@ -2691,7 +2693,7 @@ void RageDisplay_Legacy::SetLineWidth(float fWidth) glLineWidth(fWidth); } -RString RageDisplay_Legacy::GetTextureDiagnostics(unsigned iTexture) const +RString RageDisplay_Legacy::GetTextureDiagnostics(uintptr_t iTexture) const { /* s << (bGenerateMipMaps? "gluBuild2DMipmaps":"glTexImage2D"); diff --git a/src/RageDisplay_OGL.h b/src/RageDisplay_OGL.h index a54c51aeb5..f713dbe745 100644 --- a/src/RageDisplay_OGL.h +++ b/src/RageDisplay_OGL.h @@ -115,7 +115,7 @@ public: virtual void SetPolygonMode( PolygonMode pm ); virtual void SetLineWidth( float fWidth ); - RString GetTextureDiagnostics( unsigned id ) const; + RString GetTextureDiagnostics( uintptr_t id ) const; protected: void DrawQuadsInternal( const RageSpriteVertex v[], int iNumVerts ); diff --git a/src/RageException.h b/src/RageException.h index d86ff39ce3..297d58aa86 100644 --- a/src/RageException.h +++ b/src/RageException.h @@ -9,7 +9,7 @@ * The original documentation stated this was a class for some reason. */ namespace RageException { - void NORETURN Throw( const char *fmt, ... ) PRINTF(1,2); + void SM_NORETURN Throw( const char *fmt, ... ) PRINTF(1,2); void SetCleanupHandler( void (*pHandler)(const RString &sError) ); } diff --git a/src/RageFileBasic.cpp b/src/RageFileBasic.cpp index 31c9e71ce4..b3ac5659a7 100644 --- a/src/RageFileBasic.cpp +++ b/src/RageFileBasic.cpp @@ -439,7 +439,7 @@ int RageFileObj::FillReadBuf() * the two is old data that we've read. (Don't mangle that data; we can use it * for seeking backwards.) */ const int iBufAvail = BSIZE - (m_pReadBuf-m_pReadBuffer) - m_iReadBufAvail; - ASSERT_M( iBufAvail >= 0, ssprintf("%p, %p, %i", m_pReadBuf, m_pReadBuffer, (int) BSIZE ) ); + ASSERT_M( iBufAvail >= 0, ssprintf("%p, %p, %i", static_cast(m_pReadBuf), static_cast(m_pReadBuffer), BSIZE ) ); const int iSize = this->ReadInternal( m_pReadBuf+m_iReadBufAvail, iBufAvail ); if( iSize > 0 ) diff --git a/src/RageFileDriverDirect.cpp b/src/RageFileDriverDirect.cpp index 66c9bd1c7b..440b3b337d 100644 --- a/src/RageFileDriverDirect.cpp +++ b/src/RageFileDriverDirect.cpp @@ -204,7 +204,7 @@ RageFileObjDirect *RageFileObjDirect::Copy() const if( ret == nullptr ) RageException::Throw( "Couldn't reopen \"%s\": %s", m_sPath.c_str(), strerror(iErr) ); - ret->Seek( (int)lseek( m_iFD, 0, SEEK_CUR ) ); + ret->Seek( (int)DoLseek( m_iFD, 0, SEEK_CUR ) ); return ret; } @@ -322,7 +322,7 @@ RageFileObjDirect::~RageFileObjDirect() if( m_iFD != -1 ) { - if( close( m_iFD ) == -1 ) + if( DoClose( m_iFD ) == -1 ) { WARN( ssprintf("Error closing %s: %s", this->m_sPath.c_str(), strerror(errno)) ); SetError( strerror(errno) ); @@ -391,7 +391,7 @@ RageFileObjDirect::~RageFileObjDirect() int RageFileObjDirect::ReadInternal( void *pBuf, size_t iBytes ) { - int iRet = read( m_iFD, pBuf, iBytes ); + int iRet = DoRead( m_iFD, pBuf, iBytes ); if( iRet == -1 ) { SetError( strerror(errno) ); @@ -407,7 +407,7 @@ static int RetriedWrite( int iFD, const void *pBuf, size_t iCount ) int iTries = 3, iRet; do { - iRet = write( iFD, pBuf, iCount ); + iRet = DoWrite( iFD, pBuf, iCount ); } while( iRet == -1 && errno == EINTR && iTries-- ); @@ -448,16 +448,16 @@ int RageFileObjDirect::WriteInternal( const void *pBuf, size_t iBytes ) int RageFileObjDirect::SeekInternal( int iOffset ) { - return (int)lseek( m_iFD, iOffset, SEEK_SET ); + return (int)DoLseek( m_iFD, iOffset, SEEK_SET ); } int RageFileObjDirect::GetFileSize() const { - const int iOldPos = (int)lseek( m_iFD, 0, SEEK_CUR ); + const int iOldPos = (int)DoLseek( m_iFD, 0, SEEK_CUR ); ASSERT_M( iOldPos != -1, ssprintf("\"%s\": %s", m_sPath.c_str(), strerror(errno)) ); - const int iRet = (int)lseek( m_iFD, 0, SEEK_END ); + const int iRet = (int)DoLseek( m_iFD, 0, SEEK_END ); ASSERT_M( iRet != -1, ssprintf("\"%s\": %s", m_sPath.c_str(), strerror(errno)) ); - lseek( m_iFD, iOldPos, SEEK_SET ); + DoLseek( m_iFD, iOldPos, SEEK_SET ); return iRet; } diff --git a/src/RageFileDriverDirectHelpers.h b/src/RageFileDriverDirectHelpers.h index 7d37f08f2e..aa4a8e1a81 100644 --- a/src/RageFileDriverDirectHelpers.h +++ b/src/RageFileDriverDirectHelpers.h @@ -7,13 +7,28 @@ #include #endif -#define DoOpen open #define DoStat stat #define DoMkdir mkdir #define DoFindFirstFile FindFirstFile #define DoRename rename #define DoRemove remove +#if defined(WIN32) +#define DoOpen _open +#define DoRmdir _rmdir +#define DoLseek _lseek +#define DoClose _close +#define DoRead _read +#define DoWrite _write +#define DoGetCwd _getcwd +#else +#define DoOpen open #define DoRmdir rmdir +#define DoLseek lseek +#define DoClose close +#define DoRead read +#define DoWrite write +#define DoGetCwd getcwd +#endif RString DoPathReplace( const RString &sPath ); #if defined(WIN32) diff --git a/src/RageFileDriverZip.cpp b/src/RageFileDriverZip.cpp index ee66d686c4..ae9ad76e2a 100644 --- a/src/RageFileDriverZip.cpp +++ b/src/RageFileDriverZip.cpp @@ -61,8 +61,8 @@ bool RageFileDriverZip::Load( const RString &sPath ) bool RageFileDriverZip::Load( RageFileBasic *pFile ) { ASSERT( m_pZip == nullptr ); /* don't load twice */ - m_sPath = ssprintf("%p", pFile); - m_Mutex.SetName( ssprintf("RageFileDriverZip(%p)", pFile) ); + m_sPath = ssprintf("%p", static_cast(pFile)); + m_Mutex.SetName( ssprintf("RageFileDriverZip(%p)", static_cast(pFile)) ); m_pZip = pFile; diff --git a/src/RageFileManager.cpp b/src/RageFileManager.cpp index 737f896815..ac6337cd7b 100644 --- a/src/RageFileManager.cpp +++ b/src/RageFileManager.cpp @@ -114,8 +114,8 @@ size_t zipRead(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { RageFile *f = static_cast(pOpaque); - int pos = f->Seek(file_ofs); - if (pos != file_ofs) + const auto pos = f->Seek(file_ofs); + if (pos >= 0 && static_cast(pos) != file_ofs) { return 0; } @@ -305,9 +305,9 @@ static RString ExtractDirectory( RString sPath ) return sPath; } +#if defined(UNIX) || defined(MACOSX) static RString ReadlinkRecursive( RString sPath ) { -#if defined(UNIX) || defined(MACOSX) // unices support symbolic links; dereference them RString dereferenced = sPath; do @@ -325,10 +325,10 @@ static RString ReadlinkRecursive( RString sPath ) } } } while (sPath != dereferenced); -#endif return sPath; } +#endif static RString GetDirOfExecutable( RString argv0 ) { diff --git a/src/RageMath.cpp b/src/RageMath.cpp index acff3a48d3..1f270fe3cc 100644 --- a/src/RageMath.cpp +++ b/src/RageMath.cpp @@ -616,8 +616,8 @@ float RageFastSin(float angle) { if(angle == 0) { return 0; } float index= angle * sine_table_index_mult; - int first_index= static_cast(index); - int second_index= (first_index + 1) % sine_index_mod; + auto first_index= static_cast(index); + auto second_index= (first_index + 1) % sine_index_mod; float remainder= index - first_index; first_index%= sine_index_mod; float first= 0.0f; diff --git a/src/RageModelGeometry.cpp b/src/RageModelGeometry.cpp index e4c6027498..392664c455 100644 --- a/src/RageModelGeometry.cpp +++ b/src/RageModelGeometry.cpp @@ -239,7 +239,7 @@ void RageModelGeometry::LoadMilkshapeAscii( const RString& _sPath, bool bNeedsNo uint16_t nIndices[3]; uint16_t nNormalIndices[3]; - if( sscanf (sLine, "%d %hd %hd %hd %hd %hd %hd %d", + if( sscanf (sLine, "%d %hu %hu %hu %hu %hu %hu %d", &nFlags, &nIndices[0], &nIndices[1], &nIndices[2], &nNormalIndices[0], &nNormalIndices[1], &nNormalIndices[2], diff --git a/src/RageSound.cpp b/src/RageSound.cpp index 5c632ac6cb..9b0a9d49ed 100644 --- a/src/RageSound.cpp +++ b/src/RageSound.cpp @@ -271,7 +271,7 @@ int RageSound::GetDataToPlay( float *pBuffer, int iFrames, int64_t &iStreamFrame /* We only update m_iStreamFrame; only take a shared lock, so we don't block the main thread. */ // LockMut(m_Mutex); - ASSERT_M( m_bPlaying, ssprintf("%p", this) ); + ASSERT_M( m_bPlaying, ssprintf("%p", static_cast(this)) ); ASSERT( m_pSource != nullptr ); iFramesStored = 0; diff --git a/src/RageSoundPosMap.cpp b/src/RageSoundPosMap.cpp index c49f1ad85c..f5890f2456 100644 --- a/src/RageSoundPosMap.cpp +++ b/src/RageSoundPosMap.cpp @@ -176,20 +176,15 @@ int64_t pos_map_queue::Search( int64_t iSourceFrame, bool *bApproximate ) const * SoundStopped has been called. * 3. Underflow; we'll be given a larger frame number than we know about. */ -#if defined(WIN32) -#define I64F "%I64i" -#elif defined(__x86_64__) -#define I64F "%li" -#else -#define I64F "%lli" -#endif static RageTimer last; if( last.PeekDeltaTime() >= 1.0f ) { last.GetDeltaTime(); - LOG->Trace( "Approximate sound time: driver frame " I64F ", m_pImpl->m_Queue frame " I64F ".." I64F " (dist " I64F "), closest position is " I64F, - iSourceFrame, pClosestBlock->m_iDestFrame, pClosestBlock->m_iDestFrame+pClosestBlock->m_iFrames, - iClosestPositionDist, iClosestPosition ); + std::stringstream ss; + ss << "Approximate sound time: driver frame " << iSourceFrame << ", m_pImpl->m_Queue frame " + << pClosestBlock->m_iDestFrame << ".." << (pClosestBlock->m_iDestFrame+pClosestBlock->m_iFrames) + << " (dist " << iClosestPositionDist << "), closest position is " << iClosestPosition; + LOG->Trace( "%s", ss.str().c_str() ); } if( bApproximate ) diff --git a/src/RageSoundReader_MP3.cpp b/src/RageSoundReader_MP3.cpp index 0059c29637..8d15a43c6e 100644 --- a/src/RageSoundReader_MP3.cpp +++ b/src/RageSoundReader_MP3.cpp @@ -45,9 +45,9 @@ static unsigned long id3_parse_uint( const unsigned char **ptr, unsigned int byt switch (bytes) { - case 4: value = (value << 8) | *(*ptr)++; - case 3: value = (value << 8) | *(*ptr)++; - case 2: value = (value << 8) | *(*ptr)++; + case 4: value = (value << 8) | *(*ptr)++; [[fallthrough]]; + case 3: value = (value << 8) | *(*ptr)++; [[fallthrough]]; + case 2: value = (value << 8) | *(*ptr)++; [[fallthrough]]; case 1: value = (value << 8) | *(*ptr)++; } @@ -63,7 +63,7 @@ static unsigned long id3_parse_syncsafe( const unsigned char **ptr, unsigned int switch (bytes) { case 5: - value = (value << 4) | (*(*ptr)++ & 0x0f); + value = (value << 4) | (*(*ptr)++ & 0x0f); [[fallthrough]]; case 4: value = (value << 7) | (*(*ptr)++ & 0x7f); value = (value << 7) | (*(*ptr)++ & 0x7f); diff --git a/src/RageSoundReader_Merge.cpp b/src/RageSoundReader_Merge.cpp index 1419395e65..a54af322d7 100644 --- a/src/RageSoundReader_Merge.cpp +++ b/src/RageSoundReader_Merge.cpp @@ -253,13 +253,6 @@ int RageSoundReader_Merge::Read( float *pBuffer, int iFrames ) } int iGotFrames = pSound->Read( Buffer, iFrames - iFramesRead ); - if( 0 && /*i == 1 && */iGotFrames > 0 ) - { - int iAt = aNextSourceFrames[i] + lrintf(iGotFrames * aRatios[i]); - if( iAt != m_aSounds[i]->GetNextSourceFrame() ) - LOG->Trace( "%i: at %i, expected %i", - i, iAt, m_aSounds[i]->GetNextSourceFrame() ); - } aNextSourceFrames[i] = m_aSounds[i]->GetNextSourceFrame(); aRatios[i] = m_aSounds[i]->GetStreamToSourceRatio(); // LOG->Trace( "read %i from %i; %i -> %i", iGotFrames, i, oldf, aNextSourceFrames[i] ); diff --git a/src/RageSoundReader_Resample_Good.cpp b/src/RageSoundReader_Resample_Good.cpp index caa93ab367..a8a3b4757c 100644 --- a/src/RageSoundReader_Resample_Good.cpp +++ b/src/RageSoundReader_Resample_Good.cpp @@ -120,8 +120,6 @@ namespace i2 = i1; i1 = iRem; } - - return i1; } } diff --git a/src/RageSoundReader_Vorbisfile.cpp b/src/RageSoundReader_Vorbisfile.cpp index 78972aa357..d47e3d00cb 100644 --- a/src/RageSoundReader_Vorbisfile.cpp +++ b/src/RageSoundReader_Vorbisfile.cpp @@ -158,7 +158,7 @@ int RageSoundReader_Vorbisfile::Read( float *buf, int iFrames ) /* The timestamps moved backwards. Ignore it. This file probably * won't sync correctly. */ LOG->Trace( "p ahead %p %i < %i, we're ahead by %i", - this, curofs, read_offset, read_offset-curofs ); + static_cast(this), curofs, read_offset, read_offset-curofs ); read_offset = curofs; } else if( curofs > read_offset ) diff --git a/src/RageSurface.cpp b/src/RageSurface.cpp index 2967d1ff49..5800e9b7a4 100644 --- a/src/RageSurface.cpp +++ b/src/RageSurface.cpp @@ -41,21 +41,19 @@ RageSurfaceFormat::RageSurfaceFormat(): Rmask(Mask[0]), Gmask(Mask[1]), Bmask(Mask[2]), Amask(Mask[3]), Rshift(Shift[0]), Gshift(Shift[1]), Bshift(Shift[2]), Ashift(Shift[3]) { - palette = nullptr; } RageSurfaceFormat::RageSurfaceFormat( const RageSurfaceFormat &cpy ): Rmask(Mask[0]), Gmask(Mask[1]), Bmask(Mask[2]), Amask(Mask[3]), Rshift(Shift[0]), Gshift(Shift[1]), Bshift(Shift[2]), Ashift(Shift[3]) { - memcpy( this, &cpy, sizeof(RageSurfaceFormat) ); + BytesPerPixel = cpy.BytesPerPixel; + BitsPerPixel = cpy.BitsPerPixel; + Mask = cpy.Mask; + Shift = cpy.Shift; + Loss = cpy.Loss; if( palette ) - palette = new RageSurfacePalette( *palette ); -} - -RageSurfaceFormat::~RageSurfaceFormat() -{ - delete palette; + palette = std::make_unique(*palette); } void RageSurfaceFormat::GetRGB( uint32_t val, uint8_t *r, uint8_t *g, uint8_t *b ) const @@ -98,7 +96,7 @@ bool RageSurfaceFormat::operator== ( const RageSurfaceFormat &rhs ) const return false; if( BytesPerPixel == 1 ) - if( memcmp( palette, rhs.palette, sizeof(RageSurfaceFormat) ) ) + if( memcmp( palette.get(), rhs.palette.get(), sizeof(RageSurfaceFormat) ) ) return false; return true; @@ -191,7 +189,7 @@ void SetupFormat( RageSurfaceFormat &fmt, // Loss for paletted textures is zero; the actual palette entries are 8-bit. ZERO( fmt.Loss ); - fmt.palette = new RageSurfacePalette; + fmt.palette = std::make_unique(); fmt.palette->ncolors = 256; } else diff --git a/src/RageSurface.h b/src/RageSurface.h index 7d95f35ffb..cac482672b 100644 --- a/src/RageSurface.h +++ b/src/RageSurface.h @@ -3,6 +3,9 @@ #ifndef RAGE_SURFACE_H #define RAGE_SURFACE_H +#include +#include + /* XXX remove? */ struct RageSurfaceColor { @@ -40,16 +43,16 @@ struct RageSurfaceFormat { RageSurfaceFormat(); RageSurfaceFormat( const RageSurfaceFormat &cpy ); - ~RageSurfaceFormat(); + ~RageSurfaceFormat() = default; int32_t BytesPerPixel; int32_t BitsPerPixel; - uint32_t Mask[4]; - uint32_t Shift[4]; - uint8_t Loss[4]; + std::array Mask; + std::array Shift; + std::array Loss; uint32_t &Rmask, &Gmask, &Bmask, &Amask; /* deprecated */ uint32_t &Rshift, &Gshift, &Bshift, &Ashift; /* deprecated */ - RageSurfacePalette *palette; + std::unique_ptr palette; void GetRGB( uint32_t val, uint8_t *r, uint8_t *g, uint8_t *b ) const; diff --git a/src/RageSurfaceUtils.cpp b/src/RageSurfaceUtils.cpp index b079e43134..428b81af81 100644 --- a/src/RageSurfaceUtils.cpp +++ b/src/RageSurfaceUtils.cpp @@ -12,7 +12,7 @@ uint32_t RageSurfaceUtils::decodepixel( const uint8_t *p, int bpp ) case 1: return *p; case 2: return *(uint16_t *)p; case 3: - if( BYTE_ORDER == BIG_ENDIAN ) + if constexpr ( Endian::big ) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; @@ -29,7 +29,7 @@ void RageSurfaceUtils::encodepixel( uint8_t *p, int bpp, uint32_t pixel ) case 1: *p = uint8_t(pixel); break; case 2: *(uint16_t *)p = uint16_t(pixel); break; case 3: - if( BYTE_ORDER == BIG_ENDIAN ) + if constexpr ( Endian::big ) { p[0] = uint8_t((pixel >> 16) & 0xff); p[1] = uint8_t((pixel >> 8) & 0xff); @@ -518,10 +518,10 @@ static bool blit_rgba_to_rgba( const RageSurface *src_surf, const RageSurface *d const int srcskip = src_surf->pitch - width*src_surf->format->BytesPerPixel; const int dstskip = dst_surf->pitch - width*dst_surf->format->BytesPerPixel; - const uint32_t *src_shifts = src_surf->format->Shift; - const uint32_t *dst_shifts = dst_surf->format->Shift; - const uint32_t *src_masks = src_surf->format->Mask; - const uint32_t *dst_masks = dst_surf->format->Mask; + const auto &src_shifts = src_surf->format->Shift; + const auto &dst_shifts = dst_surf->format->Shift; + const auto &src_masks = src_surf->format->Mask; + const auto &dst_masks = dst_surf->format->Mask; uint8_t lookup[4][256]; for( int c = 0; c < 4; ++c ) @@ -833,44 +833,38 @@ RageSurface *RageSurfaceUtils::LoadSurface( RString file ) * two bits are the alpha component. * * This gives us a generic way to handle arbitrary 8-bit texture formats. */ -RageSurface *RageSurfaceUtils::PalettizeToGrayscale( const RageSurface *src_surf, int GrayBits, int AlphaBits ) +RageSurface *RageSurfaceUtils::PalettizeToGrayscale( const RageSurface *src_surf, uint32_t GrayBits, uint32_t AlphaBits ) { AlphaBits = std::min( AlphaBits, 8-src_surf->format->Loss[3] ); - const int TotalBits = GrayBits + AlphaBits; + const auto TotalBits = GrayBits + AlphaBits; ASSERT( TotalBits <= 8 ); RageSurface *dst_surf = CreateSurface(src_surf->w, src_surf->h, 8, 0,0,0,0 ); // Set up the palette. - const int TotalColors = 1 << TotalBits; - const int Ivalues = 1 << GrayBits; // number of intensity values - const int Ishift = 0; // intensity shift - const int Imask = ((1 << GrayBits) - 1) << Ishift; // intensity mask - const int Iloss = 8-GrayBits; + const auto TotalColors = 1u << TotalBits; + const auto Ivalues = 1u << GrayBits; // number of intensity values + const auto Ishift = 0u; // intensity shift + const auto Imask = ((1u << GrayBits) - 1u) << Ishift; // intensity mask + const auto Iloss = 8u-GrayBits; - const int Avalues = 1 << AlphaBits; // number of alpha values - const int Ashift = GrayBits; // alpha shift - const int Amask = ((1 << AlphaBits) - 1) << Ashift; // alpha mask - const int Aloss = 8-AlphaBits; + const auto Avalues = 1u << AlphaBits; // number of alpha values + const auto Ashift = GrayBits; // alpha shift + const auto Amask = ((1u << AlphaBits) - 1u) << Ashift; // alpha mask + const auto Aloss = 8u-AlphaBits; - for( int index = 0; index < TotalColors; ++index ) + for( size_t index = 0; index < TotalColors; ++index ) { - const int I = (index & Imask) >> Ishift; - const int A = (index & Amask) >> Ashift; + const auto I = (index & Imask) >> Ishift; + const auto A = (index & Amask) >> Ashift; - int ScaledI; - if( Ivalues == 1 ) - ScaledI = 255; // if only one intensity value, always fullbright - else - ScaledI = clamp( lrintf(I * (255.0f / (Ivalues-1))), 0L, 255L ); + // if only one intensity value, always fullbright + const auto ScaledI = Ivalues == 1 ? 255 : clamp( lrintf(I * (255.0f / (Ivalues-1))), 0L, 255L ); - int ScaledA; - if( Avalues == 1 ) - ScaledA = 255; // if only one alpha value, always opaque - else - ScaledA = clamp( lrintf(A * (255.0f / (Avalues-1))), 0L, 255L ); + // if only one alpha value, always opaque + const auto ScaledA = Avalues == 1 ? 255 : clamp( lrintf(A * (255.0f / (Avalues-1))), 0L, 255L ); RageSurfaceColor c; c.r = uint8_t(ScaledI); diff --git a/src/RageSurfaceUtils.h b/src/RageSurfaceUtils.h index 533d74e11a..a39dbcffe4 100644 --- a/src/RageSurfaceUtils.h +++ b/src/RageSurfaceUtils.h @@ -55,7 +55,7 @@ namespace RageSurfaceUtils RageSurface *LoadSurface( RString file ); /* Quickly palettize to an gray/alpha texture. */ - RageSurface *PalettizeToGrayscale( const RageSurface *src_surf, int GrayBits, int AlphaBits ); + RageSurface *PalettizeToGrayscale( const RageSurface *src_surf, uint32_t GrayBits, uint32_t AlphaBits ); RageSurface *MakeDummySurface( int height, int width ); diff --git a/src/RageSurfaceUtils_Palettize.cpp b/src/RageSurfaceUtils_Palettize.cpp index 458267e598..d3afdd1e0e 100644 --- a/src/RageSurfaceUtils_Palettize.cpp +++ b/src/RageSurfaceUtils_Palettize.cpp @@ -156,7 +156,7 @@ void RageSurfaceUtils::Palettize( RageSurface *&pImg, int iColors, bool bDither // Rescale the palette colors to a maxval of 255. { - RageSurfacePalette *pal = pRet->format->palette; + auto& pal = pRet->format->palette; for( int x = 0; x < pal->ncolors; ++x ) { // This is really just PAM_DEPTH() broken out for the palette. diff --git a/src/RageSurface_Load_GIF.cpp b/src/RageSurface_Load_GIF.cpp index 7c8a5e3d2f..8eb46dc45f 100644 --- a/src/RageSurface_Load_GIF.cpp +++ b/src/RageSurface_Load_GIF.cpp @@ -136,8 +136,8 @@ RageSurfaceUtils::OpenResult RageSurface_Load_GIF( const RString &sPath, RageSur imageCount, imageCount > 1 ? "s" : ""); return RageSurfaceUtils::OPEN_FATAL_ERROR; } + [[fallthrough]]; } - case '!': { /* Extension */ diff --git a/src/RageSurface_Load_JPEG.cpp b/src/RageSurface_Load_JPEG.cpp index 48f028c150..d839263d10 100644 --- a/src/RageSurface_Load_JPEG.cpp +++ b/src/RageSurface_Load_JPEG.cpp @@ -27,10 +27,13 @@ struct my_jpeg_error_mgr { struct jpeg_error_mgr pub; /* "public" fields */ + uint8_t pad1[8]; // Explicitly add padding that's implicitly added by the compiler + jmp_buf setjmp_buffer; /* for return to caller */ char errorbuf[JMSG_LENGTH_MAX]; -}; + uint8_t pad2[8]; // Explicitly add padding that's implicitly added by the compiler +}; void my_output_message( j_common_ptr cinfo ) { diff --git a/src/RageSurface_Load_PNG.cpp b/src/RageSurface_Load_PNG.cpp index 7d4665136b..dfa5444fb3 100644 --- a/src/RageSurface_Load_PNG.cpp +++ b/src/RageSurface_Load_PNG.cpp @@ -236,7 +236,7 @@ static RageSurface *RageSurface_Load_PNG( RageFile *f, const char *fn, char erro ASSERT( img != nullptr ); row_pointers = new png_byte*[height]; - CHECKPOINT_M( ssprintf("%p",row_pointers) ); + CHECKPOINT_M( ssprintf("%p",static_cast(row_pointers)) ); for( unsigned y = 0; y < height; ++y ) { diff --git a/src/RageSurface_Load_XPM.cpp b/src/RageSurface_Load_XPM.cpp index fdf9f3ab58..74886b9120 100644 --- a/src/RageSurface_Load_XPM.cpp +++ b/src/RageSurface_Load_XPM.cpp @@ -53,7 +53,7 @@ RageSurface *RageSurface_Load_XPM( char * const *xpm, RString &error ) continue; RString clr = color.substr( color_length+4 ); - int r, g, b; + unsigned int r, g, b; if( sscanf( clr, "%2x%2x%2x", &r, &g, &b ) != 3 ) continue; RageSurfaceColor colorval; diff --git a/src/RageTextureManager.cpp b/src/RageTextureManager.cpp index 7840ab4bac..07061ddfdb 100644 --- a/src/RageTextureManager.cpp +++ b/src/RageTextureManager.cpp @@ -254,27 +254,8 @@ void RageTextureManager::DeleteTexture( RageTexture *t ) m_texture_ids_by_pointer.erase(id_entry); return; } - else - { - FAIL_M("Tried to delete a texture that wasn't in the ids by pointer list."); - for (std::map::iterator iter = m_mapPathToTexture.begin(); iter != m_mapPathToTexture.end(); ++iter) - { - if( iter->second == t ) - { - m_mapPathToTexture.erase( iter ); // remove map entry - SAFE_DELETE( t ); // free the texture - std::map::iterator tex_update_entry= - m_textures_to_update.find(iter->first); - if(tex_update_entry != m_textures_to_update.end()) - { - m_textures_to_update.erase(tex_update_entry); - } - return; - } - } - } - FAIL_M("Tried to delete a texture that wasn't loaded"); + FAIL_M("Tried to delete a texture that wasn't in the ids by pointer list."); } void RageTextureManager::GarbageCollect( GCType type ) diff --git a/src/RageTypes.h b/src/RageTypes.h index 6a2ea018cc..4b13941783 100644 --- a/src/RageTypes.h +++ b/src/RageTypes.h @@ -3,6 +3,8 @@ #ifndef RAGETYPES_H #define RAGETYPES_H +#include + #include "EnumHelper.h" enum BlendMode @@ -101,7 +103,7 @@ struct lua_State; struct RageVector2 { public: - RageVector2(): x(0), y(0) {} + RageVector2() = default; RageVector2( const float * f ): x(f[0]), y(f[1]) {} RageVector2( float x1, float y1 ): x(x1), y(y1) {} @@ -123,14 +125,14 @@ public: friend RageVector2 operator * ( float f, const RageVector2& other ) { return other*f; } - float x, y; + float x{0}, y{0}; }; struct RageVector3 { public: - RageVector3(): x(0), y(0), z(0) {} + RageVector3() = default; RageVector3( const float * f ): x(f[0]), y(f[1]), z(f[2]) {} RageVector3( float x1, float y1, float z1 ): x(x1), y(y1), z(z1) {} @@ -152,14 +154,14 @@ public: friend RageVector3 operator * ( float f, const RageVector3& other ) { return other*f; } - float x, y, z; + float x{0}, y{0}, z{0}; }; struct RageVector4 { public: - RageVector4(): x(0), y(0), z(0), w(0) {} + RageVector4() = default; RageVector4( const float * f ): x(f[0]), y(f[1]), z(f[2]), w(f[3]) {} RageVector4( float x1, float y1, float z1, float w1 ): x(x1), y(y1), z(z1), w(w1) {} @@ -181,15 +183,23 @@ public: friend RageVector4 operator * ( float f, const RageVector4& other ) { return other*f; } - float x, y, z, w; + float x{0}, y{0}, z{0}, w{0}; }; struct RageColor { public: - RageColor(): r(0), g(0), b(0), a(0) {} + RageColor() = default; explicit RageColor( const float * f ): r(f[0]), g(f[1]), b(f[2]), a(f[3]) {} RageColor( float r1, float g1, float b1, float a1 ): r(r1), g(g1), b(b1), a(a1) {} + + RageColor& operator=( const RageVector4& rv4 ) { + r = rv4.x; + g = rv4.y; + b = rv4.z; + a = rv4.w; + return *this; + } // casting operator float* () { return &r; }; @@ -228,7 +238,7 @@ public: if( result == 4 ) return true; - int ir=255, ib=255, ig=255, ia=255; + unsigned int ir=255, ib=255, ig=255, ia=255; result = sscanf( str, "#%2x%2x%2x%2x", &ir, &ig, &ib, &ia ); if( result >= 3 ) { @@ -251,7 +261,7 @@ public: void FromStack( lua_State *L, int iPos ); void FromStackCompat( lua_State *L, int iPos ); - float r, g, b, a; + float r{0}, g{0}, b{0}, a{0}; }; /* Convert floating-point 0..1 value to integer 0..255 value. * @@ -310,9 +320,9 @@ inline unsigned char FTOC(float a) class RageVColor { public: - uint8_t b,g,r,a; // specific ordering required by Direct3D + uint8_t b{0},g{0},r{0},a{0}; // specific ordering required by Direct3D - RageVColor(): b(0), g(0), r(0), a(0) { } + RageVColor() = default; RageVColor(const RageColor &rc): b(0), g(0), r(0), a(0) { *this = rc; } RageVColor &operator= (const RageColor &rc) { @@ -327,7 +337,7 @@ namespace StepMania class Rect { public: - Rect(): left(0), top(0), right(0), bottom(0) {} + Rect() = default; Rect(T l, T t, T r, T b): left(l), top(t), right(r), bottom(b) {} T GetWidth() const { return right-left; }; @@ -347,7 +357,7 @@ public: } bool operator!=( const Rect &other ) const { return !operator==(other); } - T left, top, right, bottom; + T left{}, top{}, right{}, bottom{}; }; } typedef StepMania::Rect RectI; @@ -357,11 +367,11 @@ typedef StepMania::Rect RectF; * have the same layout that D3D expects. */ struct RageSpriteVertex // has color { - RageSpriteVertex(): p(), n(), c(), t() {} - RageVector3 p; // position - RageVector3 n; // normal - RageVColor c; // diffuse color - RageVector2 t; // texture coordinates + RageSpriteVertex() = default; + RageVector3 p{}; // position + RageVector3 n{}; // normal + RageVColor c{}; // diffuse color + RageVector2 t{}; // texture coordinates }; void lerp_rage_color(RageColor& out, RageColor const& a, RageColor const& b, float t); @@ -369,19 +379,12 @@ void WeightedAvergeOfRSVs(RageSpriteVertex& average_out, RageSpriteVertex const& struct RageModelVertex // doesn't have color. Relies on material color { - /* Zero out by default. */ - RageModelVertex(): - p(0,0,0), - n(0,0,0), - t(0,0), - bone(0), - TextureMatrixScale(1,1) - { } - RageVector3 p; // position - RageVector3 n; // normal - RageVector2 t; // texture coordinates - int8_t bone; - RageVector2 TextureMatrixScale; // usually 1,1 + RageModelVertex() = default; + RageVector3 p{}; // position + RageVector3 n{}; // normal + RageVector2 t{}; // texture coordinates + int8_t bone{0}; + RageVector2 TextureMatrixScale{1,1}; // usually 1,1 }; @@ -394,9 +397,8 @@ struct RageModelVertex // doesn't have color. Relies on material color struct RageMatrix { public: - RageMatrix() {}; + RageMatrix() = default; RageMatrix( const float *f ) { for(int i=0; i<4; i++) for(int j=0; j<4; j++) m[j][i]=f[j*4+i]; } - RageMatrix( const RageMatrix& other ) { for(int i=0; i<4; i++) for(int j=0; j<4; j++) m[j][i]=other.m[j][i]; } RageMatrix( float v00, float v01, float v02, float v03, float v10, float v11, float v12, float v13, float v20, float v21, float v22, float v23, @@ -407,12 +409,12 @@ public: float operator () ( int iRow, int iCol ) const { return m[iCol][iRow]; } // casting operators - operator float* () { return m[0]; } - operator const float* () const { return m[0]; } + operator float* () { return m[0].data(); } + operator const float* () const { return m[0].data(); } RageMatrix GetTranspose() const; - float m[4][4]; + std::array, 4> m{}; }; #endif diff --git a/src/RageUtil.cpp b/src/RageUtil.cpp index 76174c8f92..e68bae4ec9 100644 --- a/src/RageUtil.cpp +++ b/src/RageUtil.cpp @@ -3,6 +3,7 @@ #include "RageMath.h" #include "RageLog.h" #include "RageFile.h" +#include "RageFileDriverDirectHelpers.h" #include "RageSoundReader_FileReader.h" #include "LocalizedString.h" #include "LuaBinding.h" @@ -1086,7 +1087,7 @@ bool GetCommandlineArgument( const RString &option, RString *argument, int iInde RString GetCwd() { char buf[PATH_MAX]; - bool ret = getcwd(buf, PATH_MAX) != nullptr; + bool ret = DoGetCwd(buf, PATH_MAX) != nullptr; ASSERT(ret); return buf; } @@ -1980,7 +1981,7 @@ void ReplaceEntityText( RString &sText, const std::map &m ) { RString sFind; - for (std::pair const &c : m) + for (const auto &c : m) sFind.append( 1, c.first ); RString sRet; @@ -2058,11 +2059,8 @@ void Replace_Unicode_Markers( RString &sText ) continue; p++; - int iNum; - if( bHex ) - sscanf( sText.c_str()+iPos, "&x%x;", &iNum ); - else - sscanf( sText.c_str()+iPos, "&#%i;", &iNum ); + unsigned int iNum; + sscanf( sText.c_str()+iPos, bHex ? "&x%x;" : "&#%u;", &iNum ); if( iNum > 0xFFFF ) iNum = INVALID_CHAR; @@ -2509,7 +2507,7 @@ int LuaFunc_JsonEncode(lua_State* L) Json::Value array(Json::arrayValue); array.resize(len); - for (int i = 0; i < len; i++) + for (unsigned int i = 0; i < len; i++) { lua_rawgeti(L, index, i + 1); array[i] = convert(-1); @@ -2615,7 +2613,7 @@ int LuaFunc_JsonDecode(lua_State* L) else if (val.isArray()) { lua_createtable(L, val.size(), 0); - for (int i = 0; i < val.size(); i++) + for (unsigned int i = 0; i < val.size(); i++) { convert(val[i]); lua_rawseti(L, -2, i + 1); diff --git a/src/RageUtil.h b/src/RageUtil.h index ce046d54c6..de0b894181 100644 --- a/src/RageUtil.h +++ b/src/RageUtil.h @@ -3,6 +3,8 @@ #ifndef RAGE_UTIL_H #define RAGE_UTIL_H +#include +#include #include #include #include @@ -25,7 +27,7 @@ class RageFileDriver; extern const RString CUSTOM_SONG_PATH; /** @brief If outside the range from low to high, bring it within range. */ -#define clamp(val,low,high) ( std::max( (low), std::min((val),(high)) ) ) +#define clamp(val,low,high) std::clamp( val, low, high ) /** * @brief Scales x so that l1 corresponds to l2 and h1 corresponds to h2. @@ -183,6 +185,21 @@ static inline T enum_cycle( T val, int iMax, int iAmt = 1 ) return static_cast( iVal ); } +namespace Endian +{ + // When std::endian is supported by all desired compilers, we can eliminate the #ifdefs + // (At least) the current compiler used for the Ubuntu 20.04 build does not support this. +#if defined(__cpp_lib_endian) + inline constexpr bool little = std::endian::native == std::endian::little; + inline constexpr bool big = std::endian::native == std::endian::big; +#elif defined(_WIN32) + inline constexpr bool little = false; + inline constexpr bool big = true; +#else + inline constexpr bool little = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__; + inline constexpr bool big = __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__; +#endif +} /* We only have unsigned swaps; byte swapping a signed value doesn't make sense. * @@ -215,21 +232,12 @@ inline uint16_t Swap16( uint16_t n ) } #endif -#if defined(ENDIAN_LITTLE) -inline uint32_t Swap32LE( uint32_t n ) { return n; } -inline uint32_t Swap24LE( uint32_t n ) { return n; } -inline uint16_t Swap16LE( uint16_t n ) { return n; } -inline uint32_t Swap32BE( uint32_t n ) { return Swap32( n ); } -inline uint32_t Swap24BE( uint32_t n ) { return Swap24( n ); } -inline uint16_t Swap16BE( uint16_t n ) { return Swap16( n ); } -#else -inline uint32_t Swap32BE( uint32_t n ) { return n; } -inline uint32_t Swap24BE( uint32_t n ) { return n; } -inline uint16_t Swap16BE( uint16_t n ) { return n; } -inline uint32_t Swap32LE( uint32_t n ) { return Swap32( n ); } -inline uint32_t Swap24LE( uint32_t n ) { return Swap24( n ); } -inline uint16_t Swap16LE( uint16_t n ) { return Swap16( n ); } -#endif +inline uint32_t Swap32LE( uint32_t n ) { return Endian::little ? n : Swap32( n ); } +inline uint32_t Swap24LE( uint32_t n ) { return Endian::little ? n : Swap24( n ); } +inline uint16_t Swap16LE( uint16_t n ) { return Endian::little ? n : Swap16( n ); } +inline uint32_t Swap32BE( uint32_t n ) { return Endian::big ? n : Swap32( n ); } +inline uint32_t Swap24BE( uint32_t n ) { return Endian::big ? n : Swap24( n ); } +inline uint16_t Swap16BE( uint16_t n ) { return Endian::big ? n : Swap16( n ); } class MersenneTwister : public std::mt19937 { diff --git a/src/RageUtil_AutoPtr.h b/src/RageUtil_AutoPtr.h index 44f8d31299..4ba59b6bae 100644 --- a/src/RageUtil_AutoPtr.h +++ b/src/RageUtil_AutoPtr.h @@ -176,6 +176,8 @@ public: } #endif + bool isNull() const { return !m_pPtr; } + private: T *m_pPtr; diff --git a/src/RageUtil_BackgroundLoader.cpp b/src/RageUtil_BackgroundLoader.cpp index 48efc1d5a9..edc6abcee1 100644 --- a/src/RageUtil_BackgroundLoader.cpp +++ b/src/RageUtil_BackgroundLoader.cpp @@ -23,7 +23,7 @@ BackgroundLoader::BackgroundLoader(): if( !g_bEnableBackgroundLoading ) return; - m_sCachePathPrefix = ssprintf( "@mem/%p", this ); + m_sCachePathPrefix = ssprintf( "@mem/%p", static_cast(this) ); m_bShutdownThread = false; m_sThreadIsActive = m_sThreadShouldAbort = false; diff --git a/src/RageUtil_CircularBuffer.h b/src/RageUtil_CircularBuffer.h index 7dc0863326..93f8ea3649 100644 --- a/src/RageUtil_CircularBuffer.h +++ b/src/RageUtil_CircularBuffer.h @@ -131,7 +131,8 @@ public: void clear() { - read_pos = write_pos = 0; + read_pos = 0; + write_pos = 0; } /* Indicate that n elements have been written. */ diff --git a/src/ScoreDisplayRave.cpp b/src/ScoreDisplayRave.cpp index 7154a1dc9b..14ab48f601 100644 --- a/src/ScoreDisplayRave.cpp +++ b/src/ScoreDisplayRave.cpp @@ -65,7 +65,7 @@ void ScoreDisplayRave::Update( float fDelta ) m_textLevel.SetText( ssprintf("%d",level+1) ); } - float fPercent = fLevel - level; + float fPercent = fLevel - Enum::to_integral(level); m_sprMeter[level].SetCropRight( 1-fPercent ); } diff --git a/src/ScoreKeeperRave.cpp b/src/ScoreKeeperRave.cpp index 1c4af32f50..acd8c5de8a 100644 --- a/src/ScoreKeeperRave.cpp +++ b/src/ScoreKeeperRave.cpp @@ -116,7 +116,7 @@ void ScoreKeeperRave::AddSuperMeterDelta( float fUnscaledPercentChange ) { if( PREFSMAN->m_bMercifulDrain && fUnscaledPercentChange<0 ) { - float fSuperPercentage = m_pPlayerState->m_fSuperMeter / NUM_ATTACK_LEVELS; + float fSuperPercentage = m_pPlayerState->m_fSuperMeter / Enum::to_integral(NUM_ATTACK_LEVELS); fUnscaledPercentChange *= SCALE( fSuperPercentage, 0.f, 1.f, 0.5f, 1.f); } diff --git a/src/ScreenEdit.cpp b/src/ScreenEdit.cpp index 8ddf866717..1d7a9137c5 100644 --- a/src/ScreenEdit.cpp +++ b/src/ScreenEdit.cpp @@ -3238,6 +3238,7 @@ bool ScreenEdit::InputPlay( const InputEventPlus &input, EditButton EditB ) break; // fall through to input handling logic: + [[fallthrough]]; case PLAYER_1: { switch( gbt ) @@ -5255,12 +5256,12 @@ void ScreenEdit::HandleAlterMenuChoice(AlterMenuChoice c, const std::vector case tempo: { // This affects all steps. - AlterType at = (AlterType)answers[c]; + const auto tt = static_cast(answers[c]); float fScale = -1; - switch( at ) + switch( tt ) { - DEFAULT_FAIL( at ); + DEFAULT_FAIL( tt ); case compress_2x: fScale = 0.5f; break; case compress_3_2: fScale = 2.0f/3; break; case compress_4_3: fScale = 0.75f; break; diff --git a/src/ScreenGameplayLesson.cpp b/src/ScreenGameplayLesson.cpp index b21599abb9..74450dd6ef 100644 --- a/src/ScreenGameplayLesson.cpp +++ b/src/ScreenGameplayLesson.cpp @@ -113,7 +113,7 @@ void ScreenGameplayLesson::HandleScreenMessage( const ScreenMessage SM ) ResetAndRestartCurrentSong(); m_Try = (Try)(m_Try+1); - MESSAGEMAN->Broadcast( (MessageID)(Message_LessonTry1+m_Try) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_LessonTry1+Enum::to_integral(m_Try)) ); } else { @@ -164,7 +164,7 @@ void ScreenGameplayLesson::ChangeLessonPage( int iDir ) ResetAndRestartCurrentSong(); - MESSAGEMAN->Broadcast( (MessageID)(Message_LessonTry1+m_Try) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_LessonTry1+Enum::to_integral(m_Try)) ); // Change back to the current autoplay setting (in most cases, human controlled). FOREACH_EnabledPlayerInfo( m_vPlayerInfo, pi ) diff --git a/src/ScreenOptions.cpp b/src/ScreenOptions.cpp index 7eea338622..943964854e 100644 --- a/src/ScreenOptions.cpp +++ b/src/ScreenOptions.cpp @@ -1269,7 +1269,7 @@ bool ScreenOptions::MenuLeft( const InputEventPlus &input ) ChangeValueInRowRelative(m_iCurrentRow[input.pn],input.pn,-1, input.type != IET_FIRST_PRESS); PlayerNumber pn = input.pn; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+Enum::to_integral(pn)) ); return true; } @@ -1281,7 +1281,7 @@ bool ScreenOptions::MenuRight( const InputEventPlus &input ) ChangeValueInRowRelative(m_iCurrentRow[input.pn], input.pn,+1, input.type != IET_FIRST_PRESS); PlayerNumber pn = input.pn; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+Enum::to_integral(pn)) ); return true; } @@ -1289,7 +1289,7 @@ bool ScreenOptions::MenuUp( const InputEventPlus &input ) { MenuUpDown( input, -1 ); PlayerNumber pn = input.pn; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+Enum::to_integral(pn)) ); return true; } @@ -1297,7 +1297,7 @@ bool ScreenOptions::MenuDown( const InputEventPlus &input ) { MenuUpDown( input, +1 ); PlayerNumber pn = input.pn; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+Enum::to_integral(pn)) ); return true; } diff --git a/src/ScreenOptionsMasterPrefs.cpp b/src/ScreenOptionsMasterPrefs.cpp index 6efe407cc5..047d54c087 100644 --- a/src/ScreenOptionsMasterPrefs.cpp +++ b/src/ScreenOptionsMasterPrefs.cpp @@ -53,7 +53,17 @@ int FindClosestEntry( T value, const U *mapping, unsigned cnt ) for( unsigned i = 0; i < cnt; ++i ) { - const U val = mapping[i]; + // Need to use if constexpr here so the compiler doesn't even + // attempt to parse the else branch for enums + const T val = [&]{ + if constexpr (std::is_enum::value) { + return Enum::to_integral(mapping[i]); + } + else { + return mapping[i]; + } + }(); + float dist = value < val? (float)(val-value):(float)(value-val); if( have_best && best_dist < dist ) continue; @@ -64,10 +74,7 @@ int FindClosestEntry( T value, const U *mapping, unsigned cnt ) iBestIndex = i; } - if( have_best ) - return iBestIndex; - else - return 0; + return iBestIndex; } template @@ -845,7 +852,7 @@ static void InitializeConfOptions() ADD(ConfOption("CustomSongsMaxCount", CustomSongsCount, "10", "20", "30", "40", "50", "60", "70", "80", "90", "100", "1000")); ADD(ConfOption("CustomSongsLoadTimeout", CustomSongsLoadTimeout, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "20", "30", "1000")); ADD(ConfOption("CustomSongsMaxSeconds", CustomSongsMaxSeconds, "60", "90", "120", "150", "180", "210", "240", "10000")); - ADD(ConfOption("CustomSongsMaxMegabytes", CustomSongsLoadTimeout, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "20", "30", "1000")); + ADD(ConfOption("CustomSongsMaxMegabytes", CustomSongsMaxMegabytes, "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "20", "30", "1000")); // Machine options ADD( ConfOption( "MenuTimer", MovePref, "Off","On" ) ); diff --git a/src/ScreenSelectMaster.cpp b/src/ScreenSelectMaster.cpp index e4088ae6db..571a8c90aa 100644 --- a/src/ScreenSelectMaster.cpp +++ b/src/ScreenSelectMaster.cpp @@ -374,7 +374,7 @@ void ScreenSelectMaster::HandleScreenMessage( const ScreenMessage SM ) if( SM == SM_PlayPostSwitchPage ) { - int iNewChoice = m_iChoice[ GAMESTATE->GetMasterPlayerNumber() ]; + const auto iNewChoice = m_iChoice[ GAMESTATE->GetMasterPlayerNumber() ]; Page newPage = GetPage( iNewChoice ); Message msg("PostSwitchPage"); @@ -390,7 +390,7 @@ void ScreenSelectMaster::HandleScreenMessage( const ScreenMessage SM ) { for (PlayerNumber const &p : vpns) { - int iChoice = m_iChoice[p]; + const auto iChoice = m_iChoice[p]; m_vsprScroll[p][iChoice]->HandleMessage( msg ); } } @@ -460,7 +460,7 @@ void ScreenSelectMaster::UpdateSelectableChoices() for ( PlayerNumber &p : vpns) { - if(disabled && m_iChoice[p] == c) + if(disabled && m_iChoice[p] == static_cast(c)) { on_unplayable[p]= true; } @@ -503,7 +503,7 @@ bool ScreenSelectMaster::Move( PlayerNumber pn, MenuDir dir ) if( !AnyOptionsArePlayable() ) return false; - int iSwitchToIndex = m_iChoice[pn]; + auto iSwitchToIndex = m_iChoice[pn]; std::set seen; do @@ -540,7 +540,7 @@ bool ScreenSelectMaster::MenuLeft( const InputEventPlus &input ) { m_TrackingRepeatingInput = input.MenuI; m_soundChange.Play(true); - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+Enum::to_integral(pn)) ); MESSAGEMAN->Broadcast( (MessageID)(Message_MenuSelectionChanged) ); // if they use double select @@ -571,7 +571,7 @@ bool ScreenSelectMaster::MenuRight( const InputEventPlus &input ) { m_TrackingRepeatingInput = input.MenuI; m_soundChange.Play(true); - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+Enum::to_integral(pn)) ); MESSAGEMAN->Broadcast( (MessageID)(Message_MenuSelectionChanged) ); // if they use double select @@ -602,7 +602,7 @@ bool ScreenSelectMaster::MenuUp( const InputEventPlus &input ) { m_TrackingRepeatingInput = input.MenuI; m_soundChange.Play(true); - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+Enum::to_integral(pn)) ); MESSAGEMAN->Broadcast( (MessageID)(Message_MenuSelectionChanged) ); // if they use double select @@ -633,7 +633,7 @@ bool ScreenSelectMaster::MenuDown( const InputEventPlus &input ) { m_TrackingRepeatingInput = input.MenuI; m_soundChange.Play(true); - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+Enum::to_integral(pn)) ); MESSAGEMAN->Broadcast( (MessageID)(Message_MenuSelectionChanged) ); // if they use double select @@ -963,7 +963,7 @@ bool ScreenSelectMaster::MenuStart( const InputEventPlus &input ) mc->ApplyToAllPlayers(); // We want to be able to broadcast a Start message to the theme, in // case a themer wants to handle something. -aj - Message msg( MessageIDToString((MessageID)(Message_MenuStartP1+pn)) ); + Message msg( MessageIDToString((MessageID)(Message_MenuStartP1+Enum::to_integral(pn))) ); msg.SetParam( "ScreenEmpty", true ); MESSAGEMAN->Broadcast( msg ); return true; @@ -991,7 +991,7 @@ bool ScreenSelectMaster::MenuStart( const InputEventPlus &input ) if( bAllDone ) { // broadcast MenuStart just like MenuLeft/Right/etc. - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuStartP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuStartP1+Enum::to_integral(pn)) ); this->PostScreenMessage( SM_BeginFadingOut, fSecs );// tell our owner it's time to move on } return true; diff --git a/src/ScreenSelectProfile.cpp b/src/ScreenSelectProfile.cpp index 502038f0c5..326fb0608c 100644 --- a/src/ScreenSelectProfile.cpp +++ b/src/ScreenSelectProfile.cpp @@ -44,7 +44,7 @@ bool ScreenSelectProfile::MenuLeft( const InputEventPlus &input ) return false; } m_TrackingRepeatingInput = input.MenuI; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuLeftP1+Enum::to_integral(pn)) ); return true; } @@ -65,7 +65,7 @@ bool ScreenSelectProfile::MenuRight( const InputEventPlus &input ) return false; } m_TrackingRepeatingInput = input.MenuI; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuRightP1+Enum::to_integral(pn)) ); return true; } @@ -86,7 +86,7 @@ bool ScreenSelectProfile::MenuUp( const InputEventPlus &input ) return false; } m_TrackingRepeatingInput = input.MenuI; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuUpP1+Enum::to_integral(pn)) ); return true; } @@ -107,7 +107,7 @@ bool ScreenSelectProfile::MenuDown( const InputEventPlus &input ) return false; } m_TrackingRepeatingInput = input.MenuI; - MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+pn) ); + MESSAGEMAN->Broadcast( (MessageID)(Message_MenuDownP1+Enum::to_integral(pn)) ); return true; } diff --git a/src/ScreenTestSound.cpp b/src/ScreenTestSound.cpp index 6786092674..559cf21688 100644 --- a/src/ScreenTestSound.cpp +++ b/src/ScreenTestSound.cpp @@ -198,12 +198,13 @@ bool ScreenTestSound::Input( const InputEventPlus &input ) break; */ default: - return false; + break; } - default: - return false; + default: + break; } - return true; + + return false; } /* diff --git a/src/SongManager.cpp b/src/SongManager.cpp index 5a5075d49a..94a1c3102c 100644 --- a/src/SongManager.cpp +++ b/src/SongManager.cpp @@ -575,13 +575,8 @@ void SongManager::UnlistSong(Song *song) // remove all occurences of the song in each of our song vectors std::vector* songVectors[3] = { &m_pSongs, &m_pPopularSongs, &m_pShuffledSongs }; for (int songVecIdx=0; songVecIdx<3; ++songVecIdx) { - std::vector& v = *songVectors[songVecIdx]; - for (int i=0; im_pCurSong.Get(), + static_cast(GAMESTATE->m_pCurSong.Get()), GAMESTATE->m_pCurSong? GAMESTATE->m_pCurSong->GetSongDir().c_str():"", GAMESTATE->m_pCurSong? GAMESTATE->m_pCurSong->m_sGroupName.c_str():"") ); diff --git a/src/SongOptions.cpp b/src/SongOptions.cpp index 5479055666..e547bc6678 100644 --- a/src/SongOptions.cpp +++ b/src/SongOptions.cpp @@ -23,22 +23,6 @@ XToString( SoundEffectType ); XToLocalizedString( SoundEffectType ); LuaXType( SoundEffectType ); -void SongOptions::Init() -{ - m_bAssistClap = false; - m_bAssistMetronome = false; - m_fMusicRate = 1.0f; - m_SpeedfMusicRate = 1.0f; - m_fHaste = 0.0f; - m_SpeedfHaste = 1.0f; - m_AutosyncType = AutosyncType_Off; - m_SoundEffectType = SoundEffectType_Off; - m_bStaticBackground = false; - m_bRandomBGOnly = false; - m_bSaveScore = true; - m_bSaveReplay = false; // don't save replays by default? -} - void SongOptions::Approach( const SongOptions& other, float fDeltaSeconds ) { #define APPROACH( opt ) \ diff --git a/src/SongOptions.h b/src/SongOptions.h index 1e26952810..d6752e9b19 100644 --- a/src/SongOptions.h +++ b/src/SongOptions.h @@ -33,30 +33,19 @@ LuaDeclareType( SoundEffectType ); class SongOptions { public: - bool m_bAssistClap; - bool m_bAssistMetronome; - float m_fMusicRate, m_SpeedfMusicRate; - float m_fHaste, m_SpeedfHaste; - AutosyncType m_AutosyncType; - SoundEffectType m_SoundEffectType; - bool m_bStaticBackground; - bool m_bRandomBGOnly; - bool m_bSaveScore; - bool m_bSaveReplay; + bool m_bAssistClap{false}; + bool m_bAssistMetronome{false}; + float m_fMusicRate{1.0f}, m_SpeedfMusicRate{1.0f}; + float m_fHaste{0.0f}, m_SpeedfHaste{1.0f}; + AutosyncType m_AutosyncType{AutosyncType_Off}; + SoundEffectType m_SoundEffectType{SoundEffectType_Off}; + bool m_bStaticBackground{false}; + bool m_bRandomBGOnly{false}; + bool m_bSaveScore{true}; + bool m_bSaveReplay{false}; - /** - * @brief Set up the SongOptions with reasonable defaults. - * - * This is taken from Init(), but uses the intended - * initialization lists. */ - SongOptions(): m_bAssistClap(false), - m_bAssistMetronome(false), m_fMusicRate(1.0f), - m_SpeedfMusicRate(1.0f), m_fHaste(0.0f), - m_SpeedfHaste(1.0f), m_AutosyncType(AutosyncType_Off), - m_SoundEffectType(SoundEffectType_Off), - m_bStaticBackground(false), m_bRandomBGOnly(false), - m_bSaveScore(true), m_bSaveReplay(false) {}; - void Init(); + SongOptions() = default; + void Init() { *this = {}; } void Approach( const SongOptions& other, float fDeltaSeconds ); void GetMods( std::vector &AddTo ) const; void GetLocalizedMods( std::vector &AddTo ) const; diff --git a/src/SongUtil.cpp b/src/SongUtil.cpp index ba26e00428..f75318baee 100644 --- a/src/SongUtil.cpp +++ b/src/SongUtil.cpp @@ -326,7 +326,7 @@ void SongUtil::DeleteDuplicateSteps( Song *pSong, std::vector &vSteps ) continue; LOG->Trace("Removed %p duplicate steps in song \"%s\" with description \"%s\", step author \"%s\", and meter \"%i\"", - s2, pSong->GetSongDir().c_str(), s1->GetDescription().c_str(), s1->GetCredit().c_str(), s1->GetMeter() ); + static_cast(s2), pSong->GetSongDir().c_str(), s1->GetDescription().c_str(), s1->GetCredit().c_str(), s1->GetMeter() ); pSong->DeleteSteps( s2, false ); diff --git a/src/StageStats.cpp b/src/StageStats.cpp index eac4cb0bfe..b04522ae17 100644 --- a/src/StageStats.cpp +++ b/src/StageStats.cpp @@ -314,7 +314,7 @@ bool StageStats::PlayerHasHighScore( PlayerNumber pn ) const PROFILEMAN->GetMachineProfile()->GetCourseHighScoreList(pCourse, pTrail) : PROFILEMAN->GetMachineProfile()->GetStepsHighScoreList(pSong, pSteps); - int iScore = m_player[pn].m_iScore; + const auto iScore = m_player[pn].m_iScore; float fPercentDP = m_player[pn].GetPercentDancePoints(); for( int h=0; h<(int)hsl.vHighScores.size() && hm_iMaxHighScoresPerListForMachine; ++h ) { diff --git a/src/StepsUtil.cpp b/src/StepsUtil.cpp index e2c9762da5..00983c74d9 100644 --- a/src/StepsUtil.cpp +++ b/src/StepsUtil.cpp @@ -65,7 +65,7 @@ void StepsUtil::GetAllMatchingEndless( Song *pSong, const StepsCriteria &stc, st { const std::vector &vSteps = ( stc.m_st == StepsType_Invalid ? pSong->GetAllSteps() : pSong->GetStepsByStepsType( stc.m_st ) ); - int previousSize = out.size(); + const auto previousSize = out.size(); int successful = false; GetAllMatching( pSong, stc, out ); diff --git a/src/ThemeManager.cpp b/src/ThemeManager.cpp index 9967f909e9..c800dc6c31 100644 --- a/src/ThemeManager.cpp +++ b/src/ThemeManager.cpp @@ -880,7 +880,6 @@ try_element_again: GetThemeDirFromName(SpecialFiles::BASE_THEME_NAME).c_str() ); DEFAULT_FAIL( res ); } - FAIL_M( "" ); // Silence gcc 4. } RString ThemeManager::GetPath( ElementCategory category, const RString &sMetricsGroup, const RString &sElement, bool bOptional ) diff --git a/src/TimingData.cpp b/src/TimingData.cpp index a19a2af935..263fe9703c 100644 --- a/src/TimingData.cpp +++ b/src/TimingData.cpp @@ -105,7 +105,6 @@ void TimingData::PrepareLookup() GetBeatStarts time_start; time_start.last_time= -m_fBeat0OffsetInSeconds; - float time= GetElapsedTimeInternal(time_start, FLT_MAX, curr_segment); m_time_start_lookup.push_back(lookup_item_t(NoteRowToBeat(time_start.last_row), time_start)); } // If there are less than two entries, then FindEntryInLookup in lookup @@ -267,7 +266,7 @@ void TimingData::ShiftRange(int start_row, int end_row, int last_row= std::max(end_row, end_row + shift_amount); int first_affected= GetSegmentIndexAtRow(seg_type, first_row); int last_affected= GetSegmentIndexAtRow(seg_type, last_row); - if(first_affected == INVALID_INDEX) + if(first_affected == INVALID_INDEX || last_affected == INVALID_INDEX) { continue; } @@ -275,7 +274,7 @@ void TimingData::ShiftRange(int start_row, int end_row, // the rows of the segments, the second time removing segments that // have been run over by a segment being moved. Attempts to combine // both operations into a single loop were error prone. -Kyz - for(size_t i= first_affected; i <= last_affected && i < segs.size(); ++i) + for(size_t i= first_affected; last_affected >= 0 && i <= static_cast(last_affected) && i < segs.size(); ++i) { int seg_row= segs[i]->GetRow(); if(seg_row > 0 && seg_row >= start_row && seg_row <= end_row) @@ -285,7 +284,7 @@ void TimingData::ShiftRange(int start_row, int end_row, } } #define ERASE_SEG(s) if(segs.size() > 1) { EraseSegment(segs, s, segs[s]); --i; --last_affected; erased= true; } - for(size_t i= first_affected; i <= last_affected && i < segs.size(); ++i) + for(size_t i= first_affected; last_affected >= 0 && i <= static_cast(last_affected) && i < segs.size(); ++i) { bool erased= false; int seg_row= segs[i]->GetRow(); @@ -570,8 +569,6 @@ const TimingSegment* TimingData::GetSegmentAtRow( int iNoteRow, TimingSegmentTyp return DummySegments[tst]; } } - - FAIL_M("Could not find timing segment for row"); } TimingSegment* TimingData::GetSegmentAtRow( int iNoteRow, TimingSegmentType tst ) @@ -866,6 +863,7 @@ void TimingData::GetBeatInternal(GetBeatStarts& start, GetBeatArgs& args, { break; } + [[fallthrough]]; } case FOUND_STOP: { @@ -1130,18 +1128,6 @@ void TimingData::DeleteRows( int iStartRow, int iRowsToDelete ) float TimingData::GetDisplayedSpeedPercent( float fSongBeat, float fMusicSeconds ) const { - /* HACK: Somehow we get called into this function when there is no - * TimingData to work with. This seems to happen the most upon - * leaving the editor. Still, cover our butts in case this instance - * isn't existing. */ - /* ...but force a crash, so debuggers will catch it and stop here. - * That'll make us keep this bug in mind. -- vyhd */ - if( !this ) - { - DEBUG_ASSERT( this ); - return 1.0f; - } - const std::vector &speeds = GetTimingSegments(SEGMENT_SPEED); if( speeds.size() == 0 ) { diff --git a/src/TimingData.h b/src/TimingData.h index f27a0c1ab7..bde4c06529 100644 --- a/src/TimingData.h +++ b/src/TimingData.h @@ -186,7 +186,7 @@ public: } TimingSegment* GetSegmentAtBeat( float fBeat, TimingSegmentType tst ) { - return const_cast( GetSegmentAtBeat(fBeat, tst) ); + return GetSegmentAtRow( BeatToNoteRow(fBeat), tst ); } #define DefineSegmentWithName(Seg, SegName, SegType) \ @@ -391,7 +391,7 @@ public: * @param other the other TimingData. * @return the equality or lack thereof of the two TimingData. */ - bool operator==( const TimingData &other ) + bool operator==( const TimingData &other ) const { FOREACH_ENUM( TimingSegmentType, tst ) { @@ -423,7 +423,7 @@ public: * @param other the other TimingData. * @return the inequality or lack thereof of the two TimingData. */ - bool operator!=( const TimingData &other ) { return !operator==(other); } + bool operator!=( const TimingData &other ) const { return !operator==(other); } void ScaleRegion( float fScale = 1, int iStartRow = 0, int iEndRow = MAX_NOTE_ROW, bool bAdjustBPM = false ); void InsertRows( int iStartRow, int iRowsToAdd ); diff --git a/src/XmlToLua.cpp b/src/XmlToLua.cpp index fe9ba107bf..74b6a72cd2 100644 --- a/src/XmlToLua.cpp +++ b/src/XmlToLua.cpp @@ -562,6 +562,7 @@ void actor_template_t::load_node(XNode const& node, RString const& dirname, cond { case FT_Xml: this_relative= SetExtension(this_relative, "lua"); + [[fallthrough]]; case FT_Lua: set_type("LoadActor"); store_field("File", this_relative, false); diff --git a/src/arch/ArchHooks/ArchHooks_Win32.cpp b/src/arch/ArchHooks/ArchHooks_Win32.cpp index dfc9738a7f..dbb7281e44 100644 --- a/src/arch/ArchHooks/ArchHooks_Win32.cpp +++ b/src/arch/ArchHooks/ArchHooks_Win32.cpp @@ -12,6 +12,8 @@ #include "archutils/win32/GotoURL.h" #include "archutils/Win32/RegistryAccess.h" +#include "VersionHelpers.h" + static HANDLE g_hInstanceMutex; static bool g_bIsMultipleInstance = false; @@ -148,20 +150,12 @@ void ArchHooks_Win32::BoostPriority() * in the background. We don't really want to be high-priority--above normal should * be enough. However, ABOVE_NORMAL_PRIORITY_CLASS is only supported in Win2000 * and later. */ - OSVERSIONINFO version; - version.dwOSVersionInfoSize=sizeof(version); - if( !GetVersionEx(&version) ) - { - LOG->Warn( werr_ssprintf(GetLastError(), "GetVersionEx failed") ); - return; - } - #ifndef ABOVE_NORMAL_PRIORITY_CLASS #define ABOVE_NORMAL_PRIORITY_CLASS 0x00008000 #endif DWORD pri = HIGH_PRIORITY_CLASS; - if( version.dwMajorVersion >= 5 ) + if( IsWindowsVersionOrGreater(HIBYTE(_WIN32_WINNT_WIN2K), LOBYTE(_WIN32_WINNT_WIN2K), 0) ) pri = ABOVE_NORMAL_PRIORITY_CLASS; /* Be sure to boost the app, not the thread, to make sure the diff --git a/src/arch/Dialog/DialogDriver_Win32.cpp b/src/arch/Dialog/DialogDriver_Win32.cpp index 865bc712f7..6a93be927d 100644 --- a/src/arch/Dialog/DialogDriver_Win32.cpp +++ b/src/arch/Dialog/DialogDriver_Win32.cpp @@ -183,7 +183,7 @@ static INT_PTR CALLBACK ErrorWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM break; case IDC_BUTTON_RESTART: Win32RestartProgram(); - // Possibly make W32RP a NORETURN call? + // Possibly make W32RP a SM_NORETURN call? FAIL_M("Win32RestartProgram failed?"); case IDOK: EndDialog( hWnd, 0 ); diff --git a/src/arch/InputHandler/InputHandler_DirectInput.cpp b/src/arch/InputHandler/InputHandler_DirectInput.cpp index 349c626a89..6f15efec41 100644 --- a/src/arch/InputHandler/InputHandler_DirectInput.cpp +++ b/src/arch/InputHandler/InputHandler_DirectInput.cpp @@ -23,6 +23,7 @@ #include #include #include +#include // this may not be defined if we are using an older Windows SDK. (for instance, toolsetversion v140_xp does not define it) // the number was taken from the documentation @@ -623,10 +624,8 @@ void InputHandler_DInput::UpdateBuffered( DIDevice &device, const RageTimer &tm } // reset mousewheel - DeviceInput diUp = DeviceInput(device.dev, MOUSE_WHEELUP, 0.0f, tm); - ButtonPressed( diUp ); - DeviceInput diDown = DeviceInput(device.dev, MOUSE_WHEELDOWN, 0.0f, tm); - ButtonPressed( diDown ); + ButtonPressed( DeviceInput(device.dev, MOUSE_WHEELUP, 0.0f, tm) ); + ButtonPressed( DeviceInput(device.dev, MOUSE_WHEELDOWN, 0.0f, tm) ); for( int i = 0; i < (int) numevents; ++i ) { @@ -772,8 +771,8 @@ void InputHandler_DInput::UpdateBuffered( DIDevice &device, const RageTimer &tm } } -const short XINPUT_GAMEPAD_THUMB_MIN = MINSHORT; -const short XINPUT_GAMEPAD_THUMB_MAX = MAXSHORT; +inline constexpr auto XINPUT_GAMEPAD_THUMB_MIN = std::numeric_limits::min(); +inline constexpr auto XINPUT_GAMEPAD_THUMB_MAX = std::numeric_limits::max(); void InputHandler_DInput::UpdateXInput( XIDevice &device, const RageTimer &tm ) { diff --git a/src/arch/InputHandler/InputHandler_Linux_Event.cpp b/src/arch/InputHandler/InputHandler_Linux_Event.cpp index 20a18a3e25..c9a0896bed 100644 --- a/src/arch/InputHandler/InputHandler_Linux_Event.cpp +++ b/src/arch/InputHandler/InputHandler_Linux_Event.cpp @@ -263,9 +263,6 @@ EventDevice::~EventDevice() } InputHandler_Linux_Event::InputHandler_Linux_Event() - : m_bShutdown(true) - , m_bDevicesChanged(false) - , m_NextDevice(DEVICE_JOY10) { if(LINUXINPUT == nullptr) LINUXINPUT = new LinuxInputManager; LINUXINPUT->InitDriver(this); diff --git a/src/arch/InputHandler/InputHandler_Linux_Event.h b/src/arch/InputHandler/InputHandler_Linux_Event.h index 1028a5af2e..d6ce9cde5b 100644 --- a/src/arch/InputHandler/InputHandler_Linux_Event.h +++ b/src/arch/InputHandler/InputHandler_Linux_Event.h @@ -23,8 +23,8 @@ private: void InputThread(); RageThread m_InputThread; - InputDevice m_NextDevice; - bool m_bShutdown, m_bDevicesChanged; + InputDevice m_NextDevice{DEVICE_JOY10}; + bool m_bShutdown{true}, m_bDevicesChanged{false}; }; #define USE_INPUT_HANDLER_LINUX_JOYSTICK diff --git a/src/arch/InputHandler/InputHandler_MacOSX_HID.mm b/src/arch/InputHandler/InputHandler_MacOSX_HID.mm index cf8f01693b..1a6a594f39 100644 --- a/src/arch/InputHandler/InputHandler_MacOSX_HID.mm +++ b/src/arch/InputHandler/InputHandler_MacOSX_HID.mm @@ -281,8 +281,8 @@ RString InputHandler_MacOSX_HID::GetDeviceSpecificInputString( const DeviceInput { if( di.device == DEVICE_KEYBOARD ) { -#define OTHER(n) (KEY_OTHER_0 + (n)) - switch( di.button ) +#define OTHER(n) (Enum::to_integral(KEY_OTHER_0) + (n)) + switch( Enum::to_integral(di.button) ) { case KEY_DEL: return "del"; case KEY_BACK: return "delete"; @@ -381,7 +381,7 @@ static wchar_t KeyCodeToChar(CGKeyCode keyCode, unsigned int modifierFlags) if( keyboardLayout ) { UInt32 deadKeyState = 0; - UniCharCount maxStringLength = 255; + constexpr UniCharCount maxStringLength = 255; UniCharCount actualStringLength = 0; UniChar unicodeString[maxStringLength]; diff --git a/src/arch/InputHandler/InputHandler_Win32_RTIO.cpp b/src/arch/InputHandler/InputHandler_Win32_RTIO.cpp index c085acd0ea..3139d720ff 100644 --- a/src/arch/InputHandler/InputHandler_Win32_RTIO.cpp +++ b/src/arch/InputHandler/InputHandler_Win32_RTIO.cpp @@ -13,19 +13,19 @@ // an older increment command. This delay is the minimum amount of time to wait // between receiving an ack for an increment command and sending a new // increment command. -const static float COUNTER_MINIMUM_SEND_DELAY = 0.15; +inline constexpr float COUNTER_MINIMUM_SEND_DELAY = 0.15f; // The longest amount of time to wait for an ack to the increment command // before moving on with the coin counter increment sequence. -const static float COUNTER_MAXIMUM_RECV_DELAY = 3.0; +inline constexpr float COUNTER_MAXIMUM_RECV_DELAY = 3.0f; // If RTIO does not initialize within this amount of time, exit the RTIO input // loop to free resources. -const static float RTIO_INIT_TIME_MAX = 10.0; +inline constexpr float RTIO_INIT_TIME_MAX = 10.0f; // If there are this many failures, something has most likely gone very wrong, // so just exit the RTIO input loop. -const static int RTIO_MAX_READ_FAILURES = 50; +inline constexpr int RTIO_MAX_READ_FAILURES = 50; REGISTER_INPUT_HANDLER_CLASS2(Rtio, Win32_RTIO); diff --git a/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp b/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp index 25eb8a69d0..65740f184e 100644 --- a/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp +++ b/src/arch/LowLevelWindow/LowLevelWindow_X11.cpp @@ -315,7 +315,7 @@ RString LowLevelWindow_X11::TryVideoMode( const VideoModeParams &p, bool &bNewDe // If an output name has been specified, search for it RROutput targetOut = None; if (p.sDisplayId.length() > 0) { - for (unsigned int i = 0; i < scrRes->noutput && targetOut == None; ++i) { + for (unsigned int i = 0; i < static_cast(scrRes->noutput) && targetOut == None; ++i) { XRROutputInfo *outInfo = XRRGetOutputInfo(Dpy, scrRes, scrRes->outputs[i]); std::string outName = std::string(outInfo->name, static_cast (outInfo->nameLen)); if (p.sDisplayId == outName) { @@ -335,7 +335,7 @@ RString LowLevelWindow_X11::TryVideoMode( const VideoModeParams &p, bool &bNewDe // (it is possible the connection state could be unknown), we'll at least // look for an output with a CRTC driving it RROutput connected = None, hasCrtc = None; - for (unsigned int i = 0; i < scrRes->noutput; ++i) { + for (unsigned int i = 0; i < static_cast(scrRes->noutput); ++i) { XRROutputInfo *outInfo = XRRGetOutputInfo(Dpy, scrRes, scrRes->outputs[i]); if (outInfo->connection == RR_Connected) { // Check for CONNECTED state: Connected == 0 connected = scrRes->outputs[i]; @@ -362,7 +362,7 @@ RString LowLevelWindow_X11::TryVideoMode( const VideoModeParams &p, bool &bNewDe RRCrtc tgtOutCrtc = tgtOutInfo->crtc; if (tgtOutCrtc == None) { - for (unsigned int i = 0; i < tgtOutInfo->ncrtc; ++i) + for (unsigned int i = 0; i < static_cast(tgtOutInfo->ncrtc); ++i) { XRRCrtcInfo *crtcInfo = XRRGetCrtcInfo( Dpy, scrRes, tgtOutInfo->crtcs[i] ); if (crtcInfo->mode == None) @@ -388,9 +388,9 @@ RString LowLevelWindow_X11::TryVideoMode( const VideoModeParams &p, bool &bNewDe // with as close to our desired refresh rate as possible. for (int i = 0; i < scrRes->nmode; i++) { const XRRModeInfo &thisMI = scrRes->modes[i]; - const unsigned int modeWidth = bPortrait ? thisMI.height : thisMI.width; - const unsigned int modeHeight = bPortrait ? thisMI.width : thisMI.height; - if (modeWidth == p.width && modeHeight == p.height) { + const auto modeWidth = bPortrait ? thisMI.height : thisMI.width; + const auto modeHeight = bPortrait ? thisMI.width : thisMI.height; + if (p.width >= 0 && p.height >= 0 && modeWidth == static_cast(p.width) && modeHeight == static_cast(p.height)) { float fTempRefresh = calcRandRRefresh(thisMI.dotClock, thisMI.hTotal, thisMI.vTotal); float fTempDiff = std::abs(p.rate - fTempRefresh); if ((p.rate != REFRESH_DEFAULT && fTempDiff < fRefreshDiff) || @@ -659,12 +659,12 @@ void LowLevelWindow_X11::GetDisplaySpecs(DisplaySpecs &out) const { std::set screenModes; int nsizes = 0; XRRScreenSize *screenSizes = XRRSizes( Dpy, screenNum, &nsizes); - DisplayMode screenCurMode = {0}; - for (unsigned int szIdx = 0, mode_idx = 0; szIdx < nsizes; ++szIdx) { + DisplayMode screenCurMode{}; + for (unsigned int szIdx = 0, mode_idx = 0; nsizes >= 0 && szIdx < static_cast(nsizes); ++szIdx) { XRRScreenSize &size = screenSizes[szIdx]; int nrates = 0; short *rates = XRRRates(Dpy, screenNum, szIdx, &nrates); - for (unsigned int rIdx = 0; rIdx < nrates; ++rIdx, ++mode_idx) { + for (unsigned int rIdx = 0; nrates >=0 && rIdx < static_cast(nrates); ++rIdx, ++mode_idx) { DisplayMode m = {static_cast (size.width), static_cast (size.height), static_cast (rates[rIdx])}; screenModes.insert(m); if (rates[rIdx] == curRate && szIdx == curSizeId) { @@ -686,7 +686,7 @@ void LowLevelWindow_X11::GetDisplaySpecs(DisplaySpecs &out) const { // OutputInfo XRRScreenResources *scrRes = XRRGetScreenResources(Dpy, Win); std::map outputModes; - for (unsigned int i = 0; i < scrRes->nmode; ++i) { + for (int i = 0; i < scrRes->nmode; ++i) { const XRRModeInfo &mode = scrRes->modes[i]; DisplayMode m = {mode.width, mode.height, calcRandRRefresh(mode.dotClock, mode.hTotal, mode.vTotal)}; @@ -694,7 +694,7 @@ void LowLevelWindow_X11::GetDisplaySpecs(DisplaySpecs &out) const { } // Now, for each output, build a corresponding DisplaySpec - for (unsigned int outIdx = 0; outIdx < scrRes->noutput; ++outIdx) + for (unsigned int outIdx = 0; outIdx < static_cast(scrRes->noutput); ++outIdx) { XRROutputInfo *outInfo = XRRGetOutputInfo( Dpy, scrRes, scrRes->outputs[outIdx] ); if (outInfo->nmode > 0) @@ -715,9 +715,9 @@ void LowLevelWindow_X11::GetDisplaySpecs(DisplaySpecs &out) const { } // Get all supported modes, noting which one, if any, is currently active std::set outputSupported; - DisplayMode outputCurMode = {0}; + DisplayMode outputCurMode{}; RectI outBounds; - for (unsigned int modeIdx = 0; modeIdx < outInfo->nmode; ++modeIdx) + for (unsigned int modeIdx = 0; modeIdx < static_cast(outInfo->nmode); ++modeIdx) { DisplayMode mode = outputModes[outInfo->modes[modeIdx]]; unsigned int modeWidth = bPortrait ? mode.height : mode.width; diff --git a/src/arch/MemoryCard/MemoryCardDriver.cpp b/src/arch/MemoryCard/MemoryCardDriver.cpp index b2d28d6283..79c1bf38a1 100644 --- a/src/arch/MemoryCard/MemoryCardDriver.cpp +++ b/src/arch/MemoryCard/MemoryCardDriver.cpp @@ -153,6 +153,8 @@ MemoryCardDriver *MemoryCardDriver::Create() ret = new ARCH_MEMORY_CARD_DRIVER; #endif break; + default: + break; } if( !ret ) diff --git a/src/arch/MemoryCard/MemoryCardDriver.h b/src/arch/MemoryCard/MemoryCardDriver.h index b7e3800848..d9607e500d 100644 --- a/src/arch/MemoryCard/MemoryCardDriver.h +++ b/src/arch/MemoryCard/MemoryCardDriver.h @@ -3,34 +3,18 @@ struct UsbStorageDevice { - UsbStorageDevice() { MakeBlank(); } + UsbStorageDevice() = default; - void MakeBlank() - { - // -1 means "don't know" - iBus = -1; - iPort = -1; - iLevel = -1; - sDevice = ""; - sSerial = ""; // be different than a card with no serial - sOsMountDir = ""; - m_State = STATE_NONE; - bIsNameAvailable = false; - sName = ""; - idVendor = 0; - idProduct = 0; - sVendor = ""; - sProduct = ""; - sVolumeLabel = ""; - iVolumeSizeMB = 0; - }; - int iBus; - int iPort; - int iLevel; - RString sSerial; - RString sDevice; - RString sOsMountDir; // WITHOUT trailing slash - RString sSysPath; // Linux: /sys/block name + void MakeBlank() { *this = {}; }; + + // -1 means "don't know" + int iBus{-1}; + int iPort{-1}; + int iLevel{-1}; + RString sSerial{"none"}; // be different than a card with no serial + RString sDevice{}; + RString sOsMountDir{}; // WITHOUT trailing slash + RString sSysPath{}; // Linux: /sys/block name enum State { /* Empty device. This is used only by MemoryCardManager. */ @@ -52,19 +36,19 @@ struct UsbStorageDevice NUM_State, State_INVALID }; - State m_State; - RString m_sError; + State m_State{STATE_NONE}; + RString m_sError{}; void SetError( const RString &sError ) { m_State = STATE_ERROR; m_sError = sError; } - bool bIsNameAvailable; // Name in the profile on the memory card. - RString sName; // Name in the profile on the memory card. - int idVendor; - int idProduct; - RString sVendor; - RString sProduct; - RString sVolumeLabel; - int iVolumeSizeMB; + bool bIsNameAvailable{false}; // Name in the profile on the memory card. + RString sName{}; // Name in the profile on the memory card. + unsigned int idVendor{0}; + unsigned int idProduct{0}; + RString sVendor{}; + RString sProduct{}; + RString sVolumeLabel{}; + int iVolumeSizeMB{0}; bool IsBlank() const { return m_State == STATE_NONE; } void SetOsMountDir( const RString &s ); diff --git a/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp b/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp index f945fed8e6..055d44f277 100644 --- a/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp +++ b/src/arch/MovieTexture/MovieTexture_FFMpeg.cpp @@ -11,7 +11,10 @@ static void FixLilEndian() { -#if defined(ENDIAN_LITTLE) + if constexpr ( !Endian::little ) { + return; + } + static bool Initialized = false; if( Initialized ) return; @@ -37,7 +40,6 @@ static void FixLilEndian() pf.masks[mask] = m; } } -#endif } static int FindCompatibleAVFormat( bool bHighColor ) diff --git a/src/arch/Sound/ALSA9Dynamic.h b/src/arch/Sound/ALSA9Dynamic.h index e661ccf578..90f2754255 100644 --- a/src/arch/Sound/ALSA9Dynamic.h +++ b/src/arch/Sound/ALSA9Dynamic.h @@ -12,11 +12,11 @@ #include "ALSA9Functions.h" #undef FUNC -#define dsnd_pcm_hw_params_alloca(ptr) { assert(ptr); *ptr = (snd_pcm_hw_params_t *) alloca(dsnd_pcm_hw_params_sizeof()); memset(*ptr, 0, dsnd_pcm_hw_params_sizeof()); } -#define dsnd_pcm_sw_params_alloca(ptr) { assert(ptr); *ptr = (snd_pcm_sw_params_t *) alloca(dsnd_pcm_sw_params_sizeof()); memset(*ptr, 0, dsnd_pcm_sw_params_sizeof()); } -#define dsnd_pcm_info_alloca(ptr) { assert(ptr); *ptr = (snd_pcm_info_t *) alloca(dsnd_pcm_info_sizeof()); memset(*ptr, 0, dsnd_pcm_info_sizeof()); } -#define dsnd_ctl_card_info_alloca(ptr) { assert(ptr); *ptr = (snd_ctl_card_info_t *) alloca(dsnd_ctl_card_info_sizeof()); memset(*ptr, 0, dsnd_ctl_card_info_sizeof()); } -#define dsnd_pcm_status_alloca(ptr) do { assert(ptr); *ptr = (snd_pcm_status_t *) alloca(dsnd_pcm_status_sizeof()); memset(*ptr, 0, dsnd_pcm_status_sizeof()); } while (0) +#define dsnd_pcm_hw_params_alloca(ptr) { *ptr = (snd_pcm_hw_params_t *) alloca(dsnd_pcm_hw_params_sizeof()); memset(*ptr, 0, dsnd_pcm_hw_params_sizeof()); } +#define dsnd_pcm_sw_params_alloca(ptr) { *ptr = (snd_pcm_sw_params_t *) alloca(dsnd_pcm_sw_params_sizeof()); memset(*ptr, 0, dsnd_pcm_sw_params_sizeof()); } +#define dsnd_pcm_info_alloca(ptr) { *ptr = (snd_pcm_info_t *) alloca(dsnd_pcm_info_sizeof()); memset(*ptr, 0, dsnd_pcm_info_sizeof()); } +#define dsnd_ctl_card_info_alloca(ptr) { *ptr = (snd_ctl_card_info_t *) alloca(dsnd_ctl_card_info_sizeof()); memset(*ptr, 0, dsnd_ctl_card_info_sizeof()); } +#define dsnd_pcm_status_alloca(ptr) do { ptr = (snd_pcm_status_t *) alloca(dsnd_pcm_status_sizeof()); memset(*ptr, 0, dsnd_pcm_status_sizeof()); } while (0) RString LoadALSA(); void UnloadALSA(); diff --git a/src/arch/Sound/DSoundHelpers.cpp b/src/arch/Sound/DSoundHelpers.cpp index 3c69af8c21..2346e6058e 100644 --- a/src/arch/Sound/DSoundHelpers.cpp +++ b/src/arch/Sound/DSoundHelpers.cpp @@ -117,7 +117,6 @@ RString DSound::Init() DSCAPS Caps; Caps.dwSize = sizeof(Caps); - HRESULT hr; if( FAILED(hr = m_pDS->GetCaps(&Caps)) ) { LOG->Warn( hr_ssprintf(hr, "m_pDS->GetCaps failed") ); @@ -211,7 +210,7 @@ RString DSoundBuf::Init( DSound &ds, DSoundBuf::hw hardware, memset( &format, 0, sizeof(format) ); format.dwSize = sizeof(format); - if (at_least_vista()) + if (IsWindowsVistaOrGreater()) { format.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLVOLUME | DSBCAPS_TRUEPLAYPOSITION; } diff --git a/src/arch/Sound/RageSoundDriver.h b/src/arch/Sound/RageSoundDriver.h index 1a51221c02..3b4efe73d4 100644 --- a/src/arch/Sound/RageSoundDriver.h +++ b/src/arch/Sound/RageSoundDriver.h @@ -98,7 +98,7 @@ protected: void Mix( int16_t *pBuf, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ); void Mix( float *pBuf, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ); - void MixDeinterlaced( float **pBufs, int channels, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ); + void MixDeinterlaced( float **pBufs, int iChannels, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ); private: /* This mutex is used for serializing with the decoder thread. Locking this mutex diff --git a/src/arch/Sound/RageSoundDriver_AU.mm b/src/arch/Sound/RageSoundDriver_AU.mm index 51c1154091..9776d92996 100644 --- a/src/arch/Sound/RageSoundDriver_AU.mm +++ b/src/arch/Sound/RageSoundDriver_AU.mm @@ -14,7 +14,7 @@ static const UInt32 kChannelsPerFrame = 2; static const UInt32 kBitsPerChannel = 32; static const UInt32 kBytesPerPacket = kChannelsPerFrame * kBitsPerChannel / 8; static const UInt32 kBytesPerFrame = kBytesPerPacket; -static const UInt32 kFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsFloat; +static const UInt32 kFormatFlags = Enum::to_integral(kAudioFormatFlagsNativeEndian) | Enum::to_integral(kAudioFormatFlagIsFloat); static const char *FormatOSError(OSStatus status) { @@ -62,7 +62,7 @@ static void SetSampleRate( AudioUnit au, Float64 desiredRate ) kAudioObjectPropertyElementWildcard }; - if( (error = AudioObjectGetPropertyData(OutputDevice, &AvailableRatesAddr, 0, nullptr, &size, nullptr)) ) + if( (error = AudioObjectGetPropertyDataSize(OutputDevice, &AvailableRatesAddr, 0, nullptr, &size)) ) { LOG->Warn("Couldn't get available nominal sample rates info: %s", FormatOSError(error)); return; @@ -295,7 +295,7 @@ float RageSoundDriver_AU::GetPlayLatency() const kAudioObjectPropertyElementWildcard }; - if( (error = AudioObjectGetPropertyData(OutputDevice, &StreamsAddr, 0, nullptr, &size, nullptr)) ) + if( (error = AudioObjectGetPropertyDataSize(OutputDevice, &StreamsAddr, 0, nullptr, &size)) ) { LOG->Warn("Device has no streams: %s", FormatOSError(error)); break; diff --git a/src/arch/Sound/RageSoundDriver_Generic_Software.cpp b/src/arch/Sound/RageSoundDriver_Generic_Software.cpp index 1f31dac8b9..e945bd1071 100644 --- a/src/arch/Sound/RageSoundDriver_Generic_Software.cpp +++ b/src/arch/Sound/RageSoundDriver_Generic_Software.cpp @@ -170,11 +170,11 @@ void RageSoundDriver::Mix( float *pBuf, int iFrames, int64_t iFrameNumber, int64 MixIntoBuffer( iFrames, iFrameNumber, iCurrentFrame ).read( pBuf ); } -void RageSoundDriver::MixDeinterlaced( float **pBufs, int channels, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ) +void RageSoundDriver::MixDeinterlaced( float **pBufs, int iChannels, int iFrames, int64_t iFrameNumber, int64_t iCurrentFrame ) { - for (int i = 0; i < channels; ++i ) + for (int i = 0; i < iChannels; ++i ) memset( pBufs[i], 0, iFrames*sizeof(float) ); - MixIntoBuffer( iFrames, iFrameNumber, iCurrentFrame ).read_deinterlace( pBufs, channels ); + MixIntoBuffer( iFrames, iFrameNumber, iCurrentFrame ).read_deinterlace( pBufs, iChannels ); } void RageSoundDriver::DecodeThread() diff --git a/src/arch/Sound/RageSoundDriver_PulseAudio.cpp b/src/arch/Sound/RageSoundDriver_PulseAudio.cpp index b9b4469d95..d6df700ad2 100644 --- a/src/arch/Sound/RageSoundDriver_PulseAudio.cpp +++ b/src/arch/Sound/RageSoundDriver_PulseAudio.cpp @@ -268,6 +268,8 @@ void RageSoundDriver_PulseAudio::CtxStateCb(pa_context *c) m_Sem.Post(); return; break; + default: + break; } } @@ -313,12 +315,12 @@ void RageSoundDriver_PulseAudio::StreamWriteCb(pa_stream *s, size_t length) * maybe the requested length is given in frames instead of bytes */ length *= 2; #endif - size_t nbframes = length / sizeof(int16_t); /* we use 16-bit frames */ - int16_t buf[nbframes]; + const size_t nbframes = length / sizeof(int16_t); /* we use 16-bit frames */ + std::vector buf(nbframes); int64_t pos1 = m_LastPosition; int64_t pos2 = pos1 + nbframes/2; /* Mix() position in stereo frames */ - this->Mix( buf, pos2-pos1, pos1, pos2); - if(pa_stream_write(m_PulseStream, buf, length, nullptr, 0, PA_SEEK_RELATIVE) < 0) + this->Mix( buf.data(), pos2-pos1, pos1, pos2); + if(pa_stream_write(m_PulseStream, buf.data(), length, nullptr, 0, PA_SEEK_RELATIVE) < 0) { RageException::Throw("Pulse: pa_stream_write()"); } diff --git a/src/arch/Sound/RageSoundDriver_WDMKS.cpp b/src/arch/Sound/RageSoundDriver_WDMKS.cpp index d90cdec44f..7c2ef1af58 100644 --- a/src/arch/Sound/RageSoundDriver_WDMKS.cpp +++ b/src/arch/Sound/RageSoundDriver_WDMKS.cpp @@ -120,14 +120,6 @@ struct WinWdmFilter int m_iUsageCount; }; -static RString GUIDToString( const GUID *pGuid ) -{ - return ssprintf("%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", - pGuid->Data1, pGuid->Data2, pGuid->Data3, - pGuid->Data4[0], pGuid->Data4[1], pGuid->Data4[2], pGuid->Data4[3], - pGuid->Data4[4], pGuid->Data4[5], pGuid->Data4[6], pGuid->Data4[7] ); -} - static HMODULE DllKsUser = nullptr; static KSCREATEPIN *FunctionKsCreatePin = nullptr; diff --git a/src/archutils/Unix/CrashHandler.cpp b/src/archutils/Unix/CrashHandler.cpp index f16cc501f4..cf3bb6af9a 100644 --- a/src/archutils/Unix/CrashHandler.cpp +++ b/src/archutils/Unix/CrashHandler.cpp @@ -69,7 +69,7 @@ static void GetExecutableName( char *buf, int bufsize ) } #endif -static void NORETURN spawn_child_process( int from_parent ) +static void SM_NORETURN spawn_child_process( int from_parent ) { /* We need to re-exec ourself, to get a clean process. Close all * FDs except for 0-2 and to_child, and then assign to_child to 3. */ diff --git a/src/archutils/Unix/CrashHandlerChild.cpp b/src/archutils/Unix/CrashHandlerChild.cpp index 38c6d65d21..9a0834a29a 100644 --- a/src/archutils/Unix/CrashHandlerChild.cpp +++ b/src/archutils/Unix/CrashHandlerChild.cpp @@ -230,6 +230,7 @@ static void child_process() } break; } + [[fallthrough]]; } case CrashData::FORCE_CRASH: crash.reason[sizeof(crash.reason)-1] = 0; diff --git a/src/archutils/Unix/X11Helper.cpp b/src/archutils/Unix/X11Helper.cpp index 16f8bbb81b..763fb27c5a 100644 --- a/src/archutils/Unix/X11Helper.cpp +++ b/src/archutils/Unix/X11Helper.cpp @@ -204,7 +204,8 @@ bool X11Helper::SetWMFullscreenMonitors( const DisplaySpec &target ) { auto mon = std::find_if( screens, end, [&]( XineramaScreenInfo &screen ) { return screen.x_org == target.currentBounds().left && screen.y_org == target.currentBounds().top - && screen.width == target.currentMode()->width && screen.height == target.currentMode()->height; + && screen.width >= 0 && static_cast(screen.width) == target.currentMode()->width + && screen.height >= 0 && static_cast(screen.height) == target.currentMode()->height; } ); if (mon != end) { @@ -214,7 +215,7 @@ bool X11Helper::SetWMFullscreenMonitors( const DisplaySpec &target ) } XFree( screens ); - XWindowAttributes attr = {0}; + XWindowAttributes attr{}; if (!found_bounds || !XGetWindowAttributes( Dpy, Win, &attr )) { return false; @@ -222,7 +223,7 @@ bool X11Helper::SetWMFullscreenMonitors( const DisplaySpec &target ) SetWMState( attr.root, Win, 1, XInternAtom( Dpy, "_NET_WM_STATE_FULLSCREEN", False )); - XClientMessageEvent xclient = {0}; + XClientMessageEvent xclient{}; xclient.type = ClientMessage; xclient.window = Win; xclient.message_type = XInternAtom( Dpy, "_NET_WM_FULLSCREEN_MONITORS", False ); diff --git a/src/archutils/Win32/Crash.cpp b/src/archutils/Win32/Crash.cpp index c60e9d279d..7654a09c7d 100644 --- a/src/archutils/Win32/Crash.cpp +++ b/src/archutils/Win32/Crash.cpp @@ -298,7 +298,7 @@ static DWORD WINAPI MainExceptionHandler( LPVOID lpParameter ) #else pExc->ContextRecord->FloatSave.ControlWord |= 0x3F; #endif - return EXCEPTION_CONTINUE_EXECUTION; + return static_cast(EXCEPTION_CONTINUE_EXECUTION); } static int InHere = 0; @@ -563,7 +563,7 @@ void CrashHandler::do_backtrace( const void **buf, size_t size, } // Trigger the crash handler. This works even in the debugger. -static void NORETURN debug_crash() +static void SM_NORETURN debug_crash() { // __try { #if defined(__MSC_VER) diff --git a/src/archutils/Win32/CrashHandlerChild.cpp b/src/archutils/Win32/CrashHandlerChild.cpp index 53ff1bd6c0..67528a28af 100644 --- a/src/archutils/Win32/CrashHandlerChild.cpp +++ b/src/archutils/Win32/CrashHandlerChild.cpp @@ -818,7 +818,6 @@ INT_PTR CrashDialog::HandleMessage( UINT msg, WPARAM wParam, LPARAM lParam ) XNode xml; if( sError.empty() ) { - RString sError; XmlFileUtil::Load( &xml, sResult, sError ); if( !sError.empty() ) { diff --git a/src/archutils/Win32/DebugInfoHunt.cpp b/src/archutils/Win32/DebugInfoHunt.cpp index f8b15219a7..79cfe14878 100644 --- a/src/archutils/Win32/DebugInfoHunt.cpp +++ b/src/archutils/Win32/DebugInfoHunt.cpp @@ -79,43 +79,7 @@ static RString wo_ssprintf( MMRESULT err, const char *fmt, ...) return s += ssprintf( "(%s)", buf ); } -static void GetDriveDebugInfo9x() -{ - - /* - * HKEY_LOCAL_MACHINE\Enum\ESDI - * *\ (disk id) - * *\ (eg. MF&CHILD0000&PCI&VEN_8086&DEV_7111&SUBSYS_197615AD&REV_01&BUS_00&DEV_07&FUNC_0100) - * DMACurrentlyUsed 0 or 1 - * DeviceDesc "GENERIC IDE DISK TYPE01" - */ - std::vector Drives; - if( !RegistryAccess::GetRegSubKeys( "HKEY_LOCAL_MACHINE\\Enum\\ESDI", Drives ) ) - return; - - for( unsigned drive = 0; drive < Drives.size(); ++drive ) - { - std::vector IDs; - if( !RegistryAccess::GetRegSubKeys( Drives[drive], IDs ) ) - continue; - - for( unsigned id = 0; id < IDs.size(); ++id ) - { - RString DeviceDesc; - - RegistryAccess::GetRegValue( IDs[id], "DeviceDesc", DeviceDesc ); - TrimRight( DeviceDesc ); - - int DMACurrentlyUsed = -1; - RegistryAccess::GetRegValue( IDs[id], "DMACurrentlyUsed", DMACurrentlyUsed ); - - LOG->Info( "Drive: \"%s\" DMA: %s", - DeviceDesc.c_str(), DMACurrentlyUsed? "yes":"NO" ); - } - } -} - -static void GetDriveDebugInfoNT() +static void GetDriveDebugInfo() { /* * HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\Scsi\ @@ -169,31 +133,15 @@ static void GetDriveDebugInfoNT() } } -static void GetDriveDebugInfo() -{ - OSVERSIONINFO ovi; - ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if( !GetVersionEx(&ovi) ) - { - LOG->Info("GetVersionEx failed!"); - return; - } - - switch( ovi.dwPlatformId ) - { - case VER_PLATFORM_WIN32_WINDOWS: - GetDriveDebugInfo9x(); break; - case VER_PLATFORM_WIN32_NT: - GetDriveDebugInfoNT(); break; - } -} - static void GetWindowsVersionDebugInfo() { // Detect operating system. OSVERSIONINFO ovi; ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); +#pragma warning( push ) +#pragma warning( disable : 4996 ) if (!GetVersionEx(&ovi)) +#pragma warning( pop ) { LOG->Info("GetVersionEx failed!"); return; diff --git a/src/archutils/Win32/DirectXHelpers.h b/src/archutils/Win32/DirectXHelpers.h index 42c00f5d19..d8c56232b4 100644 --- a/src/archutils/Win32/DirectXHelpers.h +++ b/src/archutils/Win32/DirectXHelpers.h @@ -1,27 +1,10 @@ #ifndef DIRECTX_HELPERS_H #define DIRECTX_HELPERS_H #include "windows.h" +#include "VersionHelpers.h" RString hr_ssprintf( int hr, const char *fmt, ... ); -//Keep XP on life support -static bool at_least_vista() -{ -OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, { 0 }, 0, 0 }; -DWORDLONG const dwlConditionMask = VerSetConditionMask( - VerSetConditionMask( - VerSetConditionMask( - 0, VER_MAJORVERSION, VER_GREATER_EQUAL), - VER_MINORVERSION, VER_GREATER_EQUAL), - VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - -osvi.dwMajorVersion = 0x0600; -osvi.dwMinorVersion = 0x0; -osvi.wServicePackMajor = 0; - -return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) != false; -} - RString GetErrorString(HRESULT hr); #endif diff --git a/src/archutils/Win32/GraphicsWindow.cpp b/src/archutils/Win32/GraphicsWindow.cpp index 401aa6ed3c..371b63970d 100644 --- a/src/archutils/Win32/GraphicsWindow.cpp +++ b/src/archutils/Win32/GraphicsWindow.cpp @@ -417,7 +417,7 @@ void GraphicsWindow::Initialize( bool bD3D ) g_bD3D = bD3D; //keeping xp on life support -- check for vista+ for dwm - if (at_least_vista()) + if (IsWindowsVistaOrGreater()) { hInstanceDwmapi = LoadLibraryA("dwmapi.dll"); } diff --git a/src/archutils/Win32/VideoDriverInfo.cpp b/src/archutils/Win32/VideoDriverInfo.cpp index 0e944ec455..cd3c1767a5 100644 --- a/src/archutils/Win32/VideoDriverInfo.cpp +++ b/src/archutils/Win32/VideoDriverInfo.cpp @@ -62,19 +62,13 @@ RString GetPrimaryVideoDriverName() /* Get info for the given card number. Return false if that card doesn't exist. */ bool GetVideoDriverInfo( int iCardno, VideoDriverInfo &info ) { - OSVERSIONINFO version; - version.dwOSVersionInfoSize = sizeof(version); - GetVersionEx(&version); - const bool bIsWin9x = version.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS; - static bool bInitialized=false; static std::vector lst; if( !bInitialized ) { bInitialized = true; - const RString sTopKey = bIsWin9x? - "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\Class\\Display": + const RString sTopKey = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E968-E325-11CE-BFC1-08002BE10318}"; RegistryAccess::GetRegSubKeys( sTopKey, lst, ".*", false ); @@ -113,7 +107,7 @@ bool GetVideoDriverInfo( int iCardno, VideoDriverInfo &info ) RegistryAccess::GetRegValue( sKey, "DriverDate", info.sDate ); RegistryAccess::GetRegValue( sKey, "MatchingDeviceId", info.sDeviceID ); RegistryAccess::GetRegValue( sKey, "ProviderName", info.sProvider ); - RegistryAccess::GetRegValue( sKey, bIsWin9x? "Ver":"DriverVersion", info.sVersion ); + RegistryAccess::GetRegValue( sKey, "DriverVersion", info.sVersion ); return true; } diff --git a/src/archutils/Win32/ddk/hidpi.h b/src/archutils/Win32/ddk/hidpi.h index 4a361227d5..3b2936ec3f 100644 --- a/src/archutils/Win32/ddk/hidpi.h +++ b/src/archutils/Win32/ddk/hidpi.h @@ -1699,7 +1699,7 @@ typedef struct _HIDP_KEYBOARD_MODIFIER_STATE { ULONG ScollLock: 1; ULONG NumLock: 1; ULONG Reserved: 21; - }; + } s; ULONG ul; }; diff --git a/src/config.in.hpp b/src/config.in.hpp index 3e8fca76e5..b724f2eac0 100644 --- a/src/config.in.hpp +++ b/src/config.in.hpp @@ -124,12 +124,6 @@ typedef unsigned long size_t; typedef std::make_signed::type ssize_t; #endif -/* Defined to 1 if the underlying system uses little endian. */ -#cmakedefine ENDIAN_LITTLE 1 - -/* Defined to 1 if the underlying system uses big endian. */ -#cmakedefine ENDIAN_BIG 1 - /* Defined to 1 if logging timing segment additions and removals. */ #cmakedefine WITH_LOGGING_TIMING_DATA 1 @@ -250,26 +244,12 @@ inline long lrintf( float f ) #define M_PI 3.1415926535897932384626433832795 #endif -/* Ensure we have an endianness defined. */ -#if !defined(ENDIAN_LITTLE) && !defined(ENDIAN_BIG) -#error "Neither ENDIAN_LITTLE nor ENDIAN_BIG defined. Aborting." -#endif - /* Define standard endianness macros, if they're missing. */ #if defined(HAVE_ENDIAN_H) #include #elif defined(HAVE_MACHINE_ENDIAN_H) #include #else -/** @brief The macro for little endian order. */ -#define LITTLE_ENDIAN 1234 -/** @brief The macro for big endian order. */ -#define BIG_ENDIAN 4321 -#if defined(ENDIAN_LITTLE) -#define BYTE_ORDER LITTLE_ENDIAN -#elif defined(ENDIAN_BIG) -#define BYTE_ORDER BIG_ENDIAN -#endif #endif diff --git a/src/global.cpp b/src/global.cpp index 6faea324fd..4d7ddc0dec 100644 --- a/src/global.cpp +++ b/src/global.cpp @@ -25,7 +25,7 @@ using CrashHandler::DebugBreak; #include "archutils/Unix/CrashHandler.h" #endif -void NORETURN sm_crash( const char *reason ) +void SM_NORETURN sm_crash( const char *reason ) { #if ( defined(_WINDOWS) && defined(CRASH_HANDLER) ) || defined(MACOSX) || defined(_XDBG) /* If we're being debugged, throw a debug break so it'll suspend the process. */ diff --git a/src/global.h b/src/global.h index 3fd49c2af1..bcc8e4396c 100644 --- a/src/global.h +++ b/src/global.h @@ -68,11 +68,11 @@ namespace Checkpoints * beginning of the function prototype (although it looks better near the end, * VC only accepts it at the beginning). */ #if defined(_MSC_VER) -#define NORETURN __declspec(noreturn) +#define SM_NORETURN __declspec(noreturn) #elif defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5)) -#define NORETURN __attribute__ ((__noreturn__)) +#define SM_NORETURN __attribute__ ((__noreturn__)) #else -#define NORETURN +#define SM_NORETURN #endif /** @@ -84,7 +84,7 @@ namespace Checkpoints * @param reason the crash reason as determined by prior function calls. * @return nothing: there is no escape without quitting the program. */ -void NORETURN sm_crash( const char *reason = "Internal error" ); +void SM_NORETURN sm_crash( const char *reason = "Internal error" ); /** * @brief Assertion that sets an optional message and brings up the crash