diff --git a/src/Etterna/Actor/Base/Actor.cpp b/src/Etterna/Actor/Base/Actor.cpp index 2c050330a2..c5926fcbd4 100644 --- a/src/Etterna/Actor/Base/Actor.cpp +++ b/src/Etterna/Actor/Base/Actor.cpp @@ -29,7 +29,7 @@ class HiddenActor : public Actor { public: HiddenActor() { SetVisible(false); } - HiddenActor* Copy() const override; + [[nodiscard]] HiddenActor* Copy() const override; }; REGISTER_ACTOR_CLASS_WITH_NAME(HiddenActor, Actor); @@ -143,7 +143,7 @@ GetMessageNameFromCommandName(const std::string& sCommandName, Actor::Actor() { m_pLuaInstance = new LuaClass; - auto L = LUA->Get(); + auto* L = LUA->Get(); m_pLuaInstance->PushSelf(L); lua_newtable(L); lua_pushvalue(L, -1); @@ -184,7 +184,7 @@ Actor::Actor(const Actor& cpy) m_WrapperStates.resize(cpy.m_WrapperStates.size()); for (size_t i = 0; i < m_WrapperStates.size(); ++i) { - auto cp = dynamic_cast(cpy.m_WrapperStates[i]); + auto* const cp = dynamic_cast(cpy.m_WrapperStates[i]); ASSERT_M(cp != nullptr, "Dynamic cast to ActorFrame copy failed at runtime."); m_WrapperStates[i] = new ActorFrame(*cp); @@ -199,7 +199,7 @@ Actor::Actor(const Actor& cpy) CPY(m_size); CPY(m_current); CPY(m_start); - for (auto m_Tween : cpy.m_Tweens) + for (auto* m_Tween : cpy.m_Tweens) m_Tweens.push_back(new TweenStateAndInfo(*m_Tween)); CPY(m_fHorizAlign); @@ -254,14 +254,14 @@ Actor::Actor(const Actor& cpy) void Actor::LoadFromNode(const XNode* pNode) { - auto L = LUA->Get(); + auto* L = LUA->Get(); FOREACH_CONST_Attr(pNode, pAttr) { // Load Name, if any. const auto& sKeyName = pAttr->first; const XNodeValue* pValue = pAttr->second; if (EndsWith(sKeyName, "Command")) { - auto pRef = new LuaReference; + auto* pRef = new LuaReference; pValue->PushValue(L); pRef->SetFromStack(L); auto sCmdName = sKeyName.substr(0, sKeyName.size() - 7); @@ -290,7 +290,7 @@ Actor::LoadFromNode(const XNode* pNode) } bool -Actor::PartiallyOpaque() +Actor::PartiallyOpaque() const { return m_pTempState->diffuse[0].a > 0 || m_pTempState->diffuse[1].a > 0 || m_pTempState->diffuse[2].a > 0 || m_pTempState->diffuse[3].a > 0 || @@ -303,24 +303,26 @@ Actor::IsOver(float mx, float my) if (!IsVisible()) return false; - auto x = GetTrueX(); - auto y = GetTrueY(); + const auto x = GetTrueX(); + const auto y = GetTrueY(); - auto hal = GetHorizAlign(); - auto val = GetVertAlign(); + const auto hal = GetHorizAlign(); + const auto val = GetVertAlign(); - auto wi = GetZoomedWidth() * GetFakeParentOrParent()->GetTrueZoom(); - auto hi = GetZoomedHeight() * GetFakeParentOrParent()->GetTrueZoom(); + const auto wi = GetZoomedWidth() * GetFakeParentOrParent()->GetTrueZoom(); + const auto hi = GetZoomedHeight() * GetFakeParentOrParent()->GetTrueZoom(); - auto rotZ = GetTrueRotationZ(); + const auto rotZ = GetTrueRotationZ(); RageVector2 p1(mx - x, my - y); RageVec2RotateFromOrigin(&p1, -rotZ); p1.x += x; p1.y += y; - auto withinX = (p1.x >= (x - hal * wi)) && (p1.x <= (x + wi - hal * wi)); - auto withinY = (p1.y >= (y - val * hi)) && (p1.y <= (y + hi - val * hi)); + const auto withinX = + (p1.x >= (x - hal * wi)) && (p1.x <= (x + wi - hal * wi)); + const auto withinY = + (p1.y >= (y - val * hi)) && (p1.y <= (y + hi - val * hi)); return withinX && withinY; } Actor* @@ -431,7 +433,7 @@ Actor::Draw() // wrapper[1] is inside wrapper[2]. The actor is inside wrapper[1]. // -Kyz for (auto i = m_WrapperStates.size(); i > 0 && dont_abort_draw; --i) { - auto state = m_WrapperStates[i - 1]; + auto* state = m_WrapperStates[i - 1]; if (!state->m_bVisible || state->EarlyAbortDraw()) { dont_abort_draw = false; } else { @@ -468,7 +470,7 @@ Actor::Draw() this->PostDraw(); } for (size_t i = 0; i < wrapper_states_used; ++i) { - auto state = m_WrapperStates[i]; + auto* state = m_WrapperStates[i]; if (abort_with_end_draw) { state->EndDraw(); } @@ -533,14 +535,14 @@ Actor::PreDraw() // calculate actor properties ASSERT_M(fPercentThroughEffect >= 0 && fPercentThroughEffect <= 1, ssprintf("PercentThroughEffect: %f", fPercentThroughEffect)); - auto bBlinkOn = fPercentThroughEffect > 0.5f; - auto fPercentBetweenColors = + const auto bBlinkOn = fPercentThroughEffect > 0.5f; + const auto fPercentBetweenColors = RageFastSin((fPercentThroughEffect + 0.25f) * 2 * PI) / 2 + 0.5f; ASSERT_M(fPercentBetweenColors >= 0 && fPercentBetweenColors <= 1, ssprintf("PercentBetweenColors: %f, PercentThroughEffect: %f", fPercentBetweenColors, fPercentThroughEffect)); - auto fOriginalAlpha = tempState.diffuse[0].a; + const auto fOriginalAlpha = tempState.diffuse[0].a; // todo: account for SSC_FUTURES -aj switch (m_Effect) { @@ -622,25 +624,27 @@ Actor::PreDraw() // calculate actor properties m_vEffectMagnitude.z * randomf(-1.0f, 1.0f) * GetZoom(); break; case bounce: { - auto fPercentOffset = RageFastSin(fPercentThroughEffect * PI); + const auto fPercentOffset = + RageFastSin(fPercentThroughEffect * PI); tempState.pos += m_vEffectMagnitude * fPercentOffset; } break; case bob: { - auto fPercentOffset = + const auto fPercentOffset = RageFastSin(fPercentThroughEffect * PI * 2); tempState.pos += m_vEffectMagnitude * fPercentOffset; } break; case pulse: { - auto fMinZoom = m_vEffectMagnitude[0]; - auto fMaxZoom = m_vEffectMagnitude[1]; - auto fPercentOffset = RageFastSin(fPercentThroughEffect * PI); - auto fZoom = + const auto fMinZoom = m_vEffectMagnitude[0]; + const auto fMaxZoom = m_vEffectMagnitude[1]; + const auto fPercentOffset = + RageFastSin(fPercentThroughEffect * PI); + const auto fZoom = SCALE(fPercentOffset, 0.f, 1.f, fMinZoom, fMaxZoom); tempState.scale *= fZoom; // Use the color as a Vector3 to scale the effect for added // control - auto c = SCALE( + const auto c = SCALE( fPercentOffset, 0.f, 1.f, m_effectColor1, m_effectColor2); tempState.scale.x *= c.r; tempState.scale.y *= c.g; @@ -720,9 +724,9 @@ Actor::BeginDraw() // set the world matrix // handle alignment; most actors have default alignment. if (unlikely(m_fHorizAlign != 0.5f || m_fVertAlign != 0.5f)) { - auto fX = + const auto fX = SCALE(m_fHorizAlign, 0.0f, 1.0f, +m_size.x / 2.0f, -m_size.x / 2.0f); - auto fY = + const auto fY = SCALE(m_fVertAlign, 0.0f, 1.0f, +m_size.y / 2.0f, -m_size.y / 2.0f); RageMatrix m{}; RageMatrixTranslate(&m, fX, fY, 0); @@ -796,7 +800,7 @@ Actor::CalcPercentThroughTween() auto& TI = m_Tweens[0]->info; const auto percent_through = 1 - (TI.m_fTimeLeftInTween / TI.m_fTweenTime); // distort the percentage if appropriate - auto percent_along = TI.m_pTween->Tween(percent_through); + const auto percent_along = TI.m_pTween->Tween(percent_through); TweenState::MakeWeightedAverage(m_current, m_start, TS, percent_along); UpdatePercentThroughTween(percent_along); } @@ -817,9 +821,9 @@ Actor::UpdateTweening(float fDeltaTime) auto& TS = m_Tweens[0]->state; auto& TI = m_Tweens[0]->info; - auto bBeginning = TI.m_fTimeLeftInTween == TI.m_fTweenTime; + const auto bBeginning = TI.m_fTimeLeftInTween == TI.m_fTweenTime; - auto fSecsToSubtract = min(TI.m_fTimeLeftInTween, fDeltaTime); + const auto fSecsToSubtract = min(TI.m_fTimeLeftInTween, fDeltaTime); TI.m_fTimeLeftInTween -= fSecsToSubtract; fDeltaTime -= fSecsToSubtract; @@ -1016,7 +1020,7 @@ Actor::BeginTweening(float time, TweenType tt) { ASSERT(time >= 0); - auto pTween = ITween::CreateFromType(tt); + auto* const pTween = ITween::CreateFromType(tt); this->BeginTweening(time, pTween); } @@ -1049,8 +1053,8 @@ void Actor::ScaleTo(const RectF& rect, StretchType st) { // width and height of rectangle - auto rect_width = rect.GetWidth(); - auto rect_height = rect.GetHeight(); + const auto rect_width = rect.GetWidth(); + const auto rect_height = rect.GetHeight(); if (rect_width < 0) SetRotationY(180); @@ -1102,16 +1106,16 @@ void Actor::StretchTo(const RectF& r) { // width and height of rectangle - auto width = r.GetWidth(); - auto height = r.GetHeight(); + const auto width = r.GetWidth(); + const auto height = r.GetHeight(); // center of the rectangle - auto cx = r.left + width / 2.0f; - auto cy = r.top + height / 2.0f; + const auto cx = r.left + width / 2.0f; + const auto cy = r.top + height / 2.0f; // zoom fActor needed to scale the Actor to fill the rectangle - auto fNewZoomX = width / m_size.x; - auto fNewZoomY = height / m_size.y; + const auto fNewZoomX = width / m_size.x; + const auto fNewZoomY = height / m_size.y; SetXY(cx, cy); SetZoomX(fNewZoomX); @@ -1373,7 +1377,7 @@ Actor::RunCommands(const LuaReference& cmds, const LuaReference* pParamTable) return; } - auto L = LUA->Get(); + auto* L = LUA->Get(); // function cmds.PushSelf(L); @@ -1404,7 +1408,7 @@ float Actor::GetTweenTimeLeft() const { float tot = 0; - for (auto m_Tween : m_Tweens) + for (auto* m_Tween : m_Tweens) tot += m_Tween->info.m_fTimeLeftInTween; return tot; @@ -1555,7 +1559,7 @@ Actor::AddCommand(const std::string& sCmdName, bool warn) { if (HasCommand(sCmdName) && warn) { - auto sWarning = + const auto sWarning = GetLineage() + "'s command '" + sCmdName + "' defined twice"; LuaHelpers::ReportScriptError(sWarning, "COMMAND_DEFINED_TWICE"); } @@ -1579,7 +1583,7 @@ Actor::HasCommand(const std::string& sCmdName) const const apActorCommands* Actor::GetCommand(const std::string& sCommandName) const { - auto it = m_mapNameToCommands.find(sCommandName); + const auto it = m_mapNameToCommands.find(sCommandName); if (it == m_mapNameToCommands.end()) return nullptr; return &it->second; @@ -1594,8 +1598,8 @@ Actor::HandleMessage(const Message& msg) void Actor::PlayCommandNoRecurse(const Message& msg) { - auto pCmd = GetCommand(msg.GetName()); - if (pCmd != NULL && (*pCmd)->IsSet() && !(*pCmd)->IsNil()) { + const auto* pCmd = GetCommand(msg.GetName()); + if (pCmd != nullptr && (*pCmd)->IsSet() && !(*pCmd)->IsNil()) { RunCommands(*pCmd, &msg.GetParamTable()); } } @@ -1614,8 +1618,8 @@ Actor::SetParent(Actor* pParent) { m_pParent = pParent; - auto L = LUA->Get(); - auto iTop = lua_gettop(L); + auto* L = LUA->Get(); + const auto iTop = lua_gettop(L); this->PushContext(L); lua_pushstring(L, "__index"); @@ -1669,7 +1673,7 @@ class LunaActor : public Luna } static int sleep(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: sleep(%f): time must not be negative", fTime); @@ -1680,7 +1684,7 @@ class LunaActor : public Luna } static int linear(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: linear(%f): tween time must not be negative", fTime); @@ -1691,7 +1695,7 @@ class LunaActor : public Luna } static int accelerate(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: accelerate(%f): tween time must not be negative", fTime); @@ -1702,7 +1706,7 @@ class LunaActor : public Luna } static int decelerate(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: decelerate(%f): tween time must not be negative", fTime); @@ -1713,7 +1717,7 @@ class LunaActor : public Luna } static int spring(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: spring(%f): tween time must not be negative", fTime); @@ -1724,13 +1728,13 @@ class LunaActor : public Luna } static int tween(T* p, lua_State* L) { - auto fTime = FArg(1); + const auto fTime = FArg(1); if (fTime < 0) { LuaHelpers::ReportScriptErrorFmt( "Lua: tween(%f): tween time must not be negative", fTime); COMMON_RETURN_SELF; } - auto pTween = ITween::CreateFromStack(L, 2); + auto* const pTween = ITween::CreateFromStack(L, 2); if (pTween != nullptr) { p->BeginTweening(fTime, pTween); } @@ -1748,7 +1752,7 @@ class LunaActor : public Luna } static int hurrytweening(T* p, lua_State* L) { - auto time = FArg(1); + const auto time = FArg(1); if (time < 0.0f) { luaL_error(L, "Tweening hurry factor cannot be negative. %f", time); } @@ -2219,7 +2223,7 @@ class LunaActor : public Luna } static int effectperiod(T* p, lua_State* L) { - auto fPeriod = FArg(1); + const auto fPeriod = FArg(1); if (fPeriod <= 0) { LuaHelpers::ReportScriptErrorFmt( "Effect period (%f) must be positive; ignoring", fPeriod); @@ -2230,10 +2234,10 @@ class LunaActor : public Luna } static int effecttiming(T* p, lua_State* L) { - auto rth = FArg(1); - auto hah = FArg(2); - auto rtf = FArg(3); - auto haz = FArg(4); + const auto rth = FArg(1); + const auto hah = FArg(2); + const auto rtf = FArg(3); + const auto haz = FArg(4); // Compatibility: hold_at_full is optional. float haf = 0; if (lua_isnumber(L, 5) != 0) { @@ -2391,7 +2395,7 @@ class LunaActor : public Luna lua_pushvalue(L, 2); ParamTable.SetFromStack(L); - Message msg(SArg(1), ParamTable); + const Message msg(SArg(1), ParamTable); p->HandleMessage(msg); COMMON_RETURN_SELF; @@ -2415,7 +2419,7 @@ class LunaActor : public Luna } static int GetCommand(T* p, lua_State* L) { - auto pCommand = p->GetCommand(SArg(1)); + const auto* const pCommand = p->GetCommand(SArg(1)); if (pCommand == nullptr) lua_pushnil(L); else @@ -2581,7 +2585,7 @@ class LunaActor : public Luna } static int GetParent(T* p, lua_State* L) { - auto pParent = p->GetParent(); + auto* pParent = p->GetParent(); if (pParent == nullptr) lua_pushnil(L); else @@ -2590,7 +2594,7 @@ class LunaActor : public Luna } static int GetFakeParent(T* p, lua_State* L) { - auto fake = p->GetFakeParent(); + auto* fake = p->GetFakeParent(); if (fake == nullptr) { lua_pushnil(L); } else { @@ -2601,9 +2605,9 @@ class LunaActor : public Luna static int SetFakeParent(T* p, lua_State* L) { if (lua_isnoneornil(L, 1)) { - p->SetFakeParent(NULL); + p->SetFakeParent(nullptr); } else { - auto fake = Luna::check(L, 1); + auto* const fake = Luna::check(L, 1); p->SetFakeParent(fake); } COMMON_RETURN_SELF; @@ -2617,7 +2621,7 @@ class LunaActor : public Luna static size_t get_state_index(T* p, lua_State* L, int stack_index) { // Lua is one indexed. - auto i = IArg(stack_index) - 1; + const auto i = IArg(stack_index) - 1; const auto si = static_cast(i); if (i < 0 || si >= p->GetNumWrapperStates()) { luaL_error(L, "%d is not a valid wrapper state index.", i + 1); @@ -2626,7 +2630,7 @@ class LunaActor : public Luna } static int RemoveWrapperState(T* p, lua_State* L) { - auto si = get_state_index(p, L, 1); + const auto si = get_state_index(p, L, 1); p->RemoveWrapperState(si); COMMON_RETURN_SELF; } @@ -2637,7 +2641,7 @@ class LunaActor : public Luna } static int GetWrapperState(T* p, lua_State* L) { - auto si = get_state_index(p, L, 1); + const auto si = get_state_index(p, L, 1); p->GetWrapperState(si)->PushSelf(L); return 1; } @@ -2658,7 +2662,7 @@ class LunaActor : public Luna static int LoadXY(T* p, lua_State* L) { - auto doot = FILTERMAN->loadpos(p->GetName()); + const auto doot = FILTERMAN->loadpos(p->GetName()); p->SetX(static_cast(doot.first)); p->SetY(static_cast(doot.second)); COMMON_RETURN_SELF; diff --git a/src/Etterna/Actor/Base/Actor.h b/src/Etterna/Actor/Base/Actor.h index 5e8013e97a..8092ccaba2 100644 --- a/src/Etterna/Actor/Base/Actor.h +++ b/src/Etterna/Actor/Base/Actor.h @@ -5,12 +5,13 @@ #include "Etterna/Models/Lua/LuaReference.h" #include "RageUtil/Misc/RageTypes.h" #include "RageUtil/Utils/RageUtil_AutoPtr.h" +#include "Etterna/Singletons/MessageManager.h" +#include "Tween.h" + #include class XNode; struct lua_State; class LuaClass; -#include "Etterna/Singletons/MessageManager.h" -#include "Tween.h" using apActorCommands = AutoPtrCopyOnWrite; @@ -71,35 +72,6 @@ LuaDeclareType(VertAlign); // number of diffuse colors, so change this at your own risk. -Kyz #define NUM_DIFFUSE_COLORS 4 -// ssc futures: -/* -enum EffectAction -{ - EffectAction_None, // no_effect - // [Diffuse] - EffectAction_DiffuseBlink, // diffuse_blink - EffectAction_DiffuseShift, // diffuse_shift - EffectAction_DiffuseRamp, // diffuse_ramp - EffectAction_Rainbow, // rainbow - // [Glow] - EffectAction_GlowBlink, // glow_blink - EffectAction_GlowShift, // glow_shift - EffectAction_GlowRamp, // glow_ramp - // [Translate] - EffectAction_Bob, - EffectAction_Bounce, - EffectAction_Vibrate, - // [Rotate] - EffectAction_Spin, - EffectAction_Wag, - // [Zoom] - EffectAction_Pulse, - NUM_EffectAction, - EffectAction_Invalid -}; -LuaDeclareType( EffectAction ); -*/ - /** @brief Base class for all objects that appear on the screen. */ class Actor : public MessageSubscriber { @@ -111,7 +83,7 @@ class Actor : public MessageSubscriber * @param cpy the new Actor to use in place of this one. */ Actor(const Actor& cpy); ~Actor() override; - virtual Actor* Copy() const; + [[nodiscard]] virtual Actor* Copy() const; virtual void InitState(); virtual void LoadFromNode(const XNode* pNode); @@ -120,7 +92,6 @@ class Actor : public MessageSubscriber float fTimeNoOffset, float fBeatNoOffset); static void SetPlayerBGMBeat(float fBeat, float fBeatNoOffset); - static void SetBGMLight(int iLightNumber, float fCabinetLights); /** * @brief The list of the different effects. @@ -161,55 +132,6 @@ class Actor : public MessageSubscriber NUM_CLOCKS }; - /* - * @brief What type of Effect this is. - * - * This is an internal enum for checking if an effect can be run; - * You can't have more than one of most EffectTypes in the Effect list. (You - * might be able to have mutliple EffectType_Translates; not sure yet.) -aj - */ - /* - enum EffectType { - EffectType_Diffuse, - EffectType_Glow, - EffectType_Translate, - EffectType_Rotate, - EffectType_Zoom, - NUM_EffectType, - EffectType_Invalid - }; - */ - - // todo: use this instead of the Effect enum -aj - /* - // This is similar to Attributes in BitmapText as far as implementation. - struct Effect - { - Effect() : m_Action(EffectAction_None), m_Type(EffectType_Invalid), - m_fSecsIntoEffect(0), m_fEffectDelta(0), m_fEffectRampUp(0.5f), - m_fEffectHoldAtHalf(0), m_fEffectRampDown(0.5f), m_fEffectHoldAtZero(0), - m_fEffectOffset(0), m_EffectClock(CLOCK_TIMER), - m_vEffectMagnitude(RageVector3(0,0,10)), m_effectColor1(RageColor(1,1,1,1)), - m_effectColor2(RageColor(1,1,1,1)) { } - - std::string m_sName; // friendly name - EffectAction m_Action; // replaces the old Effect enum - EffectType m_Type; // determined by EffectAction - float m_fSecsIntoEffect; - float m_fEffectDelta; - RageColor m_EffectColor1; - RageColor m_EffectColor2; - RageVector3 m_vEffectMagnitude; - EffectClock m_EffectClock; - // units depend on m_EffectClock - float m_fEffectRampUp; - float m_fEffectHoldAtHalf; - float m_fEffectRampDown; - float m_fEffectHoldAtZero; - float m_fEffectOffset; - }; - */ - /** * @brief The present state for the Tween. */ @@ -231,7 +153,7 @@ class Actor : public MessageSubscriber RageVector3 rotation; RageVector4 quat; RageVector3 scale; - float fSkewX, fSkewY; + float fSkewX{}, fSkewY{}; /** * @brief The amount of cropping involved. * @@ -250,11 +172,11 @@ class Actor : public MessageSubscriber /** @brief The glow color for this TweenState. */ RageColor glow; /** @brief A magical value that nobody really knows the use for. ;) */ - float aux; + float aux{}; }; // PartiallyOpaque broken out of Draw for reuse and clarity. - bool PartiallyOpaque(); + [[nodiscard]] bool PartiallyOpaque() const; bool IsOver(float mx, float my); Actor* GetFakeParentOrParent(); // fake parent > parent -mina @@ -281,7 +203,7 @@ class Actor : public MessageSubscriber * Subclasses may wish to overwrite this to allow for * aborted actors. * @return false, as by default Actors shouldn't be aborted on drawing. */ - virtual bool EarlyAbortDraw() const { return false; } + [[nodiscard]] virtual bool EarlyAbortDraw() const { return false; } /** @brief Calculate values that may be needed for drawing. */ virtual void PreDraw(); /** @brief Reset internal diffuse and glow. */ @@ -320,13 +242,17 @@ class Actor : public MessageSubscriber virtual void SetCurrentTweenStart() {} virtual void EraseHeadTween() {} virtual void UpdatePercentThroughTween(float PercentThroughTween) {} - bool get_tween_uses_effect_delta() { return m_tween_uses_effect_delta; } + + [[nodiscard]] bool get_tween_uses_effect_delta() const + { + return m_tween_uses_effect_delta; + } void set_tween_uses_effect_delta(bool t) { m_tween_uses_effect_delta = t; } /** * @brief Retrieve the Actor's name. * @return the Actor's name. */ - const std::string& GetName() const { return m_sName; } + [[nodiscard]] const std::string& GetName() const { return m_sName; } /** * @brief Set the Actor's name to a new one. * @param sName the new name for the Actor. */ @@ -338,35 +264,38 @@ class Actor : public MessageSubscriber /** * @brief Retrieve the Actor's parent. * @return the Actor's parent. */ - Actor* GetParent() { return m_pParent; } + [[nodiscard]] Actor* GetParent() const { return m_pParent; } /** * @brief Retrieve the Actor's lineage. * @return the Actor's lineage. */ - std::string GetLineage() const; + [[nodiscard]] std::string GetLineage() const; void SetFakeParent(Actor* mailman) { m_FakeParent = mailman; } - Actor* GetFakeParent() { return m_FakeParent; } + [[nodiscard]] Actor* GetFakeParent() const { return m_FakeParent; } void AddWrapperState(); void RemoveWrapperState(size_t i); Actor* GetWrapperState(size_t i); - size_t GetNumWrapperStates() const { return m_WrapperStates.size(); } + [[nodiscard]] size_t GetNumWrapperStates() const + { + return m_WrapperStates.size(); + } /** * @brief Retrieve the Actor's x position. * @return the Actor's x position. */ - float GetX() const { return m_current.pos.x; }; + [[nodiscard]] float GetX() const { return m_current.pos.x; }; /** * @brief Retrieve the Actor's y position. * @return the Actor's y position. */ - float GetY() const { return m_current.pos.y; }; + [[nodiscard]] float GetY() const { return m_current.pos.y; }; /** * @brief Retrieve the Actor's z position. * @return the Actor's z position. */ - float GetZ() const { return m_current.pos.z; }; - float GetDestX() const { return DestTweenState().pos.x; }; - float GetDestY() const { return DestTweenState().pos.y; }; - float GetDestZ() const { return DestTweenState().pos.z; }; + [[nodiscard]] float GetZ() const { return m_current.pos.z; }; + [[nodiscard]] float GetDestX() const { return DestTweenState().pos.x; }; + [[nodiscard]] float GetDestY() const { return DestTweenState().pos.y; }; + [[nodiscard]] float GetDestZ() const { return DestTweenState().pos.z; }; void SetX(float x) { DestTweenState().pos.x = x; }; void SetY(float y) { DestTweenState().pos.y = y; }; void SetZ(float z) { DestTweenState().pos.z = z; }; @@ -389,13 +318,15 @@ class Actor : public MessageSubscriber void AddZ(float z) { SetZ(GetDestZ() + z); } // height and width vary depending on zoom - float GetUnzoomedWidth() const { return m_size.x; } - float GetUnzoomedHeight() const { return m_size.y; } - float GetZoomedWidth() const + [[nodiscard]] float GetUnzoomedWidth() const { return m_size.x; } + [[nodiscard]] float GetUnzoomedHeight() const { return m_size.y; } + + [[nodiscard]] float GetZoomedWidth() const { return m_size.x * m_baseScale.x * DestTweenState().scale.x; } - float GetZoomedHeight() const + + [[nodiscard]] float GetZoomedHeight() const { return m_size.y * m_baseScale.y * DestTweenState().scale.y; } @@ -403,11 +334,11 @@ class Actor : public MessageSubscriber void SetHeight(float height) { m_size.y = height; } // Base values - float GetBaseZoomX() const { return m_baseScale.x; } + [[nodiscard]] float GetBaseZoomX() const { return m_baseScale.x; } void SetBaseZoomX(float zoom) { m_baseScale.x = zoom; } - float GetBaseZoomY() const { return m_baseScale.y; } + [[nodiscard]] float GetBaseZoomY() const { return m_baseScale.y; } void SetBaseZoomY(float zoom) { m_baseScale.y = zoom; } - float GetBaseZoomZ() const { return m_baseScale.z; } + [[nodiscard]] float GetBaseZoomZ() const { return m_baseScale.z; } void SetBaseZoomZ(float zoom) { m_baseScale.z = zoom; } void SetBaseZoom(float zoom) { @@ -427,19 +358,19 @@ class Actor : public MessageSubscriber * * Note that this is not accurate in some cases. * @return the zoom factor for the x coordinate of the Actor. */ - float GetZoom() const { return DestTweenState().scale.x; } + [[nodiscard]] float GetZoom() const { return DestTweenState().scale.x; } /** * @brief Retrieve the zoom factor for the x coordinate of the Actor. * @return the zoom factor for the x coordinate of the Actor. */ - float GetZoomX() const { return DestTweenState().scale.x; } + [[nodiscard]] float GetZoomX() const { return DestTweenState().scale.x; } /** * @brief Retrieve the zoom factor for the y coordinate of the Actor. * @return the zoom factor for the y coordinate of the Actor. */ - float GetZoomY() const { return DestTweenState().scale.y; } + [[nodiscard]] float GetZoomY() const { return DestTweenState().scale.y; } /** * @brief Retrieve the zoom factor for the z coordinate of the Actor. * @return the zoom factor for the z coordinate of the Actor. */ - float GetZoomZ() const { return DestTweenState().scale.z; } + [[nodiscard]] float GetZoomZ() const { return DestTweenState().scale.z; } /** * @brief Set the zoom factor for all dimensions of the Actor. * @param zoom the zoom factor for all dimensions. */ @@ -469,9 +400,18 @@ class Actor : public MessageSubscriber void ZoomToWidth(float zoom) { SetZoomX(zoom / GetUnzoomedWidth()); } void ZoomToHeight(float zoom) { SetZoomY(zoom / GetUnzoomedHeight()); } - float GetRotationX() const { return DestTweenState().rotation.x; } - float GetRotationY() const { return DestTweenState().rotation.y; } - float GetRotationZ() const { return DestTweenState().rotation.z; } + [[nodiscard]] float GetRotationX() const + { + return DestTweenState().rotation.x; + } + [[nodiscard]] float GetRotationY() const + { + return DestTweenState().rotation.y; + } + [[nodiscard]] float GetRotationZ() const + { + return DestTweenState().rotation.z; + } void SetRotationX(float rot) { DestTweenState().rotation.x = rot; } void SetRotationY(float rot) { DestTweenState().rotation.y = rot; } void SetRotationZ(float rot) { DestTweenState().rotation.z = rot; } @@ -485,20 +425,31 @@ class Actor : public MessageSubscriber void AddRotationR(float rot); void SetSkewX(float fAmount) { DestTweenState().fSkewX = fAmount; } - float GetSkewX(float /* fAmount */) const + + [[nodiscard]] float GetSkewX(float /* fAmount */) const { return DestTweenState().fSkewX; } void SetSkewY(float fAmount) { DestTweenState().fSkewY = fAmount; } - float GetSkewY(float /* fAmount */) const + + [[nodiscard]] float GetSkewY(float /* fAmount */) const { return DestTweenState().fSkewY; } - float GetCropLeft() const { return DestTweenState().crop.left; } - float GetCropTop() const { return DestTweenState().crop.top; } - float GetCropRight() const { return DestTweenState().crop.right; } - float GetCropBottom() const { return DestTweenState().crop.bottom; } + [[nodiscard]] float GetCropLeft() const + { + return DestTweenState().crop.left; + } + [[nodiscard]] float GetCropTop() const { return DestTweenState().crop.top; } + [[nodiscard]] float GetCropRight() const + { + return DestTweenState().crop.right; + } + [[nodiscard]] float GetCropBottom() const + { + return DestTweenState().crop.bottom; + } void SetCropLeft(float percent) { DestTweenState().crop.left = percent; } void SetCropTop(float percent) { DestTweenState().crop.top = percent; } void SetCropRight(float percent) { DestTweenState().crop.right = percent; } @@ -524,13 +475,17 @@ class Actor : public MessageSubscriber }; virtual void SetDiffuseAlpha(float f) { - for (int i = 0; i < NUM_DIFFUSE_COLORS; ++i) { - RageColor c = GetDiffuses(i); + for (auto i = 0; i < NUM_DIFFUSE_COLORS; ++i) { + auto c = GetDiffuses(i); c.a = f; SetDiffuses(i, c); } } - float GetCurrentDiffuseAlpha() const { return m_current.diffuse[0].a; } + + [[nodiscard]] float GetCurrentDiffuseAlpha() const + { + return m_current.diffuse[0].a; + } void SetDiffuseColor(const RageColor& c); void SetDiffuses(int i, const RageColor& c) { @@ -568,17 +523,26 @@ class Actor : public MessageSubscriber { DestTweenState().diffuse[0] = DestTweenState().diffuse[2] = c; }; - RageColor GetDiffuse() const { return DestTweenState().diffuse[0]; }; - RageColor GetDiffuses(int i) const { return DestTweenState().diffuse[i]; }; - float GetDiffuseAlpha() const { return DestTweenState().diffuse[0].a; }; + [[nodiscard]] RageColor GetDiffuse() const + { + return DestTweenState().diffuse[0]; + }; + [[nodiscard]] RageColor GetDiffuses(int i) const + { + return DestTweenState().diffuse[i]; + }; + [[nodiscard]] float GetDiffuseAlpha() const + { + return DestTweenState().diffuse[0].a; + }; void SetGlow(const RageColor& c) { DestTweenState().glow = c; }; - RageColor GetGlow() const { return DestTweenState().glow; }; + [[nodiscard]] RageColor GetGlow() const { return DestTweenState().glow; }; void SetAux(float f) { DestTweenState().aux = f; } - float GetAux() const { return m_current.aux; } + [[nodiscard]] 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 std::string& sCommandName); @@ -586,7 +550,7 @@ class Actor : public MessageSubscriber virtual void FinishTweening(); virtual void HurryTweening(float factor); // Let ActorFrame and BGAnimation override - virtual float GetTweenTimeLeft() + [[nodiscard]] virtual float GetTweenTimeLeft() const; // Amount of time until all tweens have stopped TweenState& DestTweenState() // where Actor will end when its tween finish { @@ -595,7 +559,8 @@ class Actor : public MessageSubscriber else return m_Tweens.back()->state; } - const TweenState& DestTweenState() const + + [[nodiscard]] const TweenState& DestTweenState() const { return const_cast(this)->DestTweenState(); } @@ -638,10 +603,10 @@ class Actor : public MessageSubscriber Effect GetEffect(int i) const { return m_Effects[i]; } #else void StopEffect() { m_Effect = no_effect; } - Effect GetEffect() const { return m_Effect; } + [[nodiscard]] Effect GetEffect() const { return m_Effect; } #endif - float GetSecsIntoEffect() const { return m_fSecsIntoEffect; } - float GetEffectDelta() const { return m_fEffectDelta; } + [[nodiscard]] float GetSecsIntoEffect() const { return m_fSecsIntoEffect; } + [[nodiscard]] float GetEffectDelta() const { return m_fEffectDelta; } // todo: account for SSC_FUTURES by adding an effect as an arg to each one // -aj @@ -649,7 +614,7 @@ class Actor : public MessageSubscriber void SetEffectColor2(const RageColor& c) { m_effectColor2 = c; } void RecalcEffectPeriod(); void SetEffectPeriod(float fTime); - float GetEffectPeriod() const { return m_effect_period; } + [[nodiscard]] float GetEffectPeriod() const { return m_effect_period; } bool SetEffectTiming(float ramp_toh, float at_half, float ramp_tof, @@ -665,7 +630,11 @@ class Actor : public MessageSubscriber { m_vEffectMagnitude = vec; } - RageVector3 GetEffectMagnitude() const { return m_vEffectMagnitude; } + + [[nodiscard]] RageVector3 GetEffectMagnitude() const + { + return m_vEffectMagnitude; + } void ResetEffectTimeIfDifferent(Effect new_effect); void SetEffectDiffuseBlink(float fEffectPeriodSeconds, @@ -698,7 +667,7 @@ class Actor : public MessageSubscriber /** * @brief Determine if the Actor is visible at this time. * @return true if it's visible, false otherwise. */ - bool GetVisible() const { return m_bVisible; } + [[nodiscard]] bool GetVisible() const { return m_bVisible; } void SetVisible(bool b) { m_bVisible = b; } void SetShadowLength(float fLength) { @@ -710,7 +679,7 @@ class Actor : public MessageSubscriber void SetShadowColor(const RageColor& c) { m_ShadowColor = c; } // TODO: Implement hibernate as a tween type? void SetDrawOrder(int iOrder) { m_iDrawOrder = iOrder; } - int GetDrawOrder() const { return m_iDrawOrder; } + [[nodiscard]] int GetDrawOrder() const { return m_iDrawOrder; } virtual void EnableAnimation(bool b) { @@ -747,8 +716,9 @@ class Actor : public MessageSubscriber void AddCommand(const std::string& sCmdName, const apActorCommands& apac, bool warn = true); - bool HasCommand(const std::string& sCmdName) const; - const apActorCommands* GetCommand(const std::string& sCommandName) const; + [[nodiscard]] bool HasCommand(const std::string& sCmdName) const; + [[nodiscard]] const apActorCommands* GetCommand( + const std::string& sCommandName) const; void PlayCommand(const std::string& sCommandName) { HandleMessage(Message(sCommandName)); @@ -758,8 +728,9 @@ class Actor : public MessageSubscriber // Commands by reference virtual void RunCommands(const LuaReference& cmds, const LuaReference* pParamTable = nullptr); - void RunCommands(const apActorCommands& cmds, - const LuaReference* pParamTable = nullptr) + + virtual void RunCommands(const apActorCommands& cmds, + const LuaReference* pParamTable = nullptr) { this->RunCommands(*cmds, pParamTable); } // convenience @@ -780,9 +751,9 @@ class Actor : public MessageSubscriber void HandleMessage(const Message& msg) override; // Animation - virtual int GetNumStates() const { return 1; } + [[nodiscard]] virtual int GetNumStates() const { return 1; } virtual void SetState(int /* iNewState */) {} - virtual float GetAnimationLengthSeconds() const { return 0; } + [[nodiscard]] virtual float GetAnimationLengthSeconds() const { return 0; } virtual void SetSecondsIntoAnimation(float) {} virtual void SetUpdateRate(float) {} virtual float GetUpdateRate() { return 1.0f; } @@ -800,7 +771,7 @@ class Actor : public MessageSubscriber Actor* m_FakeParent; // WrapperStates provides a way to wrap the actor inside ActorFrames, // applicable to any actor, not just ones the theme creates. - vector m_WrapperStates; + std::vector m_WrapperStates; /** @brief Some general information about the Tween. */ struct TweenInfo @@ -836,7 +807,7 @@ class Actor : public MessageSubscriber TweenState state; TweenInfo info; }; - vector m_Tweens; + std::vector m_Tweens; /** @brief Temporary variables that are filled just before drawing */ TweenState* m_pTempState{}; @@ -876,7 +847,7 @@ class Actor : public MessageSubscriber /* This can be used in lieu of the fDeltaTime parameter to Update() to * follow the effect clock. Actor::Update must be called first. */ - float GetEffectDeltaTime() const { return m_fEffectDelta; } + [[nodiscard]] float GetEffectDeltaTime() const { return m_fEffectDelta; } // todo: account for SSC_FUTURES by having these be vectors too -aj RageColor m_effectColor1; @@ -912,12 +883,12 @@ class Actor : public MessageSubscriber // global state static float g_fCurrentBGMTime, g_fCurrentBGMBeat; static float g_fCurrentBGMTimeNoOffset, g_fCurrentBGMBeatNoOffset; - static vector g_vfCurrentBGMBeatPlayer; - static vector g_vfCurrentBGMBeatPlayerNoOffset; + static std::vector g_vfCurrentBGMBeatPlayer; + static std::vector g_vfCurrentBGMBeatPlayerNoOffset; private: // commands - map m_mapNameToCommands; + std::map m_mapNameToCommands; }; #endif diff --git a/src/Etterna/Actor/Base/ActorFrame.cpp b/src/Etterna/Actor/Base/ActorFrame.cpp index 8544f16308..57ef71a51b 100644 --- a/src/Etterna/Actor/Base/ActorFrame.cpp +++ b/src/Etterna/Actor/Base/ActorFrame.cpp @@ -1,7 +1,6 @@ #include "Etterna/Globals/global.h" #include "ActorFrame.h" #include "ActorUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "RageUtil/Graphics/RageDisplay.h" #include "RageUtil/Utils/RageUtil.h" @@ -73,9 +72,9 @@ ActorFrame::ActorFrame(const ActorFrame& cpy) * them. If not, the derived class owns the children. This must preserve * the current order of m_SubActors. */ if (m_bDeleteChildren) { - for (auto m_SubActor : cpy.m_SubActors) { - Actor* pActor = m_SubActor->Copy(); - this->AddChild(pActor); + for (auto* m_SubActor : cpy.m_SubActors) { + auto* pActor = m_SubActor->Copy(); + this->ActorFrame::AddChild(pActor); } } } @@ -83,8 +82,10 @@ ActorFrame::ActorFrame(const ActorFrame& cpy) void ActorFrame::InitState() { - FOREACH(Actor*, m_SubActors, a) - (*a)->InitState(); + for (auto& a : m_SubActors) { + a->InitState(); + } + Actor::InitState(); } @@ -121,8 +122,8 @@ ActorFrame::LoadChildrenFromNode(const XNode* pNode) ASSERT(m_bDeleteChildren); // Load children - const XNode* pChildren = pNode->GetChild("children"); - bool bArrayOnly = false; + const auto* pChildren = pNode->GetChild("children"); + auto bArrayOnly = false; if (pChildren == nullptr) { bArrayOnly = true; pChildren = pNode; @@ -133,7 +134,7 @@ ActorFrame::LoadChildrenFromNode(const XNode* pNode) if (bArrayOnly && !IsAnInt(pChild->GetName())) continue; - Actor* pChildActor = ActorUtil::LoadFromNode(pChild, this); + auto* pChildActor = ActorUtil::LoadFromNode(pChild, this); if (pChildActor) AddChild(pChildActor); } @@ -163,8 +164,7 @@ ActorFrame::AddChild(Actor* pActor) void ActorFrame::RemoveChild(Actor* pActor) { - vector::iterator iter = - find(m_SubActors.begin(), m_SubActors.end(), pActor); + const auto iter = find(m_SubActors.begin(), m_SubActors.end(), pActor); if (iter != m_SubActors.end()) m_SubActors.erase(iter); } @@ -172,19 +172,21 @@ ActorFrame::RemoveChild(Actor* pActor) void ActorFrame::TransferChildren(ActorFrame* pTo) { - FOREACH(Actor*, m_SubActors, i) - pTo->AddChild(*i); + for (auto* a : m_SubActors) { + pTo->AddChild(a); + } + RemoveAllChildren(); } Actor* ActorFrame::GetChild(const std::string& sName) { - FOREACH(Actor*, m_SubActors, a) - { - if ((*a)->GetName() == sName) - return *a; + for (auto* a : m_SubActors) { + if (a->GetName() == sName) + return a; } + return nullptr; } @@ -197,8 +199,7 @@ ActorFrame::RemoveAllChildren() void ActorFrame::MoveToTail(Actor* pActor) { - vector::iterator iter = - find(m_SubActors.begin(), m_SubActors.end(), pActor); + const auto iter = find(m_SubActors.begin(), m_SubActors.end(), pActor); if (iter == m_SubActors.end()) // didn't find FAIL_M("Nonexistent actor"); @@ -209,8 +210,7 @@ ActorFrame::MoveToTail(Actor* pActor) void ActorFrame::MoveToHead(Actor* pActor) { - vector::iterator iter = - find(m_SubActors.begin(), m_SubActors.end(), pActor); + const auto iter = find(m_SubActors.begin(), m_SubActors.end(), pActor); if (iter == m_SubActors.end()) // didn't find FAIL_M("Nonexistent actor"); @@ -253,7 +253,7 @@ ActorFrame::DrawPrimitives() // Actor::DrawPrimitives(); if (unlikely(!m_DrawFunction.IsNil())) { - Lua* L = LUA->Get(); + auto* L = LUA->Get(); m_DrawFunction.PushSelf(L); if (lua_isnil(L, -1)) { LUA->Release(L); @@ -267,19 +267,19 @@ ActorFrame::DrawPrimitives() return; } - RageColor diffuse = m_pTempState->diffuse[0]; - RageColor glow = m_pTempState->glow; + const auto diffuse = m_pTempState->diffuse[0]; + const auto glow = m_pTempState->glow; - // Word of warning: Actor::Draw duplicates the structure of how an Actor - // is drawn inside of an ActorFrame for its wrapping feature. So if - // you're adding something new to ActorFrames that affects how Actors are - // drawn, make sure to also apply it in Actor::Draw's handling of the - // wrappers. -Kyz + // Word of warning: Actor::Draw duplicates the structure of how an + // Actor is drawn inside of an ActorFrame for its wrapping feature. So + // if you're adding something new to ActorFrames that affects how Actors + // are drawn, make sure to also apply it in Actor::Draw's handling of + // the wrappers. -Kyz - // draw all sub-ActorFrames while we're in the ActorFrame's local coordinate - // space + // draw all sub-ActorFrames while we're in the ActorFrame's local + // coordinate space if (m_bDrawByZPosition) { - vector subs = m_SubActors; + auto subs = m_SubActors; ActorUtil::SortByZPosition(subs); for (auto& sub : subs) { sub->SetInternalDiffuse(diffuse); @@ -317,15 +317,15 @@ IdenticalChildrenSingleApplier(lua_State* L) { // First arg is the table of items, get the last object. // It is the one that would have been in the children table in the old - // version. The other args are meant for the function. The upvalue for this - // function is the function the theme tried to call. + // version. The other args are meant for the function. The upvalue for + // this function is the function the theme tried to call. lua_rawgeti(L, 1, lua_objlen(L, 1)); // stack: table, args, obj lua_insert(L, 2); // stack: table, obj, args lua_pushvalue(L, lua_upvalueindex(1)); // stack: table, obj, args, func lua_insert(L, 2); // stack: table, func, obj, args - int args_count = lua_gettop(L) - 2; - // Not using RunScriptOnStack because we're inside a lua call already and - // we want an error to propagate up. + const auto args_count = lua_gettop(L) - 2; + // Not using RunScriptOnStack because we're inside a lua call already + // and we want an error to propagate up. lua_call(L, args_count, LUA_MULTRET); // stack: table, return_values return lua_gettop(L) - 1; } @@ -351,7 +351,8 @@ IdenticalChildrenIndexLayer(lua_State* L) lua_gettable(L, 1); // stack: object lua_getmetatable(L, -1); // stack: object, obj_meta lua_getfield(L, -1, "__index"); // stack: object, obj_meta, obj_index - lua_pushvalue(L, 2); // stack: object, obj_meta, obj_index, func_name + lua_pushvalue(L, + 2); // stack: object, obj_meta, obj_index, func_name lua_gettable(L, -2); // stack: object, obj_meta, obj_index, obj_function lua_pushcclosure(L, IdenticalChildrenSingleApplier, @@ -365,10 +366,10 @@ IdenticalChildrenIndexLayer(lua_State* L) static void CreateChildTable(lua_State* L, Actor* a) { - // Old PushChildrenTable assumed that all children had unique names, so only - // the last one of a name ended up in the table that was returned. Create a - // table that will hold all the children that have this name and act as a - // pass through layer for function calls. stack: old_entry + // Old PushChildrenTable assumed that all children had unique names, so + // only the last one of a name ended up in the table that was returned. + // Create a table that will hold all the children that have this name + // and act as a pass through layer for function calls. stack: old_entry lua_createtable(L, 0, 0); // stack: old_entry, table_entry lua_insert(L, -2); // stack: table_entry, old_entry lua_rawseti(L, -2, 1); // stack: table_entry @@ -376,16 +377,17 @@ CreateChildTable(lua_State* L, Actor* a) lua_rawseti(L, -2, 2); // stack: table_entry lua_createtable(L, 0, 1); // stack: table_entry, table_meta lua_pushcfunction( - L, IdenticalChildrenIndexLayer); // stack: table_entry, table_meta, ICIL - lua_setfield(L, -2, "__index"); // stack: table_entry, table_meta - lua_setmetatable(L, -2); // stack: table_entry + L, + IdenticalChildrenIndexLayer); // stack: table_entry, table_meta, ICIL + lua_setfield(L, -2, "__index"); // stack: table_entry, table_meta + lua_setmetatable(L, -2); // stack: table_entry } static void AddToChildTable(lua_State* L, Actor* a) { // stack: table_entry - int next_index = lua_objlen(L, -1) + 1; + const int next_index = lua_objlen(L, -1) + 1; a->PushSelf(L); // stack: table_entry, actor lua_rawseti(L, -2, next_index); // stack: table_entry } @@ -394,28 +396,28 @@ void ActorFrame::PushChildrenTable(lua_State* L) { lua_newtable(L); // stack: all_actors - FOREACH(Actor*, m_SubActors, a) - { - LuaHelpers::Push(L, (*a)->GetName()); // stack: all_actors, name - lua_gettable(L, -2); // stack: all_actors, entry + for (auto& a : m_SubActors) { + LuaHelpers::Push(L, a->GetName()); // stack: all_actors, name + lua_gettable(L, -2); // stack: all_actors, entry if (lua_isnil(L, -1)) { - lua_pop(L, 1); // stack: all_actors - LuaHelpers::Push(L, (*a)->GetName()); // stack: all_actors, name - (*a)->PushSelf(L); // stack: all_actors, name, actor - lua_rawset(L, -3); // stack: all_actors + lua_pop(L, 1); // stack: all_actors + LuaHelpers::Push(L, a->GetName()); // stack: all_actors, name + a->PushSelf(L); // stack: all_actors, name, actor + lua_rawset(L, -3); // stack: all_actors } else { // Fun fact: PushSelf pushes a table. if (lua_objlen(L, -1) > 0) { // stack: all_actors, table_entry - AddToChildTable(L, *a); // stack: all_actors, table_entry - lua_pop(L, 1); // stack: all_actors + AddToChildTable(L, a); // stack: all_actors, table_entry + lua_pop(L, 1); // stack: all_actors } else { // stack: all_actors, old_entry - CreateChildTable(L, *a); // stack: all_actors, table_entry + CreateChildTable(L, a); // stack: all_actors, table_entry LuaHelpers::Push( - L, (*a)->GetName()); // stack: all_actors, table_entry, name - lua_insert(L, -2); // stack: all_actors, name, table_entry - lua_rawset(L, -3); // stack: all_actors + L, + a->GetName()); // stack: all_actors, table_entry, name + lua_insert(L, -2); // stack: all_actors, name, table_entry + lua_rawset(L, -3); // stack: all_actors } } } @@ -424,19 +426,18 @@ ActorFrame::PushChildrenTable(lua_State* L) void ActorFrame::PushChildTable(lua_State* L, const std::string& sName) { - int found = 0; - FOREACH(Actor*, m_SubActors, a) - { - if ((*a)->GetName() == sName) { + auto found = 0; + for (auto& a : m_SubActors) { + if (a->GetName() == sName) { switch (found) { case 0: - (*a)->PushSelf(L); + a->PushSelf(L); break; case 1: - CreateChildTable(L, *a); + CreateChildTable(L, a); break; default: - AddToChildTable(L, *a); + AddToChildTable(L, a); break; } ++found; @@ -451,7 +452,7 @@ void ActorFrame::PlayCommandOnChildren(const std::string& sCommandName, const LuaReference* pParamTable) { - const apActorCommands* pCmd = GetCommand(sCommandName); + const auto* pCmd = GetCommand(sCommandName); if (pCmd != nullptr) RunCommandsOnChildren(*pCmd, pParamTable); } @@ -460,8 +461,8 @@ void ActorFrame::PlayCommandOnLeaves(const std::string& sCommandName, const LuaReference* pParamTable) { - const apActorCommands* pCmd = GetCommand(sCommandName); - if (pCmd != NULL) + const auto* pCmd = GetCommand(sCommandName); + if (pCmd != nullptr) RunCommandsOnLeaves(**pCmd, pParamTable); } @@ -515,7 +516,7 @@ ActorFrame::UpdateInternal(float fDeltaTime) secsSinceLuaUpdateFWasRun += fDeltaTime; if (secsSinceLuaUpdateFWasRun >= m_fUpdateFInterval) { secsSinceLuaUpdateFWasRun = 0; - Lua* L = LUA->Get(); + auto* L = LUA->Get(); m_UpdateFunction.PushSelf(L); if (lua_isnil(L, -1)) { LUA->Release(L); @@ -560,9 +561,9 @@ PropagateActorFrameCommand(FinishTweening) float ActorFrame::GetTweenTimeLeft() const { - float m = Actor::GetTweenTimeLeft(); + auto m = Actor::GetTweenTimeLeft(); - for (auto a : m_SubActors) + for (auto* a : m_SubActors) m = max(m, a->GetTweenTimeLeft()); return m; } @@ -615,7 +616,7 @@ ActorFrame::HandleMessage(const Message& msg) if (msg.IsBroadcast()) return; - for (auto pActor : m_SubActors) { + for (auto* pActor : m_SubActors) { pActor->HandleMessage(msg); } } @@ -678,7 +679,7 @@ class LunaActorFrame : public Luna } static int SetUpdateFunctionInterval(T* p, lua_State* L) { - float seconds = FArg(1); + const auto seconds = FArg(1); if (seconds <= 0) { luaL_error(L, "ActorFrame:SetUpdateRate(%f) Update interval must be " @@ -690,7 +691,7 @@ class LunaActorFrame : public Luna } static int SetUpdateRate(T* p, lua_State* L) { - float rate = FArg(1); + const auto rate = FArg(1); if (rate <= 0) { luaL_error(L, "ActorFrame:SetUpdateRate(%f) Update rate must be " @@ -811,14 +812,14 @@ class LunaActorFrame : public Luna if (coords.size() != 3) { // error } - RageVector3 vTmp = RageVector3(coords[0], coords[1], coords[2]); + const auto vTmp = RageVector3(coords[0], coords[1], coords[2]); p->SetLightDirection(vTmp); COMMON_RETURN_SELF; } static int AddChildFromPath(T* p, lua_State* L) { // this one is tricky, we need to get an Actor from Lua. - Actor* pActor = ActorUtil::MakeActor(SArg(1)); + auto* pActor = ActorUtil::MakeActor(SArg(1)); if (pActor == nullptr) { lua_pushboolean(L, 0); return 1; @@ -830,7 +831,7 @@ class LunaActorFrame : public Luna static int RemoveChild(T* p, lua_State* L) { - Actor* child = p->GetChild(SArg(1)); + auto* child = p->GetChild(SArg(1)); if (child != nullptr) { p->RemoveChild(child); SAFE_DELETE(child); diff --git a/src/Etterna/Actor/Base/ActorFrame.h b/src/Etterna/Actor/Base/ActorFrame.h index f3ff0fc080..49e487a2a0 100644 --- a/src/Etterna/Actor/Base/ActorFrame.h +++ b/src/Etterna/Actor/Base/ActorFrame.h @@ -14,7 +14,7 @@ class ActorFrame : public Actor /** @brief Set up the initial state. */ void InitState() override; void LoadFromNode(const XNode* pNode) override; - ActorFrame* Copy() const override; + [[nodiscard]] ActorFrame* Copy() const override; /** * @brief Add a new child to the ActorFrame. @@ -26,8 +26,13 @@ class ActorFrame : public Actor virtual void RemoveChild(Actor* pActor); void TransferChildren(ActorFrame* pTo); Actor* GetChild(const std::string& sName); - vector GetChildren() { return m_SubActors; } - int GetNumChildren() const { return m_SubActors.size(); } + + [[nodiscard]] std::vector GetChildren() const + { + return m_SubActors; + } + + [[nodiscard]] int GetNumChildren() const { return m_SubActors.size(); } /** @brief Remove all of the children from the frame. */ void RemoveAllChildren(); @@ -48,13 +53,18 @@ class ActorFrame : public Actor { m_DrawFunction = DrawFunction; } + void SetUpdateFunction(const LuaReference& UpdateFunction) { m_UpdateFunction = UpdateFunction; } - LuaReference GetDrawFunction() const { return m_DrawFunction; } - virtual bool AutoLoadChildren() const + [[nodiscard]] LuaReference GetDrawFunction() const + { + return m_DrawFunction; + } + + [[nodiscard]] virtual bool AutoLoadChildren() const { return false; } // derived classes override to automatically LoadChildrenFromNode @@ -62,6 +72,7 @@ class ActorFrame : public Actor { m_bDeleteChildren = bDelete; } + void DeleteAllChildren(); // Commands @@ -86,8 +97,9 @@ class ActorFrame : public Actor } // convenience void RunCommandsOnLeaves( const LuaReference& cmds, - const LuaReference* pParamTable = nullptr) override; /* but not on self */ - bool IsFirstUpdate() const; + const LuaReference* pParamTable = nullptr) override; + /* but not on self */ + [[nodiscard]] bool IsFirstUpdate() const; void UpdateInternal(float fDeltaTime) override; void BeginDraw() override; void DrawPrimitives() override; @@ -105,14 +117,17 @@ class ActorFrame : public Actor m_fUpdateFInterval = ms; } } + void SetUpdateRate(float rate) override { if (rate > 0.0f) { m_fUpdateRate = rate; } } + float GetUpdateRate() override { return m_fUpdateRate; } void SetFOV(float fFOV) { m_fFOV = fFOV; } + void SetVanishPoint(float fX, float fY) { m_fVanishX = fX; @@ -123,6 +138,7 @@ class ActorFrame : public Actor { m_bOverrideLighting = bCustomLighting; } + void SetAmbientLightColor(const RageColor& c) { m_ambientColor = c; } void SetDiffuseLightColor(const RageColor& c) { m_diffuseColor = c; } void SetSpecularLightColor(const RageColor& c) { m_specularColor = c; } @@ -132,11 +148,12 @@ class ActorFrame : public Actor /** @brief Amount of time until all tweens (and all children's tweens) have * stopped: */ - float GetTweenTimeLeft() const override; + [[nodiscard]] float GetTweenTimeLeft() const override; void HandleMessage(const Message& msg) override; void RunCommands(const LuaReference& cmds, const LuaReference* pParamTable = nullptr) override; + void RunCommands(const apActorCommands& cmds, const LuaReference* pParamTable = nullptr) { @@ -147,7 +164,7 @@ class ActorFrame : public Actor void LoadChildrenFromNode(const XNode* pNode); /** @brief The children Actors used by the ActorFrame. */ - vector m_SubActors; + std::vector m_SubActors; bool m_bPropagateCommands; bool m_bDeleteChildren; bool m_bDrawByZPosition; @@ -174,13 +191,14 @@ class ActorFrame : public Actor RageColor m_specularColor; RageVector3 m_lightDirection; }; + /** @brief an ActorFrame that handles deleting children Actors automatically. */ class ActorFrameAutoDeleteChildren : public ActorFrame { public: ActorFrameAutoDeleteChildren() { DeleteChildrenWhenDone(true); } - bool AutoLoadChildren() const override { return true; } - ActorFrameAutoDeleteChildren* Copy() const override; + [[nodiscard]] bool AutoLoadChildren() const override { return true; } + [[nodiscard]] ActorFrameAutoDeleteChildren* Copy() const override; }; #endif diff --git a/src/Etterna/Actor/Base/ActorFrameTexture.h b/src/Etterna/Actor/Base/ActorFrameTexture.h index 7875512207..113a1de792 100644 --- a/src/Etterna/Actor/Base/ActorFrameTexture.h +++ b/src/Etterna/Actor/Base/ActorFrameTexture.h @@ -10,7 +10,7 @@ class ActorFrameTexture : public ActorFrame ActorFrameTexture(); ActorFrameTexture(const ActorFrameTexture& cpy); ~ActorFrameTexture() override; - ActorFrameTexture* Copy() const override; + [[nodiscard]] ActorFrameTexture* Copy() const override; /** * @brief Set the texture name. @@ -24,8 +24,11 @@ class ActorFrameTexture : public ActorFrame /** * @brief Retrieve the texture name. * @return the texture name. */ - std::string GetTextureName() const { return m_sTextureName; } - RageTextureRenderTarget* GetTexture() { return m_pRenderTarget; } + [[nodiscard]] std::string GetTextureName() const { return m_sTextureName; } + [[nodiscard]] RageTextureRenderTarget* GetTexture() const + { + return m_pRenderTarget; + } void EnableDepthBuffer(bool b) { m_bDepthBuffer = b; } void EnableAlphaBuffer(bool b) { m_bAlphaBuffer = b; } @@ -54,8 +57,8 @@ class ActorFrameTextureAutoDeleteChildren : public ActorFrameTexture { public: ActorFrameTextureAutoDeleteChildren() { DeleteChildrenWhenDone(true); } - bool AutoLoadChildren() const override { return true; } - ActorFrameTextureAutoDeleteChildren* Copy() const override; + [[nodiscard]] bool AutoLoadChildren() const override { return true; } + [[nodiscard]] ActorFrameTextureAutoDeleteChildren* Copy() const override; }; #endif diff --git a/src/Etterna/Actor/Base/ActorMultiVertex.cpp b/src/Etterna/Actor/Base/ActorMultiVertex.cpp index a567e2c209..5abb9ba8d2 100644 --- a/src/Etterna/Actor/Base/ActorMultiVertex.cpp +++ b/src/Etterna/Actor/Base/ActorMultiVertex.cpp @@ -1,9 +1,6 @@ #include "Etterna/Globals/global.h" -#include - #include "ActorMultiVertex.h" #include "ActorUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Misc/LocalizedString.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "Etterna/Singletons/LuaManager.h" @@ -13,6 +10,8 @@ #include "RageUtil/Utils/RageUtil.h" #include "Etterna/FileTypes/XmlFile.h" +#include + const float min_state_delay = 0.0001f; static const char* DrawModeNames[] = { @@ -53,7 +52,7 @@ REGISTER_ACTOR_CLASS(ActorMultiVertex); ActorMultiVertex::ActorMultiVertex() { // Use blank texture by default. - RageTextureID ID = TEXTUREMAN->GetDefaultTextureID(); + const auto ID = TEXTUREMAN->GetDefaultTextureID(); _Texture = TEXTUREMAN->LoadTexture(ID); _EffectMode = EffectMode_Normal; @@ -265,9 +264,8 @@ ActorMultiVertex::DrawPrimitives() void ActorMultiVertex::DrawInternal(const AMV_TweenState* TS) { - - int FirstToDraw = TS->FirstToDraw; - int NumToDraw = TS->GetSafeNumToDraw(TS->_DrawMode, TS->NumToDraw); + const auto FirstToDraw = TS->FirstToDraw; + const auto NumToDraw = TS->GetSafeNumToDraw(TS->_DrawMode, TS->NumToDraw); if (NumToDraw == 0) { // Nothing to draw. @@ -327,14 +325,14 @@ ActorMultiVertex::EarlyAbortDraw() const void ActorMultiVertex::SetVertsFromSplinesInternal(size_t num_splines, size_t offset) { - vector& verts = AMV_DestTweenState().vertices; - size_t first = AMV_DestTweenState().FirstToDraw + offset; - size_t num_verts = + auto& verts = AMV_DestTweenState().vertices; + const auto first = AMV_DestTweenState().FirstToDraw + offset; + const auto num_verts = AMV_DestTweenState().GetSafeNumToDraw(AMV_DestTweenState()._DrawMode, AMV_DestTweenState().NumToDraw) - offset; vector tper(num_splines, 0.0f); - float num_parts = + const auto num_parts = (static_cast(num_verts) / static_cast(num_splines)) - 1.0f; for (size_t i = 0; i < num_splines; ++i) { tper[i] = _splines[i].get_max_t() / num_parts; @@ -342,7 +340,7 @@ ActorMultiVertex::SetVertsFromSplinesInternal(size_t num_splines, size_t offset) for (size_t v = 0; v < num_verts; ++v) { vector pos; const int spi = v % num_splines; - auto part = static_cast(v) / num_splines; + const auto part = static_cast(v) / num_splines; _splines[spi].evaluate(part * tper[spi], pos); verts[v + first].p.x = pos[0]; verts[v + first].p.y = pos[1]; @@ -398,14 +396,19 @@ ActorMultiVertex::SetState(size_t i) void ActorMultiVertex::SetAllStateDelays(float delay) { - FOREACH(State, _states, s) { s->delay = delay; } + for (auto& s : _states) { + s.delay = delay; + } } float ActorMultiVertex::GetAnimationLengthSeconds() const { - float tot = 0.0f; - FOREACH_CONST(State, _states, s) { tot += s->delay; } + auto tot = 0.0f; + for (const auto& s : _states) { + tot += s.delay; + } + return tot; } @@ -423,14 +426,14 @@ ActorMultiVertex::SetSecondsIntoAnimation(float seconds) void ActorMultiVertex::UpdateAnimationState(bool force_update) { - AMV_TweenState& dest = AMV_DestTweenState(); - vector& verts = dest.vertices; - vector& qs = dest.quad_states; + auto& dest = AMV_DestTweenState(); + auto& verts = dest.vertices; + auto& qs = dest.quad_states; if (!_use_animation_state || _states.empty() || dest._DrawMode == DrawMode_LineStrip || qs.empty()) { return; } - bool state_changed = force_update; + auto state_changed = force_update; if (_states.size() > 1) { while (_states[_cur_state].delay > min_state_delay && _secs_into_state + min_state_delay > _states[_cur_state].delay) { @@ -440,16 +443,16 @@ ActorMultiVertex::UpdateAnimationState(bool force_update) } } if (state_changed) { - size_t first = dest.FirstToDraw; - size_t last = + const size_t first = dest.FirstToDraw; + const auto last = first + dest.GetSafeNumToDraw(dest._DrawMode, dest.NumToDraw); #define STATE_ID \ const size_t state_id = \ (_cur_state + qs[quad_id % qs.size()]) % _states.size(); switch (AMV_DestTweenState()._DrawMode) { case DrawMode_Quads: - for (size_t i = first; i < last; ++i) { - const size_t quad_id = (i - first) / 4; + for (auto i = first; i < last; ++i) { + const auto quad_id = (i - first) / 4; STATE_ID; switch ((i - first) % 4) { case 0: @@ -472,8 +475,8 @@ ActorMultiVertex::UpdateAnimationState(bool force_update) } break; case DrawMode_QuadStrip: - for (size_t i = first; i < last; ++i) { - const size_t quad_id = (i - first) / 2; + for (auto i = first; i < last; ++i) { + const auto quad_id = (i - first) / 2; STATE_ID; switch ((i - first) % 2) { case 0: @@ -489,16 +492,16 @@ ActorMultiVertex::UpdateAnimationState(bool force_update) break; case DrawMode_Strip: case DrawMode_Fan: - for (size_t i = first; i < last; ++i) { - const size_t quad_id = (i - first); + for (auto i = first; i < last; ++i) { + const auto quad_id = (i - first); STATE_ID; verts[i].t.x = _states[state_id].rect.left; verts[i].t.y = _states[state_id].rect.top; } break; case DrawMode_Triangles: - for (size_t i = first; i < last; ++i) { - const size_t quad_id = (i - first) / 3; + for (auto i = first; i < last; ++i) { + const auto quad_id = (i - first) / 3; STATE_ID; switch ((i - first) % 3) { case 0: @@ -517,8 +520,8 @@ ActorMultiVertex::UpdateAnimationState(bool force_update) } break; case DrawMode_SymmetricQuadStrip: - for (size_t i = first; i < last; ++i) { - const size_t quad_id = (i - first) / 3; + for (auto i = first; i < last; ++i) { + const auto quad_id = (i - first) / 3; STATE_ID; switch ((i - first) % 3) { case 0: @@ -543,7 +546,7 @@ ActorMultiVertex::UpdateAnimationState(bool force_update) void ActorMultiVertex::EnableAnimation(bool bEnable) { - bool bWasEnabled = m_bIsAnimating; + const auto bWasEnabled = m_bIsAnimating; Actor::EnableAnimation(bEnable); if (bEnable && !bWasEnabled) { @@ -555,7 +558,7 @@ void ActorMultiVertex::Update(float fDelta) { Actor::Update(fDelta); // do tweening - const bool skip_this_movie_update = _skip_next_update; + const auto skip_this_movie_update = _skip_next_update; _skip_next_update = false; if (!m_bIsAnimating) { return; @@ -563,7 +566,7 @@ ActorMultiVertex::Update(float fDelta) if (_Texture == nullptr) { return; } - float time_passed = GetEffectDeltaTime(); + const auto time_passed = GetEffectDeltaTime(); _secs_into_state += time_passed; if (_secs_into_state < 0) { wrap(_secs_into_state, GetAnimationLengthSeconds()); @@ -599,7 +602,7 @@ ActorMultiVertex::BeginTweening(float time, ITween* pTween) { Actor::BeginTweening(time, pTween); - if (AMV_Tweens.size() >= 1) // if there was already a TS on the stack + if (!AMV_Tweens.empty()) // if there was already a TS on the stack { AMV_Tweens.push_back(AMV_Tweens.back()); } else { @@ -626,7 +629,7 @@ ActorMultiVertex::FinishTweening() void ActorMultiVertex::AMV_TweenState::SetDrawState(DrawMode dm, int first, int num) { - if (first >= static_cast(vertices.size()) && vertices.size() > 0) { + if (first >= static_cast(vertices.size()) && !vertices.empty()) { LuaHelpers::ReportScriptErrorFmt("ActorMultiVertex:SetDrawState: " "FirstToDraw > vertices.size(), %d > " "%u", @@ -634,7 +637,7 @@ ActorMultiVertex::AMV_TweenState::SetDrawState(DrawMode dm, int first, int num) (unsigned int)vertices.size()); return; } - int safe_num = GetSafeNumToDraw(dm, num); + const auto safe_num = GetSafeNumToDraw(dm, num); if (num != safe_num && num != -1) { LuaHelpers::ReportScriptErrorFmt("ActorMultiVertex:SetDrawState: " "NumToDraw %d is not valid for %u " @@ -669,7 +672,7 @@ ActorMultiVertex::AMV_TweenState::MakeWeightedAverage( int ActorMultiVertex::AMV_TweenState::GetSafeNumToDraw(DrawMode dm, int num) const { - int max = vertices.size() - FirstToDraw; + const int max = vertices.size() - FirstToDraw; // NumToDraw == -1 draws all vertices if (num == -1 || num > max) { num = max; @@ -712,12 +715,12 @@ class LunaActorMultiVertex : public Luna "Table of tables of vertex data expected."); return; } - size_t NumDataParts = lua_objlen(L, DataStackIndex); + const auto NumDataParts = lua_objlen(L, DataStackIndex); for (size_t i = 0; i < NumDataParts; ++i) { lua_pushnumber(L, i + 1); lua_gettable(L, DataStackIndex); - int DataPieceIndex = lua_gettop(L); - size_t DataPieceElements = lua_objlen(L, DataPieceIndex); + const auto DataPieceIndex = lua_gettop(L); + const auto DataPieceElements = lua_objlen(L, DataPieceIndex); if (lua_type(L, DataPieceIndex) != LUA_TTABLE) { LuaHelpers::ReportScriptErrorFmt( "ActorMultiVertex::SetVertex: non-table parameter %u " @@ -725,22 +728,22 @@ class LunaActorMultiVertex : public Luna (unsigned int)i); return; } - int pushes = 1; + auto pushes = 1; if (DataPieceElements == 2) { pushes += 2; lua_rawgeti(L, DataPieceIndex, 1); - float x = FArg(-1); + const auto x = FArg(-1); lua_rawgeti(L, DataPieceIndex, 2); - float y = FArg(-1); + const auto y = FArg(-1); p->SetVertexCoords(VertexIndex, x, y); } else if (DataPieceElements == 3) { pushes += 3; lua_rawgeti(L, DataPieceIndex, 1); - float x = FArg(-1); + const auto x = FArg(-1); lua_rawgeti(L, DataPieceIndex, 2); - float y = FArg(-1); + const auto y = FArg(-1); lua_rawgeti(L, DataPieceIndex, 3); - float z = FArg(-1); + const auto z = FArg(-1); p->SetVertexPos(VertexIndex, x, y, z); } else if (DataPieceElements == 4) { // RageColor pops the things it pushes onto the stack, so we @@ -760,13 +763,12 @@ class LunaActorMultiVertex : public Luna // Avoid a stack underflow by only popping the amount we pushed. lua_pop(L, pushes); } - return; } static int SetVertex(T* p, lua_State* L) { // Indices from Lua are one-indexed. -1 to adjust. - int Index = IArg(1) - 1; + const auto Index = IArg(1) - 1; if (Index < 0) { LuaHelpers::ReportScriptErrorFmt("ActorMultiVertex::SetVertex: " "index %d provided, cannot set " @@ -791,8 +793,8 @@ class LunaActorMultiVertex : public Luna static int SetVertices(T* p, lua_State* L) { - int First = 0; - int StackIndex = lua_gettop(L); + auto First = 0; + const auto StackIndex = lua_gettop(L); // Allow the user to just pass a table without specifying a starting // point. if (lua_type(L, 1) == LUA_TNUMBER) { @@ -806,11 +808,11 @@ class LunaActorMultiVertex : public Luna COMMON_RETURN_SELF; } } - int Last = First + lua_objlen(L, StackIndex); + const int Last = First + lua_objlen(L, StackIndex); if (Last > static_cast(p->GetNumVertices())) { p->AddVertices(Last - p->GetNumVertices()); } - for (int n = First; n < Last; ++n) { + for (auto n = First; n < Last; ++n) { lua_pushnumber(L, n - First + 1); lua_gettable(L, StackIndex); SetVertexFromStack(p, L, n, lua_gettop(L)); @@ -821,21 +823,21 @@ class LunaActorMultiVertex : public Luna static int SetEffectMode(T* p, lua_State* L) { - EffectMode em = Enum::Check(L, 1); + const auto em = Enum::Check(L, 1); p->SetEffectMode(em); COMMON_RETURN_SELF; } static int SetTextureMode(T* p, lua_State* L) { - TextureMode tm = Enum::Check(L, 1); + const auto tm = Enum::Check(L, 1); p->SetTextureMode(tm); COMMON_RETURN_SELF; } static int SetLineWidth(T* p, lua_State* L) { - float Width = FArg(1); + const auto Width = FArg(1); if (Width < 0) { LuaHelpers::ReportScriptErrorFmt( "ActorMultiVertex::SetLineWidth: cannot set negative width."); @@ -847,10 +849,10 @@ class LunaActorMultiVertex : public Luna static int SetDrawState(T* p, lua_State* L) { - DrawMode dm = p->GetDestDrawMode(); - int first = p->GetDestFirstToDraw(); - int num = p->GetDestNumToDraw(); - int ArgsIndex = 1; + auto dm = p->GetDestDrawMode(); + auto first = p->GetDestFirstToDraw(); + auto num = p->GetDestNumToDraw(); + const auto ArgsIndex = 1; if (!lua_istable(L, ArgsIndex)) { LuaHelpers::ReportScriptErrorFmt("ActorMultiVertex:SetDrawState: " "Table expected, something else " @@ -924,7 +926,7 @@ class LunaActorMultiVertex : public Luna p->UnloadTexture(); p->LoadFromTexture(TEXTUREMAN->GetDefaultTextureID()); } else { - RageTextureID ID(SArg(1)); + const RageTextureID ID(SArg(1)); TEXTUREMAN->DisableOddDimensionWarning(); p->LoadFromTexture(ID); TEXTUREMAN->EnableOddDimensionWarning(); @@ -934,7 +936,7 @@ class LunaActorMultiVertex : public Luna static int GetSpline(T* p, lua_State* L) { - auto i = static_cast(IArg(1) - 1); + const auto i = static_cast(IArg(1) - 1); if (i >= ActorMultiVertex::num_vert_splines) { luaL_error(L, "Spline index must be greater than 0 and less than or " @@ -992,8 +994,8 @@ class LunaActorMultiVertex : public Luna SET_SIDE(4, rect.bottom); lua_pop(L, 1); SET_SIDE(2, delay); - const float width_ratio = tex->GetImageToTexCoordsRatioX(); - const float height_ratio = tex->GetImageToTexCoordsRatioY(); + const auto width_ratio = tex->GetImageToTexCoordsRatioX(); + const auto height_ratio = tex->GetImageToTexCoordsRatioY(); state.rect.left = state.rect.left * width_ratio; state.rect.top = state.rect.top * height_ratio; // Pixel centers are at .5, so add an extra pixel to the size to adjust. @@ -1011,7 +1013,7 @@ class LunaActorMultiVertex : public Luna } static size_t ValidStateIndex(T* p, lua_State* L, int pos) { - int index = IArg(pos) - 1; + const auto index = IArg(pos) - 1; if (index < 0 || index >= p->GetNumStates()) { luaL_error(L, "Invalid state index %d.", index + 1); } @@ -1034,16 +1036,15 @@ class LunaActorMultiVertex : public Luna } static int GetStateData(T* p, lua_State* L) { - RageTexture* tex = p->GetTexture(); + auto* const tex = p->GetTexture(); if (tex == nullptr) { luaL_error(L, "The texture must be set before adding states."); } - const float width_pix = tex->GetImageToTexCoordsRatioX(); - const float height_pix = tex->GetImageToTexCoordsRatioY(); - const float width_ratio = 1.0f / tex->GetImageToTexCoordsRatioX(); - const float height_ratio = 1.0f / tex->GetImageToTexCoordsRatioY(); - const ActorMultiVertex::State& state = - p->GetStateData(ValidStateIndex(p, L, 1)); + const auto width_pix = tex->GetImageToTexCoordsRatioX(); + const auto height_pix = tex->GetImageToTexCoordsRatioY(); + const auto width_ratio = 1.0f / tex->GetImageToTexCoordsRatioX(); + const auto height_ratio = 1.0f / tex->GetImageToTexCoordsRatioY(); + const auto& state = p->GetStateData(ValidStateIndex(p, L, 1)); lua_createtable(L, 2, 0); lua_createtable(L, 4, 0); lua_pushnumber(L, state.rect.left * width_ratio); @@ -1061,8 +1062,7 @@ class LunaActorMultiVertex : public Luna } static int SetStateData(T* p, lua_State* L) { - ActorMultiVertex::State& state = - p->GetStateData(ValidStateIndex(p, L, 1)); + auto& state = p->GetStateData(ValidStateIndex(p, L, 1)); FillStateFromLua(L, state, p->GetTexture(), 2); COMMON_RETURN_SELF; } @@ -1071,12 +1071,12 @@ class LunaActorMultiVertex : public Luna if (!lua_istable(L, 1)) { luaL_error(L, "The states must be inside a table."); } - RageTexture* tex = p->GetTexture(); + auto* const tex = p->GetTexture(); if (tex == nullptr) { luaL_error(L, "The texture must be set before adding states."); } vector new_states; - size_t num_states = lua_objlen(L, 1); + const auto num_states = lua_objlen(L, 1); new_states.resize(num_states); for (size_t i = 0; i < num_states; ++i) { lua_rawgeti(L, 1, i + 1); @@ -1104,7 +1104,7 @@ class LunaActorMultiVertex : public Luna } static size_t QuadStateIndex(T* p, lua_State* L, int pos) { - size_t index = IArg(pos) - 1; + const size_t index = IArg(pos) - 1; if (index >= p->GetNumQuadStates()) { luaL_error(L, "Invalid state index %d.", index + 1); } @@ -1144,14 +1144,14 @@ class LunaActorMultiVertex : public Luna static int SetTexture(T* p, lua_State* L) { - RageTexture* Texture = Luna::check(L, 1); + auto* Texture = Luna::check(L, 1); Texture = TEXTUREMAN->CopyTexture(Texture); p->SetTexture(Texture); COMMON_RETURN_SELF; } static int GetTexture(T* p, lua_State* L) { - RageTexture* texture = p->GetTexture(); + auto* texture = p->GetTexture(); if (texture != nullptr) { texture->PushSelf(L); } else { diff --git a/src/Etterna/Actor/Base/ActorMultiVertex.h b/src/Etterna/Actor/Base/ActorMultiVertex.h index 6574e71736..1c4ba46f88 100644 --- a/src/Etterna/Actor/Base/ActorMultiVertex.h +++ b/src/Etterna/Actor/Base/ActorMultiVertex.h @@ -39,7 +39,7 @@ class ActorMultiVertex : public Actor ~ActorMultiVertex() override; void LoadFromNode(const XNode* Node) override; - ActorMultiVertex* Copy() const override; + [[nodiscard]] ActorMultiVertex* Copy() const override; struct AMV_TweenState { @@ -55,7 +55,7 @@ class ActorMultiVertex : public Actor } void SetDrawState(DrawMode dm, int first, int num); - int GetSafeNumToDraw(DrawMode dm, int num) const; + [[nodiscard]] int GetSafeNumToDraw(DrawMode dm, int num) const; vector vertices; vector quad_states; @@ -76,14 +76,15 @@ class ActorMultiVertex : public Actor return AMV_Tweens.back(); } - const AMV_TweenState& AMV_DestTweenState() const + + [[nodiscard]] const AMV_TweenState& AMV_DestTweenState() const { return const_cast(this)->AMV_DestTweenState(); } void EnableAnimation(bool bEnable) override; void Update(float fDelta) override; - bool EarlyAbortDraw() const override; + [[nodiscard]] bool EarlyAbortDraw() const override; void DrawPrimitives() override; virtual void DrawInternal(const AMV_TweenState* TS); @@ -96,7 +97,7 @@ class ActorMultiVertex : public Actor void FinishTweening() override; void SetTexture(RageTexture* Texture); - RageTexture* GetTexture() { return _Texture; }; + [[nodiscard]] RageTexture* GetTexture() const { return _Texture; }; void LoadFromTexture(const RageTextureID& ID); void UnloadTexture(); @@ -114,12 +115,27 @@ class ActorMultiVertex : public Actor AMV_DestTweenState().SetDrawState(dm, first, num); } - DrawMode GetDestDrawMode() const { return AMV_DestTweenState()._DrawMode; } - int GetDestFirstToDraw() const { return AMV_DestTweenState().FirstToDraw; } - int GetDestNumToDraw() const { return AMV_DestTweenState().NumToDraw; } - DrawMode GetCurrDrawMode() const { return AMV_current._DrawMode; } - int GetCurrFirstToDraw() const { return AMV_current.FirstToDraw; } - int GetCurrNumToDraw() const { return AMV_current.NumToDraw; } + [[nodiscard]] DrawMode GetDestDrawMode() const + { + return AMV_DestTweenState()._DrawMode; + } + [[nodiscard]] int GetDestFirstToDraw() const + { + return AMV_DestTweenState().FirstToDraw; + } + [[nodiscard]] int GetDestNumToDraw() const + { + return AMV_DestTweenState().NumToDraw; + } + [[nodiscard]] DrawMode GetCurrDrawMode() const + { + return AMV_current._DrawMode; + } + [[nodiscard]] int GetCurrFirstToDraw() const + { + return AMV_current.FirstToDraw; + } + [[nodiscard]] int GetCurrNumToDraw() const { return AMV_current.NumToDraw; } size_t GetNumVertices() { return AMV_DestTweenState().vertices.size(); } void SetVertexPos(int index, float x, float y, float z); @@ -136,14 +152,16 @@ class ActorMultiVertex : public Actor RectF rect; float delay; }; - int GetNumStates() const override { return _states.size(); } + + [[nodiscard]] int GetNumStates() const override { return _states.size(); } void AddState(const State& new_state) { _states.push_back(new_state); } void RemoveState(size_t i) { ASSERT(i < _states.size()); _states.erase(_states.begin() + i); } - size_t GetState() { return _cur_state; } + + [[nodiscard]] size_t GetState() const { return _cur_state; } State& GetStateData(size_t i) { ASSERT(i < _states.size()); @@ -161,10 +179,11 @@ class ActorMultiVertex : public Actor } void SetState(size_t i); void SetAllStateDelays(float delay); - float GetAnimationLengthSeconds() const override; + [[nodiscard]] float GetAnimationLengthSeconds() const override; void SetSecondsIntoAnimation(float seconds) override; void UpdateAnimationState(bool force_update = false); - size_t GetNumQuadStates() const + + [[nodiscard]] size_t GetNumQuadStates() const { return AMV_DestTweenState().quad_states.size(); } diff --git a/src/Etterna/Actor/Base/ActorScroller.cpp b/src/Etterna/Actor/Base/ActorScroller.cpp index 58a88e7b7e..a82b34e761 100644 --- a/src/Etterna/Actor/Base/ActorScroller.cpp +++ b/src/Etterna/Actor/Base/ActorScroller.cpp @@ -1,7 +1,6 @@ #include "Etterna/Globals/global.h" #include "ActorScroller.h" #include "ActorUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "RageUtil/Utils/RageUtil.h" #include "Etterna/FileTypes/XmlFile.h" @@ -47,7 +46,7 @@ ActorScroller::Load2() { m_iNumItems = m_SubActors.size(); - Lua* L = LUA->Get(); + auto* L = LUA->Get(); for (unsigned i = 0; i < m_SubActors.size(); ++i) { lua_pushnumber(L, i); this->m_SubActors[i]->m_pLuaInstance->Set(L, "ItemIndex"); @@ -128,14 +127,14 @@ ActorScroller::ScrollWithPadding(float fItemPaddingStart, float fItemPaddingEnd) float ActorScroller::GetSecondsForCompleteScrollThrough() const { - float fTotalItems = m_fNumItemsToDraw + m_iNumItems; + const auto fTotalItems = m_fNumItemsToDraw + m_iNumItems; return fTotalItems * (m_fSecondsPerItem + m_fSecondsPauseBetweenItems); } float ActorScroller::GetSecondsToDestination() const { - float fTotalItemsToMove = fabsf(m_fCurrentItem - m_fDestinationItem); + const auto fTotalItemsToMove = fabsf(m_fCurrentItem - m_fDestinationItem); return fTotalItemsToMove * m_fSecondsPerItem; } @@ -154,7 +153,7 @@ ActorScroller::LoadFromNode(const XNode* pNode) if (pNode->GetAttrValue("SecondsPerItem", fSecondsPerItem)) ActorScroller::SetSecondsPerItem(fSecondsPerItem); - Lua* L = LUA->Get(); + auto* L = LUA->Get(); pNode->PushAttrValue(L, "TransformFunction"); { LuaReference ref; @@ -164,11 +163,11 @@ ActorScroller::LoadFromNode(const XNode* pNode) } LUA->Release(L); - int iSubdivisions = 1; + auto iSubdivisions = 1; if (pNode->GetAttrValue("Subdivisions", iSubdivisions)) ActorScroller::SetNumSubdivisions(iSubdivisions); - bool bUseMask = false; + auto bUseMask = false; pNode->GetAttrValue("UseMask", bUseMask); if (bUseMask) { @@ -188,7 +187,7 @@ ActorScroller::UpdateInternal(float fDeltaTime) ActorFrame::UpdateInternal(fDeltaTime); // If we have no children, the code below will busy loop. - if (!m_SubActors.size()) + if (m_SubActors.empty()) return; // handle pause @@ -197,18 +196,18 @@ ActorScroller::UpdateInternal(float fDeltaTime) m_fPauseCountdownSeconds = 0; } else { m_fPauseCountdownSeconds -= fDeltaTime; - fDeltaTime = 0; return; } if (m_fCurrentItem == m_fDestinationItem) return; // done scrolling - float fOldItemAtTop = m_fCurrentItem; + const auto fOldItemAtTop = m_fCurrentItem; if (m_fSecondsPerItem > 0) { - float fApproachSpeed = fDeltaTime / m_fSecondsPerItem; + auto fApproachSpeed = fDeltaTime / m_fSecondsPerItem; if (m_bFastCatchup) { - float fDistanceToMove = fabsf(m_fCurrentItem - m_fDestinationItem); + const auto fDistanceToMove = + fabsf(m_fCurrentItem - m_fDestinationItem); if (fDistanceToMove > 1) fApproachSpeed *= fDistanceToMove * fDistanceToMove; } @@ -221,7 +220,7 @@ ActorScroller::UpdateInternal(float fDeltaTime) m_fPauseCountdownSeconds = m_fSecondsPauseBetweenItems; if (m_bWrap) { - float Delta = m_fDestinationItem - m_fCurrentItem; + const auto Delta = m_fDestinationItem - m_fCurrentItem; m_fCurrentItem = fmodf(m_fCurrentItem, static_cast(m_iNumItems)); m_fDestinationItem = m_fCurrentItem + Delta; } @@ -258,13 +257,13 @@ ActorScroller::PositionItemsAndDrawPrimitives(bool bDrawPrimitives) if (m_SubActors.empty()) return; - float fNumItemsToDraw = m_fNumItemsToDraw; + auto fNumItemsToDraw = m_fNumItemsToDraw; if (m_quadMask.GetVisible()) { // write to z buffer so that top and bottom are clipped // Draw an extra item; this is the one that will be masked. fNumItemsToDraw++; - float fPositionFullyOffScreenTop = -(fNumItemsToDraw) / 2.f; - float fPositionFullyOffScreenBottom = (fNumItemsToDraw) / 2.f; + const auto fPositionFullyOffScreenTop = -(fNumItemsToDraw) / 2.f; + const auto fPositionFullyOffScreenBottom = (fNumItemsToDraw) / 2.f; m_exprTransformFunction.TransformItemCached( m_quadMask, fPositionFullyOffScreenTop, -1, m_iNumItems); @@ -277,10 +276,10 @@ ActorScroller::PositionItemsAndDrawPrimitives(bool bDrawPrimitives) m_quadMask.Draw(); } - float fFirstItemToDraw = m_fCurrentItem - fNumItemsToDraw / 2.f; - float fLastItemToDraw = m_fCurrentItem + fNumItemsToDraw / 2.f; - int iFirstItemToDraw = static_cast(ceilf(fFirstItemToDraw)); - int iLastItemToDraw = static_cast(ceilf(fLastItemToDraw)); + const auto fFirstItemToDraw = m_fCurrentItem - fNumItemsToDraw / 2.f; + const auto fLastItemToDraw = m_fCurrentItem + fNumItemsToDraw / 2.f; + auto iFirstItemToDraw = static_cast(ceilf(fFirstItemToDraw)); + auto iLastItemToDraw = static_cast(ceilf(fLastItemToDraw)); if (!m_bLoop && !m_bWrap) { iFirstItemToDraw = clamp(iFirstItemToDraw, 0, m_iNumItems); iLastItemToDraw = clamp(iLastItemToDraw, 0, m_iNumItems); @@ -290,17 +289,17 @@ ActorScroller::PositionItemsAndDrawPrimitives(bool bDrawPrimitives) { // Shift m_SubActors so iFirstItemToDraw is at the beginning. - int iNewFirstIndex = iFirstItemToDraw; - int iDist = iNewFirstIndex - m_iFirstSubActorIndex; + const auto iNewFirstIndex = iFirstItemToDraw; + const auto iDist = iNewFirstIndex - m_iFirstSubActorIndex; m_iFirstSubActorIndex = iNewFirstIndex; ShiftSubActors(iDist); } - int iNumToDraw = iLastItemToDraw - iFirstItemToDraw; - for (int i = 0; i < iNumToDraw; ++i) { - int iItem = i + iFirstItemToDraw; - float fPosition = iItem - m_fCurrentItem; - int iIndex = i; // index into m_SubActors + const auto iNumToDraw = iLastItemToDraw - iFirstItemToDraw; + for (auto i = 0; i < iNumToDraw; ++i) { + auto iItem = i + iFirstItemToDraw; + auto fPosition = iItem - m_fCurrentItem; + auto iIndex = i; // index into m_SubActors if (m_bLoop || m_bWrap) wrap(iIndex, m_SubActors.size()); else if (iIndex < 0 || iIndex >= static_cast(m_SubActors.size())) @@ -327,8 +326,8 @@ ActorScroller::PositionItemsAndDrawPrimitives(bool bDrawPrimitives) if (m_bDrawByZPosition) { ActorUtil::SortByZPosition(subs); - FOREACH(Actor*, subs, a) - (*a)->Draw(); + for (auto& a : subs) + a->Draw(); } } diff --git a/src/Etterna/Actor/Base/ActorScroller.h b/src/Etterna/Actor/Base/ActorScroller.h index 174f81c67a..f538c56c59 100644 --- a/src/Etterna/Actor/Base/ActorScroller.h +++ b/src/Etterna/Actor/Base/ActorScroller.h @@ -58,7 +58,10 @@ class ActorScroller : public ActorFrame { m_fSecondsPauseBetweenItems = fSeconds; } - float GetSecondsPauseBetweenItems() { return m_fSecondsPauseBetweenItems; } + float GetSecondsPauseBetweenItems() const + { + return m_fSecondsPauseBetweenItems; + } void SetNumSubdivisions(int iNumSubdivisions) { m_exprTransformFunction.SetNumSubdivisions(iNumSubdivisions); diff --git a/src/Etterna/Actor/Base/ActorSound.cpp b/src/Etterna/Actor/Base/ActorSound.cpp index 7af46b2ddb..310ba6cbc2 100644 --- a/src/Etterna/Actor/Base/ActorSound.cpp +++ b/src/Etterna/Actor/Base/ActorSound.cpp @@ -17,7 +17,7 @@ ActorSound::Update(float dt) { Actor::Update(dt); if (m_Sound.pendingPlayBackCall) { - auto L = LUA->Get(); + auto* L = LUA->Get(); m_Sound.ExecutePlayBackCallback(L); LUA->Release(L); } @@ -49,7 +49,7 @@ ActorSound::LoadFromNode(const XNode* pNode) pNode->GetAttrValue("SupportRateChanging", params.m_bSupportRateChanging); pNode->GetAttrValue("IsAction", m_is_action); - bool bPrecache = true; + auto bPrecache = true; pNode->GetAttrValue("Precache", bPrecache); Actor::LoadFromNode(pNode); diff --git a/src/Etterna/Actor/Base/ActorUtil.cpp b/src/Etterna/Actor/Base/ActorUtil.cpp index 79bee14c69..b1a264eec6 100644 --- a/src/Etterna/Actor/Base/ActorUtil.cpp +++ b/src/Etterna/Actor/Base/ActorUtil.cpp @@ -28,8 +28,7 @@ ActorUtil::Register(const std::string& sClassName, CreateActorFn pfn) if (g_pmapRegistrees == nullptr) g_pmapRegistrees = new map; - map::iterator iter = - g_pmapRegistrees->find(sClassName); + const auto iter = g_pmapRegistrees->find(sClassName); ASSERT_M( iter == g_pmapRegistrees->end(), ssprintf("Actor class '%s' already registered.", sClassName.c_str())); @@ -49,7 +48,7 @@ ActorUtil::ResolvePath(std::string& sPath, // If we know this is an exact match, don't bother with the GetDirListing, // so "foo" doesn't partial match "foobar" if "foo" exists. - RageFileManager::FileType ft = FILEMAN->GetFileType(sPath); + const auto ft = FILEMAN->GetFileType(sPath); if (ft != RageFileManager::TYPE_FILE && ft != RageFileManager::TYPE_DIR) { vector asPaths; GetDirListing(sPath + "*", asPaths, false, true); // return path too @@ -58,7 +57,7 @@ ActorUtil::ResolvePath(std::string& sPath, if (optional) { return false; } - std::string sError = + const auto sError = ssprintf("%s: references a file \"%s\" which doesn't exist", sName.c_str(), sPath.c_str()); @@ -79,7 +78,7 @@ ActorUtil::ResolvePath(std::string& sPath, THEME->FilterFileLanguages(asPaths); if (asPaths.size() > 1) { - std::string sError = ssprintf( + auto sError = ssprintf( "%s: references a file \"%s\" which has multiple matches", sName.c_str(), sPath.c_str()); @@ -103,7 +102,7 @@ ActorUtil::ResolvePath(std::string& sPath, } if (ft == RageFileManager::TYPE_DIR) { - std::string sLuaPath = sPath + "/default.lua"; + const auto sLuaPath = sPath + "/default.lua"; if (DoesFileExist(sLuaPath)) { sPath = sLuaPath; return true; @@ -162,7 +161,7 @@ ActorUtil::LoadFromNode(const XNode* _pNode, Actor* pParentActor) { ASSERT(_pNode != nullptr); - XNode node = *_pNode; + auto node = *_pNode; // Remove this in favor of using conditionals in Lua. -Chris // There are a number of themes out there that depend on this (including @@ -174,16 +173,15 @@ ActorUtil::LoadFromNode(const XNode* _pNode, Actor* pParentActor) } std::string sClass; - bool bHasClass = node.GetAttrValue("Class", sClass); + auto bHasClass = node.GetAttrValue("Class", sClass); if (!bHasClass) bHasClass = node.GetAttrValue("Type", sClass); - bool bLegacy = (node.GetAttr("_LegacyXml") != nullptr); + const auto bLegacy = (node.GetAttr("_LegacyXml") != nullptr); if (!bHasClass && bLegacy) sClass = GetLegacyActorClass(&node); - map::iterator iter = - g_pmapRegistrees->find(sClass); + const auto iter = g_pmapRegistrees->find(sClass); if (iter == g_pmapRegistrees->end()) { std::string sFile; if (bLegacy && node.GetAttrValue("File", sFile) && !sFile.empty()) { @@ -194,7 +192,7 @@ ActorUtil::LoadFromNode(const XNode* _pNode, Actor* pParentActor) else sPath = Dirname(GetSourcePath(&node)) + sFile; if (ResolvePath(sPath, GetWhere(&node))) { - Actor* pNewActor = MakeActor(sPath, pParentActor); + auto pNewActor = MakeActor(sPath, pParentActor); if (pNewActor == nullptr) return nullptr; if (pParentActor != nullptr) @@ -205,16 +203,16 @@ ActorUtil::LoadFromNode(const XNode* _pNode, Actor* pParentActor) } // sClass is invalid - std::string sError = ssprintf("%s: invalid Class \"%s\"", - ActorUtil::GetWhere(&node).c_str(), - sClass.c_str()); + const auto sError = ssprintf("%s: invalid Class \"%s\"", + ActorUtil::GetWhere(&node).c_str(), + sClass.c_str()); LuaHelpers::ReportScriptError(sError); return new Actor; // Return a dummy object so that we don't crash in // AutoActor later. } - const CreateActorFn& pfn = iter->second; - Actor* pRet = pfn(); + const auto& pfn = iter->second; + auto pRet = pfn(); if (pParentActor != nullptr) pRet->SetParent(pParentActor); @@ -231,7 +229,7 @@ LoadXNodeFromLuaShowErrors(const std::string& sFile) if (!GetFileContents(sFile, sScript)) return nullptr; - Lua* L = LUA->Get(); + auto L = LUA->Get(); std::string sError; if (!LuaHelpers::LoadScript(L, sScript, "@" + sFile, sError)) { @@ -286,9 +284,9 @@ ActorUtil::LoadTableFromStackShowErrors(Lua* L) Actor* ActorUtil::MakeActor(const std::string& sPath_, Actor* pParentActor) { - std::string sPath(sPath_); + auto sPath(sPath_); - FileType ft = GetFileType(sPath); + auto ft = GetFileType(sPath); switch (ft) { case FT_Lua: { unique_ptr pNode(LoadXNodeFromLuaShowErrors(sPath)); @@ -297,7 +295,7 @@ ActorUtil::MakeActor(const std::string& sPath_, Actor* pParentActor) return new Actor; } - Actor* pRet = ActorUtil::LoadFromNode(pNode.get(), pParentActor); + auto pRet = ActorUtil::LoadFromNode(pNode.get(), pParentActor); return pRet; } case FT_Xml: { @@ -307,7 +305,7 @@ ActorUtil::MakeActor(const std::string& sPath_, Actor* pParentActor) if (sPath.back() != '/') sPath += '/'; - std::string sXml = sPath + "default.xml"; + auto sXml = sPath + "default.xml"; if (DoesFileExist(sXml)) return MakeActor(sXml, pParentActor); @@ -363,7 +361,7 @@ ActorUtil::GetSourcePath(const XNode* pNode) std::string ActorUtil::GetWhere(const XNode* pNode) { - std::string sPath = GetSourcePath(pNode); + auto sPath = GetSourcePath(pNode); int iLine; if (pNode->GetAttrValue("_Line", iLine)) @@ -380,7 +378,7 @@ ActorUtil::GetAttrPath(const XNode* pNode, if (!pNode->GetAttrValue(sName, sOut)) return false; - bool bIsRelativePath = sOut.front() != '/'; + const auto bIsRelativePath = sOut.front() != '/'; if (bIsRelativePath) { std::string sDir; if (!pNode->GetAttrValue("_Dir", sDir)) { @@ -400,7 +398,7 @@ apActorCommands ActorUtil::ParseActorCommands(const std::string& sCommands, const std::string& sName) { - Lua* L = LUA->Get(); + auto L = LUA->Get(); LuaHelpers::ParseCommandList(L, sCommands, sName, false); auto* pRet = new LuaReference; pRet->SetFromStack(L); @@ -419,8 +417,8 @@ ActorUtil::SetXY(Actor& actor, const std::string& sMetricsGroup) * these are both 0, leave the actor where it is. If InitCommand doesn't, * then 0,0 is the default, anyway. */ - float fX = THEME->GetMetricF(sMetricsGroup, actor.GetName() + "X"); - float fY = THEME->GetMetricF(sMetricsGroup, actor.GetName() + "Y"); + const auto fX = THEME->GetMetricF(sMetricsGroup, actor.GetName() + "X"); + const auto fY = THEME->GetMetricF(sMetricsGroup, actor.GetName() + "Y"); if (fX != 0 || fY != 0) actor.SetXY(fX, fY); } @@ -557,7 +555,7 @@ ActorUtil::GetTypeExtensionList(FileType ft) void ActorUtil::AddTypeExtensionsToList(FileType ft, vector& add_to) { - fttel_cont_t::iterator ext_list = FileTypeToExtensionList.find(ft); + auto ext_list = FileTypeToExtensionList.find(ft); if (ext_list != FileTypeToExtensionList.end()) { add_to.reserve(add_to.size() + ext_list->second.size()); for (auto& curr : ext_list->second) { @@ -569,9 +567,9 @@ ActorUtil::AddTypeExtensionsToList(FileType ft, vector& add_to) FileType ActorUtil::GetFileType(const std::string& sPath) { - std::string sExt = make_lower(GetExtension(sPath)); + const auto sExt = make_lower(GetExtension(sPath)); - etft_cont_t::iterator conversion_entry = ExtensionToFileType.find(sExt); + const auto conversion_entry = ExtensionToFileType.find(sExt); if (conversion_entry != ExtensionToFileType.end()) { return conversion_entry->second; } @@ -600,15 +598,15 @@ int ResolvePath(lua_State* L) { std::string sPath(SArg(1)); - int iLevel = IArg(2); - bool optional = lua_toboolean(L, 3) != 0; + const auto iLevel = IArg(2); + const auto optional = lua_toboolean(L, 3) != 0; luaL_where(L, iLevel); std::string sWhere = lua_tostring(L, -1); if (sWhere.size() > 2 && sWhere.substr(sWhere.size() - 2, 2) == ": ") sWhere = sWhere.substr(0, sWhere.size() - 2); // remove trailing ": " LUA->YieldLua(); - bool bRet = ActorUtil::ResolvePath(sPath, sWhere, optional); + const auto bRet = ActorUtil::ResolvePath(sPath, sWhere, optional); LUA->UnyieldLua(); if (!bRet) @@ -625,14 +623,14 @@ IsRegisteredClass(lua_State* L) static void name_error(Actor* p, lua_State* L) { - if (p->GetName() == "") { + if (p->GetName().empty()) { luaL_error(L, "LoadAllCommands requires the actor to have a name."); } } static int LoadAllCommands(lua_State* L) { - Actor* p = Luna::check(L, 1); + auto p = Luna::check(L, 1); name_error(p, L); ActorUtil::LoadAllCommands(p, SArg(2)); return 0; @@ -640,7 +638,7 @@ LoadAllCommands(lua_State* L) static int LoadAllCommandsFromName(lua_State* L) { - Actor* p = Luna::check(L, 1); + auto p = Luna::check(L, 1); name_error(p, L); ActorUtil::LoadAllCommandsFromName(*p, SArg(2), SArg(3)); return 0; @@ -648,7 +646,7 @@ LoadAllCommandsFromName(lua_State* L) static int LoadAllCommandsAndSetXY(lua_State* L) { - Actor* p = Luna::check(L, 1); + auto p = Luna::check(L, 1); name_error(p, L); ActorUtil::LoadAllCommandsAndSetXY(p, SArg(2)); return 0; diff --git a/src/Etterna/Actor/Base/ActorUtil.h b/src/Etterna/Actor/Base/ActorUtil.h index f242b95ad4..a930cec087 100644 --- a/src/Etterna/Actor/Base/ActorUtil.h +++ b/src/Etterna/Actor/Base/ActorUtil.h @@ -57,10 +57,10 @@ FileTypeToString(FileType ft); namespace ActorUtil { void InitFileTypeLists(); -vector const& +std::vector const& GetTypeExtensionList(FileType ft); void -AddTypeExtensionsToList(FileType ft, vector& add_to); +AddTypeExtensionsToList(FileType ft, std::vector& add_to); // Every screen should register its class at program initialization. void @@ -222,7 +222,7 @@ ResolvePath(std::string& sPath, bool optional = false); void -SortByZPosition(vector& vActors); +SortByZPosition(std::vector& vActors); FileType GetFileType(const std::string& sPath); diff --git a/src/Etterna/Actor/Base/AutoActor.cpp b/src/Etterna/Actor/Base/AutoActor.cpp index f949bd1ea7..41acaccf48 100644 --- a/src/Etterna/Actor/Base/AutoActor.cpp +++ b/src/Etterna/Actor/Base/AutoActor.cpp @@ -55,7 +55,8 @@ void AutoActor::LoadB(const std::string& sMetricsGroup, const std::string& sElement) { ThemeManager::PathInfo pi; - bool b = THEME->GetPathInfo(pi, EC_BGANIMATIONS, sMetricsGroup, sElement); + const auto b = + THEME->GetPathInfo(pi, EC_BGANIMATIONS, sMetricsGroup, sElement); ASSERT(b); LuaThreadVariable var1("MatchingMetricsGroup", pi.sMatchingMetricsGroup); LuaThreadVariable var2("MatchingElement", pi.sMatchingElement); diff --git a/src/Etterna/Actor/Base/AutoActor.h b/src/Etterna/Actor/Base/AutoActor.h index 2f9fad11e8..2dbcd34ccf 100644 --- a/src/Etterna/Actor/Base/AutoActor.h +++ b/src/Etterna/Actor/Base/AutoActor.h @@ -27,7 +27,7 @@ class AutoActor /** * @brief Determine if this actor is presently loaded. * @return true if it is loaded, or false otherwise. */ - bool IsLoaded() const { return m_pActor != nullptr; } + [[nodiscard]] bool IsLoaded() const { return m_pActor != nullptr; } void Load(Actor* pActor); // transfer pointer void Load(const std::string& sPath); void LoadB(const std::string& sMetricsGroup, diff --git a/src/Etterna/Actor/Base/BitmapText.cpp b/src/Etterna/Actor/Base/BitmapText.cpp index 14d2396ded..58bf83c4da 100644 --- a/src/Etterna/Actor/Base/BitmapText.cpp +++ b/src/Etterna/Actor/Base/BitmapText.cpp @@ -3,7 +3,6 @@ #include "BitmapText.h" #include "Etterna/Models/Fonts/Font.h" #include "Etterna/Singletons/FontManager.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "Etterna/Singletons/PrefsManager.h" #include "RageUtil/Graphics/RageDisplay.h" @@ -313,7 +312,7 @@ BitmapText::BuildChars() reverse(sLine.begin(), sLine.end()); const auto iLineWidth = m_iLineWidths[i]; - auto fX = + const auto fX = SCALE(m_fHorizAlign, 0, 1, -m_size.x / 2, m_size.x / 2 - iLineWidth); int iX = lround(fX); @@ -357,11 +356,11 @@ BitmapText::BuildChars() } if (m_bUsingDistortion) { - int iSeed = lround(RageTimer::GetTimeSinceStart() * 500000.0f); + const int iSeed = lround(RageTimer::GetTimeSinceStart() * 500000.0f); RandomGen rnd(iSeed); for (unsigned int i = 0; i < m_aVertices.size(); i += 4) { - auto w = m_aVertices[i + 2].p.x - m_aVertices[i].p.x; - auto h = m_aVertices[i + 2].p.y - m_aVertices[i].p.y; + const auto w = m_aVertices[i + 2].p.x - m_aVertices[i].p.x; + const auto h = m_aVertices[i + 2].p.y - m_aVertices[i].p.y; for (unsigned int ioff = 0; ioff < 4; ++ioff) { m_aVertices[i + ioff].p.x += ((rnd() % 9) / 8.0f - .5f) * m_fDistortion * w; @@ -430,7 +429,7 @@ BitmapText::DrawChars(bool bUseStrokeTexture) SCALE(fStopFadeRightPercent, 0, 1, 0, iNumGlyphs); for (auto start = iStartGlyph; start < iEndGlyph; ++start) { - auto i = start * 4; + const auto i = start * 4; auto fAlpha = 1.0f; if (FadeSize.left > 0.001f) { @@ -469,7 +468,7 @@ BitmapText::DrawChars(bool bUseStrokeTexture) m_vpFontPageTextures[end] == m_vpFontPageTextures[start]) end++; - auto bHaveATexture = + const auto bHaveATexture = !bUseStrokeTexture || (bUseStrokeTexture && m_vpFontPageTextures[start]->m_pTextureStroke); if (bHaveATexture) { @@ -577,7 +576,7 @@ BitmapText::SetTextInternal() auto iCurLineWidth = 0; for (auto& sWord : asWords) { - auto iWidthWord = + const auto iWidthWord = m_pFont->GetLineWidthInSourcePixels(RStringToWstring(sWord)); if (sCurLine.empty()) { @@ -586,8 +585,8 @@ BitmapText::SetTextInternal() continue; } - auto sToAdd = " " + sWord; - auto iWidthToAdd = + const auto sToAdd = " " + sWord; + const auto iWidthToAdd = m_pFont->GetLineWidthInSourcePixels(L" ") + iWidthWord; if (iCurLineWidth + iWidthToAdd <= m_iWrapWidthPixels) // will fit on current line @@ -665,7 +664,7 @@ BitmapText::set_mult_attrs_with_diffuse(bool m) } bool -BitmapText::get_mult_attrs_with_diffuse() +BitmapText::get_mult_attrs_with_diffuse() const { return m_mult_attrs_with_diffuse; } @@ -705,7 +704,7 @@ BitmapText::StringWillUseAlternate(const std::string& sText, ASSERT(m_pFont != nullptr); // Can't use the alternate if there isn't one. - if (!sAlternateText.size()) + if (sAlternateText.empty()) return false; // False if the alternate isn't needed. @@ -725,7 +724,7 @@ BitmapText::CropLineToWidth(size_t l, int width) if (l < m_wTextLines.size()) { auto used_width = width; auto& line = m_wTextLines[l]; - size_t fit = m_pFont->GetGlyphsThatFit(line, &used_width); + const size_t fit = m_pFont->GetGlyphsThatFit(line, &used_width); if (fit < line.size()) { line.erase(line.begin() + fit, line.end()); } @@ -797,10 +796,10 @@ BitmapText::DrawPrimitives() size_t i = 0; map::const_iterator iter = m_mAttributes.begin(); while (i < m_aVertices.size()) { - auto what = m_pTempState->diffuse[0]; - auto is = m_pTempState->diffuse[2]; - auto wrong = m_pTempState->diffuse[3]; - auto withyoupeople = m_pTempState->diffuse[1]; + const auto what = m_pTempState->diffuse[0]; + const auto is = m_pTempState->diffuse[2]; + const auto wrong = m_pTempState->diffuse[3]; + const auto withyoupeople = m_pTempState->diffuse[1]; // Set the colors up to the next attribute. auto iEnd = iter == m_mAttributes.end() ? m_aVertices.size() @@ -843,7 +842,7 @@ BitmapText::DrawPrimitives() // apply jitter to verts vector vGlyphJitter; if (m_bJitter) { - int iSeed = lround(RageTimer::GetTimeSinceStart() * 8); + const int iSeed = lround(RageTimer::GetTimeSinceStart() * 8); RandomGen rnd(iSeed); for (unsigned i = 0; i < m_aVertices.size(); i += 4) { @@ -866,8 +865,6 @@ BitmapText::DrawPrimitives() ASSERT(vGlyphJitter.size() == m_aVertices.size() / 4); for (unsigned i = 0; i < m_aVertices.size(); i += 4) { const auto& jitter = vGlyphJitter[i / 4]; - ; - m_aVertices[i + 0].p -= jitter; // top left m_aVertices[i + 1].p -= jitter; // bottom left m_aVertices[i + 2].p -= jitter; // bottom right @@ -955,9 +952,8 @@ BitmapText::AddAttribute(size_t iPos, const Attribute& attr) auto iLines = 0; auto iAdjustedPos = iPos; - FOREACH_CONST(wstring, m_wTextLines, line) - { - auto length = line->length(); + for (auto& line : m_wTextLines) { + const auto length = line.length(); if (length >= iAdjustedPos) break; iAdjustedPos -= length; @@ -1019,7 +1015,7 @@ ColorBitmapText::SetText(const std::string& _sText, const std::string& _sAlternateText, int iWrapWidthPixels) { - ASSERT(m_pFont != NULL); + ASSERT(m_pFont != nullptr); auto sNewText = StringWillUseAlternate(_sText, _sAlternateText) ? _sAlternateText @@ -1042,10 +1038,10 @@ ColorBitmapText::SetText(const std::string& _sText, m_wTextLines.clear(); - std::string sCurrentLine = ""; + std::string sCurrentLine; auto iLineWidth = 0; - std::string sCurrentWord = ""; + std::string sCurrentWord; auto iWordWidth = 0; auto iGlyphsSoFar = 0; @@ -1152,7 +1148,7 @@ ColorBitmapText::SetText(const std::string& _sText, void ColorBitmapText::ResetText() { - ASSERT(m_pFont != NULL); + ASSERT(m_pFont != nullptr); auto iWrapWidthPixels = m_iWrapWidthPixels; @@ -1165,10 +1161,10 @@ ColorBitmapText::ResetText() m_wTextLines.clear(); - std::string sCurrentLine = ""; + std::string sCurrentLine; auto iLineWidth = 0; - std::string sCurrentWord = ""; + std::string sCurrentWord; auto iWordWidth = 0; auto iGlyphsSoFar = 0; @@ -1301,7 +1297,7 @@ ColorBitmapText::SetMaxLines(int iNumLines, // If we already have a color set for the first char // do not override it. - if (m_vColors.size() > 0 && m_vColors[0].l > 0) { + if (!m_vColors.empty() && m_vColors[0].l > 0) { ColorChange tmp; tmp.c = LastColor; tmp.l = 0; @@ -1420,7 +1416,7 @@ ColorBitmapText::SetMaxLines(int iNumLines, int iDirection) // If we already have a color set for the first char // do not override it. - if (m_vColors.size() > 0 && m_vColors[0].l > 0) { + if (!m_vColors.empty() && m_vColors[0].l > 0) { ColorChange tmp; tmp.c = LastColor; tmp.l = 0; @@ -1444,7 +1440,7 @@ class LunaBitmapText : public Luna public: static int getGlyphRect(T* p, lua_State* L) { - auto idx = + const auto idx = (IArg(1) - 1) * 4; // lua idx start at 1 and 4 verts per glyph if (idx < 0 || idx >= static_cast(p->m_aVertices.size())) { lua_pushnil(L); @@ -1533,7 +1529,7 @@ class LunaBitmapText : public Luna } static int AddAttribute(T* p, lua_State* L) { - size_t iPos = IArg(1); + const size_t iPos = IArg(1); auto attr = p->GetDefaultAttribute(); attr.FromStack(L, 2); diff --git a/src/Etterna/Actor/Base/BitmapText.h b/src/Etterna/Actor/Base/BitmapText.h index 18dc243779..dfb50227ea 100644 --- a/src/Etterna/Actor/Base/BitmapText.h +++ b/src/Etterna/Actor/Base/BitmapText.h @@ -17,7 +17,7 @@ class BitmapText : public Actor ~BitmapText() override; void LoadFromNode(const XNode* pNode) override; - BitmapText* Copy() const override; + [[nodiscard]] BitmapText* Copy() const override; struct BMT_TweenState { @@ -37,7 +37,10 @@ class BitmapText : public Actor return !operator==(other); } void SetStrokeColor(RageColor const& c) { m_stroke_color = c; } - RageColor const& GetStrokeColor() { return m_stroke_color; } + [[nodiscard]] RageColor const& GetStrokeColor() const + { + return m_stroke_color; + } private: RageColor m_stroke_color; @@ -51,7 +54,8 @@ class BitmapText : public Actor return BMT_Tweens.back(); } - BMT_TweenState const& BMT_DestTweenState() const + + [[nodiscard]] BMT_TweenState const& BMT_DestTweenState() const { return const_cast(this)->BMT_DestTweenState(); } @@ -83,7 +87,7 @@ class BitmapText : public Actor void CropLineToWidth(size_t l, int width); void CropToWidth(int width); - bool EarlyAbortDraw() const override; + [[nodiscard]] bool EarlyAbortDraw() const override; void DrawPrimitives() override; void SetUppercase(bool b); @@ -92,7 +96,7 @@ class BitmapText : public Actor void SetDistortion(float f); void UnSetDistortion(); void set_mult_attrs_with_diffuse(bool m); - bool get_mult_attrs_with_diffuse(); + [[nodiscard]] bool get_mult_attrs_with_diffuse() const; void SetHorizAlign(float f) override; @@ -119,12 +123,17 @@ class BitmapText : public Actor { wTextLines = m_wTextLines; } - const vector& GetLines() const { return m_wTextLines; } - std::string GetText() const { return m_sText; } + [[nodiscard]] const vector& GetLines() const + { + return m_wTextLines; + } + + [[nodiscard]] std::string GetText() const { return m_sText; } // Return true if the string 's' will use an alternate string, if available. - bool StringWillUseAlternate(const std::string& sText, - const std::string& sAlternateText) const; + [[nodiscard]] bool StringWillUseAlternate( + const std::string& sText, + const std::string& sAlternateText) const; struct Attribute { @@ -139,7 +148,7 @@ class BitmapText : public Actor void FromStack(lua_State* L, int iPos); }; - Attribute GetDefaultAttribute() const; + [[nodiscard]] Attribute GetDefaultAttribute() const; void AddAttribute(size_t iPos, const Attribute& attr); void ClearAttributes(); @@ -188,7 +197,7 @@ class BitmapText : public Actor class ColorBitmapText : public BitmapText { public: - ColorBitmapText* Copy() const override; + [[nodiscard]] ColorBitmapText* Copy() const override; void SetText(const std::string& sText, const std::string& sAlternateText = "", int iWrapWidthPixels = -1) override; diff --git a/src/Etterna/Actor/Base/Model.cpp b/src/Etterna/Actor/Base/Model.cpp index f893545f43..ea7bd2de04 100644 --- a/src/Etterna/Actor/Base/Model.cpp +++ b/src/Etterna/Actor/Base/Model.cpp @@ -1,6 +1,5 @@ #include "Etterna/Globals/global.h" #include "ActorUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Lua/LuaBinding.h" #include "Model.h" #include "ModelManager.h" @@ -12,6 +11,7 @@ #include "RageUtil/Graphics/RageTextureManager.h" #include "RageUtil/Utils/RageUtil.h" #include "Etterna/FileTypes/XmlFile.h" + #include REGISTER_ACTOR_CLASS(Model); @@ -24,13 +24,13 @@ Model::Model() m_bTextureWrapping = true; SetUseZBuffer(true); SetCullMode(CULL_BACK); - m_pGeometry = NULL; - m_pCurAnimation = NULL; + m_pGeometry = nullptr; + m_pCurAnimation = nullptr; m_fDefaultAnimationRate = 1; m_fCurAnimationRate = 1; m_bLoop = true; m_bDrawCelShaded = false; - m_pTempGeometry = NULL; + m_pTempGeometry = nullptr; m_animation_length_seconds = 0.f; m_fCurFrame = 0.f; } @@ -45,12 +45,12 @@ Model::Clear() { if (m_pGeometry != nullptr) { MODELMAN->UnloadModel(m_pGeometry); - m_pGeometry = NULL; + m_pGeometry = nullptr; } m_vpBones.clear(); m_Materials.clear(); m_mapNameToAnimation.clear(); - m_pCurAnimation = NULL; + m_pCurAnimation = nullptr; RecalcAnimationLengthSeconds(); if (m_pTempGeometry != nullptr) @@ -60,10 +60,10 @@ Model::Clear() void Model::Load(const std::string& sFile) { - if (sFile == "") + if (sFile.empty()) return; - std::string sExt = make_lower(GetExtension(sFile)); + const auto sExt = make_lower(GetExtension(sFile)); if (sExt == "txt") LoadMilkshapeAscii(sFile); RecalcAnimationLengthSeconds(); @@ -141,10 +141,10 @@ Model::LoadFromNode(const XNode* pNode) void Model::LoadMaterialsFromMilkshapeAscii(const std::string& _sPath) { - std::string sPath = _sPath; + auto sPath = _sPath; FixSlashesInPlace(sPath); - const std::string sDir = Dirname(sPath); + const auto sDir = Dirname(sPath); RageFile f; if (!f.Open(sPath)) @@ -154,7 +154,7 @@ Model::LoadMaterialsFromMilkshapeAscii(const std::string& _sPath) f.GetError().c_str()); std::string sLine; - int iLineNum = 0; + auto iLineNum = 0; while (f.GetLine(sLine) > 0) { iLineNum++; @@ -173,14 +173,14 @@ Model::LoadMaterialsFromMilkshapeAscii(const std::string& _sPath) } // materials - int nNumMaterials = 0; + auto nNumMaterials = 0; if (sscanf(sLine.c_str(), "Materials: %d", &nNumMaterials) == 1) { m_Materials.resize(nNumMaterials); char szName[256]; - for (int i = 0; i < nNumMaterials; i++) { - msMaterial& Material = m_Materials[i]; + for (auto i = 0; i < nNumMaterials; i++) { + auto& Material = m_Materials[i]; // name if (f.GetLine(sLine) <= 0) @@ -266,10 +266,10 @@ Model::LoadMaterialsFromMilkshapeAscii(const std::string& _sPath) sscanf(sLine.c_str(), "\"%255[^\"]\"", szName); std::string sDiffuseTexture = szName; - if (sDiffuseTexture == "") { + if (sDiffuseTexture.empty()) { Material.diffuse.LoadBlank(); } else { - std::string sTexturePath = sDir + sDiffuseTexture; + auto sTexturePath = sDir + sDiffuseTexture; FixSlashesInPlace(sTexturePath); CollapsePath(sTexturePath); if (!IsAFile(sTexturePath)) @@ -288,10 +288,10 @@ Model::LoadMaterialsFromMilkshapeAscii(const std::string& _sPath) sscanf(sLine.c_str(), "\"%255[^\"]\"", szName); std::string sAlphaTexture = szName; - if (sAlphaTexture == "") { + if (sAlphaTexture.empty()) { Material.alpha.LoadBlank(); } else { - std::string sTexturePath = sDir + sAlphaTexture; + auto sTexturePath = sDir + sAlphaTexture; FixSlashesInPlace(sTexturePath); CollapsePath(sTexturePath); if (!IsAFile(sTexturePath)) @@ -312,7 +312,7 @@ Model::LoadMilkshapeAsciiBones(const std::string& sAniName, const std::string& sPath) { m_mapNameToAnimation[sAniName] = msAnimation(); - msAnimation& Animation = m_mapNameToAnimation[sAniName]; + auto& Animation = m_mapNameToAnimation[sAniName]; if (Animation.LoadMilkshapeAsciiBones(sAniName, sPath)) { m_mapNameToAnimation.erase(sAniName); @@ -325,7 +325,7 @@ Model::LoadMilkshapeAsciiBones(const std::string& sAniName, bool Model::EarlyAbortDraw() const { - return m_pGeometry == NULL || m_pGeometry->m_Meshes.empty(); + return m_pGeometry == nullptr || m_pGeometry->m_Meshes.empty(); } void @@ -370,11 +370,11 @@ Model::DrawPrimitives() if (pMesh->nMaterialIndex != -1) // has a material { // apply material - msMaterial& mat = m_Materials[pMesh->nMaterialIndex]; + auto& mat = m_Materials[pMesh->nMaterialIndex]; - RageColor Emissive = mat.Emissive; - RageColor Ambient = mat.Ambient; - RageColor Diffuse = mat.Diffuse; + auto Emissive = mat.Emissive; + auto Ambient = mat.Ambient; + auto Diffuse = mat.Diffuse; Emissive *= m_pTempState->diffuse[0]; Ambient *= m_pTempState->diffuse[0]; @@ -383,7 +383,7 @@ Model::DrawPrimitives() DISPLAY->SetMaterial( Emissive, Ambient, Diffuse, mat.Specular, mat.fShininess); - RageVector2 vTexTranslate = mat.diffuse.GetTextureTranslate(); + const auto vTexTranslate = mat.diffuse.GetTextureTranslate(); if (vTexTranslate.x != 0 || vTexTranslate.y != 0) { DISPLAY->TexturePushMatrix(); DISPLAY->TextureTranslate(vTexTranslate.x, vTexTranslate.y); @@ -391,8 +391,9 @@ Model::DrawPrimitives() /* There's some common code that could be folded out here, but * it seems clearer to keep it separate. */ - bool bUseMultitexture = PREFSMAN->m_bAllowMultitexture && - DISPLAY->GetNumTextureUnits() >= 2; + const auto bUseMultitexture = + PREFSMAN->m_bAllowMultitexture && + DISPLAY->GetNumTextureUnits() >= 2; if (bUseMultitexture) { // render the diffuse texture with texture unit 1 DISPLAY->SetTexture( @@ -494,17 +495,17 @@ Model::DrawPrimitives() const msMesh* pMesh = &m_pGeometry->m_Meshes[i]; // apply material - RageColor emissive = RageColor(0, 0, 0, 0); - RageColor ambient = RageColor(0, 0, 0, 0); - RageColor diffuse = m_pTempState->glow; - RageColor specular = RageColor(0, 0, 0, 0); - float shininess = 1; + auto emissive = RageColor(0, 0, 0, 0); + auto ambient = RageColor(0, 0, 0, 0); + auto diffuse = m_pTempState->glow; + auto specular = RageColor(0, 0, 0, 0); + const float shininess = 1; DISPLAY->SetMaterial( emissive, ambient, diffuse, specular, shininess); if (pMesh->nMaterialIndex != -1) { - msMaterial& mat = m_Materials[pMesh->nMaterialIndex]; + auto& mat = m_Materials[pMesh->nMaterialIndex]; DISPLAY->SetTexture( TextureUnit_1, mat.diffuse.GetCurrentTexture() @@ -528,7 +529,7 @@ Model::DrawMesh(int i) const if (pMesh->m_iBoneIndex != -1) { DISPLAY->PushMatrix(); - const RageMatrix& mat = m_vpBones[pMesh->m_iBoneIndex].m_Final; + const auto& mat = m_vpBones[pMesh->m_iBoneIndex].m_Final; DISPLAY->PreMultMatrix(mat); } @@ -569,8 +570,8 @@ Model::PlayAnimation(const std::string& sAniName, float fPlayRate) m_vpBones.resize(m_pCurAnimation->Bones.size()); for (unsigned i = 0; i < m_pCurAnimation->Bones.size(); i++) { - const msBone* pBone = &m_pCurAnimation->Bones[i]; - const RageVector3& vRot = pBone->Rotation; + const auto* const pBone = &m_pCurAnimation->Bones[i]; + const auto& vRot = pBone->Rotation; RageMatrixAngles(&m_vpBones[i].m_Relative, vRot); @@ -578,7 +579,8 @@ Model::PlayAnimation(const std::string& sAniName, float fPlayRate) m_vpBones[i].m_Relative.m[3][1] = pBone->Position[1]; m_vpBones[i].m_Relative.m[3][2] = pBone->Position[2]; - int nParentBone = m_pCurAnimation->FindBoneByName(pBone->sParentName); + const auto nParentBone = + m_pCurAnimation->FindBoneByName(pBone->sParentName); if (nParentBone != -1) { RageMatrixMultiply(&m_vpBones[i].m_Absolute, &m_vpBones[nParentBone].m_Absolute, @@ -591,13 +593,13 @@ Model::PlayAnimation(const std::string& sAniName, float fPlayRate) // subtract out the bone's resting position for (auto& m_Meshe : m_pGeometry->m_Meshes) { - msMesh* pMesh = &m_Meshe; - vector& Vertices = pMesh->Vertices; + auto* pMesh = &m_Meshe; + auto& Vertices = pMesh->Vertices; for (auto& Vertice : Vertices) { // int iBoneIndex = (pMesh->m_iBoneIndex!=-1) ? pMesh->m_iBoneIndex // : bone; - RageVector3& pos = Vertice.p; - int8_t bone = Vertice.bone; + auto& pos = Vertice.p; + const auto bone = Vertice.bone; if (bone != -1) { pos[0] -= m_vpBones[bone].m_Absolute.m[3][0]; pos[1] -= m_vpBones[bone].m_Absolute.m[3][1]; @@ -633,7 +635,7 @@ Model::SetPosition(float fSeconds) void Model::AdvanceFrame(float fDeltaTime) { - if (m_pGeometry == NULL || m_pGeometry->m_Meshes.empty() || + if (m_pGeometry == nullptr || m_pGeometry->m_Meshes.empty() || !m_pCurAnimation) { return; // bail early } @@ -642,7 +644,7 @@ Model::AdvanceFrame(float fDeltaTime) m_fCurFrame += FRAMES_PER_SECOND * fDeltaTime * m_fCurAnimationRate; if (m_fCurFrame < 0 || m_fCurFrame >= m_pCurAnimation->nTotalFrames) { - if (m_sDefaultAnimation != "") { + if (!m_sDefaultAnimation.empty()) { this->PlayAnimation(m_sDefaultAnimation, m_fDefaultAnimationRate); /* XXX: add to m_fCurFrame the wrapover from the previous * m_fCurFrame-m_pCurAnimation->nTotalFrames, so it doesn't skip */ @@ -666,17 +668,17 @@ Model::SetBones(const msAnimation* pAnimation, vector& vpBones) { for (size_t i = 0; i < pAnimation->Bones.size(); ++i) { - const msBone* pBone = &pAnimation->Bones[i]; - if (pBone->PositionKeys.size() == 0 && - pBone->RotationKeys.size() == 0) { + const auto* pBone = &pAnimation->Bones[i]; + if (pBone->PositionKeys.empty() && pBone->RotationKeys.empty()) { vpBones[i].m_Final = vpBones[i].m_Absolute; continue; } // search for the adjacent position keys - const msPositionKey *pLastPositionKey = NULL, *pThisPositionKey = NULL; + const msPositionKey *pLastPositionKey = nullptr, + *pThisPositionKey = nullptr; for (const auto& PositionKey : pBone->PositionKeys) { - const msPositionKey* pPositionKey = &PositionKey; + const auto* const pPositionKey = &PositionKey; if (pPositionKey->fTime >= fFrame) { pThisPositionKey = pPositionKey; break; @@ -685,21 +687,22 @@ Model::SetBones(const msAnimation* pAnimation, } RageVector3 vPos; - if (pLastPositionKey != NULL && pThisPositionKey != NULL) { - const float s = SCALE( + if (pLastPositionKey != nullptr && pThisPositionKey != nullptr) { + const auto s = SCALE( fFrame, pLastPositionKey->fTime, pThisPositionKey->fTime, 0, 1); vPos = pLastPositionKey->Position + (pThisPositionKey->Position - pLastPositionKey->Position) * s; - } else if (pLastPositionKey == NULL && pThisPositionKey != NULL) + } else if (pLastPositionKey == nullptr && pThisPositionKey != nullptr) vPos = pThisPositionKey->Position; - else if (pThisPositionKey == NULL && pLastPositionKey != NULL) + else if (pThisPositionKey == nullptr && pLastPositionKey != nullptr) vPos = pLastPositionKey->Position; // search for the adjacent rotation keys - const msRotationKey *pLastRotationKey = NULL, *pThisRotationKey = NULL; + const msRotationKey *pLastRotationKey = nullptr, + *pThisRotationKey = nullptr; for (const auto& RotationKey : pBone->RotationKeys) { - const msRotationKey* pRotationKey = &RotationKey; + const auto* const pRotationKey = &RotationKey; if (pRotationKey->fTime >= fFrame) { pThisRotationKey = pRotationKey; break; @@ -708,14 +711,14 @@ Model::SetBones(const msAnimation* pAnimation, } RageVector4 vRot; - if (pLastRotationKey != NULL && pThisRotationKey != NULL) { - const float s = SCALE( + if (pLastRotationKey != nullptr && pThisRotationKey != nullptr) { + const auto s = SCALE( fFrame, pLastRotationKey->fTime, pThisRotationKey->fTime, 0, 1); RageQuatSlerp( &vRot, pLastRotationKey->Rotation, pThisRotationKey->Rotation, s); - } else if (pLastRotationKey == NULL && pThisRotationKey != NULL) { + } else if (pLastRotationKey == nullptr && pThisRotationKey != nullptr) { vRot = pThisRotationKey->Rotation; - } else if (pThisRotationKey == NULL && pLastRotationKey != NULL) { + } else if (pThisRotationKey == nullptr && pLastRotationKey != nullptr) { vRot = pLastRotationKey->Rotation; } @@ -729,7 +732,7 @@ Model::SetBones(const msAnimation* pAnimation, RageMatrix RelativeFinal; RageMatrixMultiply(&RelativeFinal, &vpBones[i].m_Relative, &m); - int iParentBone = pAnimation->FindBoneByName(pBone->sParentName); + const auto iParentBone = pAnimation->FindBoneByName(pBone->sParentName); if (iParentBone == -1) vpBones[i].m_Final = RelativeFinal; else @@ -742,20 +745,20 @@ Model::SetBones(const msAnimation* pAnimation, void Model::UpdateTempGeometry() { - if (m_pGeometry == NULL || m_pTempGeometry == NULL) + if (m_pGeometry == nullptr || m_pTempGeometry == nullptr) return; for (unsigned i = 0; i < m_pGeometry->m_Meshes.size(); ++i) { - const msMesh& origMesh = m_pGeometry->m_Meshes[i]; - msMesh& tempMesh = m_vTempMeshes[i]; - const vector& origVertices = origMesh.Vertices; - vector& tempVertices = tempMesh.Vertices; + const auto& origMesh = m_pGeometry->m_Meshes[i]; + auto& tempMesh = m_vTempMeshes[i]; + const auto& origVertices = origMesh.Vertices; + auto& tempVertices = tempMesh.Vertices; for (unsigned j = 0; j < origVertices.size(); j++) { - RageVector3& tempPos = tempVertices[j].p; - RageVector3& tempNormal = tempVertices[j].n; - const RageVector3& originalPos = origVertices[j].p; - const RageVector3& originalNormal = origVertices[j].n; - int8_t bone = origVertices[j].bone; + auto& tempPos = tempVertices[j].p; + auto& tempNormal = tempVertices[j].n; + const auto& originalPos = origVertices[j].p; + const auto& originalNormal = origVertices[j].n; + const auto bone = origVertices[j].bone; if (bone == -1) { tempNormal = originalNormal; @@ -788,8 +791,8 @@ Model::Update(float fDelta) int Model::GetNumStates() const { - int iMaxStates = 0; - for (auto& m : m_Materials) + auto iMaxStates = 0; + for (const auto& m : m_Materials) iMaxStates = max(iMaxStates, m.diffuse.GetNumStates()); return iMaxStates; } @@ -807,29 +810,26 @@ void Model::RecalcAnimationLengthSeconds() { m_animation_length_seconds = 0; - FOREACH_CONST(msMaterial, m_Materials, m) - { - m_animation_length_seconds = max( - m_animation_length_seconds, m->diffuse.GetAnimationLengthSeconds()); + for (auto& m : m_Materials) { + m_animation_length_seconds = max(m_animation_length_seconds, + m.diffuse.GetAnimationLengthSeconds()); } } void Model::SetSecondsIntoAnimation(float fSeconds) { - FOREACH(msMaterial, m_Materials, m) - { - m->diffuse.SetSecondsIntoAnimation(fSeconds); - m->alpha.SetSecondsIntoAnimation(fSeconds); + for (auto& m : m_Materials) { + m.diffuse.SetSecondsIntoAnimation(fSeconds); + m.alpha.SetSecondsIntoAnimation(fSeconds); } } bool Model::MaterialsNeedNormals() const { - FOREACH_CONST(msMaterial, m_Materials, m) - { - if (m->NeedsNormals()) + for (auto& m : m_Materials) { + if (m.NeedsNormals()) return true; } return false; diff --git a/src/Etterna/Actor/Base/Model.h b/src/Etterna/Actor/Base/Model.h index 7708df681b..44c02a2ae2 100644 --- a/src/Etterna/Actor/Base/Model.h +++ b/src/Etterna/Actor/Base/Model.h @@ -16,7 +16,7 @@ class Model : public Actor public: Model(); ~Model() override; - Model* Copy() const override; + [[nodiscard]] Model* Copy() const override; void Clear(); void Load(const std::string& sFile); @@ -37,26 +37,30 @@ class Model : public Actor void SetPosition(float fSeconds); void Update(float fDelta) override; - bool EarlyAbortDraw() const override; + [[nodiscard]] bool EarlyAbortDraw() const override; void DrawPrimitives() override; void DrawCelShaded(); void SetCelShading(bool bShading) { m_bDrawCelShaded = bShading; } - int GetNumStates() const override; + [[nodiscard]] int GetNumStates() const override; void SetState(int iNewState) override; - float GetAnimationLengthSeconds() const override + + [[nodiscard]] float GetAnimationLengthSeconds() const override { return m_animation_length_seconds; } virtual void RecalcAnimationLengthSeconds(); void SetSecondsIntoAnimation(float fSeconds) override; - std::string GetDefaultAnimation() const { return m_sDefaultAnimation; }; + [[nodiscard]] std::string GetDefaultAnimation() const + { + return m_sDefaultAnimation; + }; void SetDefaultAnimation(const std::string& sAnimation, float fPlayRate = 1); - bool MaterialsNeedNormals() const; + [[nodiscard]] bool MaterialsNeedNormals() const; // Lua void PushSelf(lua_State* L) override; diff --git a/src/Etterna/Actor/Base/ModelManager.cpp b/src/Etterna/Actor/Base/ModelManager.cpp index 89bec83afe..4bbd257e31 100644 --- a/src/Etterna/Actor/Base/ModelManager.cpp +++ b/src/Etterna/Actor/Base/ModelManager.cpp @@ -12,7 +12,7 @@ ModelManager::ModelManager() = default; ModelManager::~ModelManager() { for (auto& i : m_mapFileToGeometry) { - RageModelGeometry* pGeom = i.second; + auto* pGeom = i.second; if (pGeom->m_iRefCount) LOG->Trace("MODELMAN LEAK: '%s', RefCount = %d.", i.first.c_str(), @@ -24,11 +24,10 @@ ModelManager::~ModelManager() RageModelGeometry* ModelManager::LoadMilkshapeAscii(const std::string& sFile, bool bNeedNormals) { - std::map::iterator p = - m_mapFileToGeometry.find(sFile); + const auto p = m_mapFileToGeometry.find(sFile); if (p != m_mapFileToGeometry.end()) { /* Found the geometry. Just increase the refcount and return it. */ - RageModelGeometry* pGeom = p->second; + auto* pGeom = p->second; ++pGeom->m_iRefCount; return pGeom; } @@ -49,9 +48,7 @@ ModelManager::UnloadModel(RageModelGeometry* m) if (m->m_iRefCount) return; /* Can't unload models that are still referenced. */ - for (std::map::iterator i = - m_mapFileToGeometry.begin(); - i != m_mapFileToGeometry.end(); + for (auto i = m_mapFileToGeometry.begin(); i != m_mapFileToGeometry.end(); ++i) { if (i->second == m) { if (m_Prefs.m_bDelayedUnload) { diff --git a/src/Etterna/Actor/Base/ModelManager.h b/src/Etterna/Actor/Base/ModelManager.h index 5796f94762..cf3de9ece0 100644 --- a/src/Etterna/Actor/Base/ModelManager.h +++ b/src/Etterna/Actor/Base/ModelManager.h @@ -15,7 +15,7 @@ struct ModelManagerPrefs m_bDelayedUnload = bDelayedUnload; } - bool operator!=(const ModelManagerPrefs& rhs) + bool operator!=(const ModelManagerPrefs& rhs) const { return m_bDelayedUnload != rhs.m_bDelayedUnload; } @@ -40,7 +40,7 @@ class ModelManager * @param prefs the new preferences to set up. * @return true if the display needs to be reset, false otherwise. */ bool SetPrefs(const ModelManagerPrefs& prefs); - const ModelManagerPrefs& GetPrefs() { return m_Prefs; } + [[nodiscard]] const ModelManagerPrefs& GetPrefs() const { return m_Prefs; } protected: std::map m_mapFileToGeometry; diff --git a/src/Etterna/Actor/Base/ModelTypes.cpp b/src/Etterna/Actor/Base/ModelTypes.cpp index 992b0fa0ac..8f9b5c5669 100644 --- a/src/Etterna/Actor/Base/ModelTypes.cpp +++ b/src/Etterna/Actor/Base/ModelTypes.cpp @@ -29,7 +29,7 @@ AnimatedTexture::~AnimatedTexture() void AnimatedTexture::LoadBlank() { - AnimatedTextureState state(nullptr, 1, RageVector2(0, 0)); + const AnimatedTextureState state(nullptr, 1, RageVector2(0, 0)); vFrames.push_back(state); } @@ -63,16 +63,16 @@ AnimatedTexture::Load(const std::string& sTexOrIniPath) pAnimatedTexture->GetAttrValue("TexOffsetX", m_vTexOffset.x); pAnimatedTexture->GetAttrValue("TexOffsetY", m_vTexOffset.y); - for (int i = 0; i < 1000; i++) { - std::string sFileKey = ssprintf("Frame%04d", i); - std::string sDelayKey = ssprintf("Delay%04d", i); + for (auto i = 0; i < 1000; i++) { + auto sFileKey = ssprintf("Frame%04d", i); + auto sDelayKey = ssprintf("Delay%04d", i); std::string sFileName; float fDelay = 0; if (pAnimatedTexture->GetAttrValue(sFileKey, sFileName) && pAnimatedTexture->GetAttrValue(sDelayKey, fDelay)) { - std::string sTranslateXKey = ssprintf("TranslateX%04d", i); - std::string sTranslateYKey = ssprintf("TranslateY%04d", i); + auto sTranslateXKey = ssprintf("TranslateX%04d", i); + auto sTranslateYKey = ssprintf("TranslateY%04d", i); RageVector2 vOffset(0, 0); pAnimatedTexture->GetAttrValue(sTranslateXKey, vOffset.x); @@ -141,7 +141,7 @@ float AnimatedTexture::GetAnimationLengthSeconds() const { float fTotalSeconds = 0; - for (auto& ats : vFrames) + for (const auto& ats : vFrames) fTotalSeconds += ats.fDelaySecs; return fTotalSeconds; } @@ -153,7 +153,7 @@ AnimatedTexture::SetSecondsIntoAnimation(float fSeconds) m_iCurState = 0; for (unsigned i = 0; i < vFrames.size(); i++) { - AnimatedTextureState& ats = vFrames[i]; + auto& ats = vFrames[i]; if (fSeconds >= ats.fDelaySecs) { fSeconds -= ats.fDelaySecs; m_iCurState = i + 1; @@ -170,7 +170,7 @@ AnimatedTexture::GetSecondsIntoAnimation() const float fSeconds = 0; for (unsigned i = 0; i < vFrames.size(); i++) { - const AnimatedTextureState& ats = vFrames[i]; + const auto& ats = vFrames[i]; if (static_cast(i) >= m_iCurState) break; @@ -193,9 +193,9 @@ AnimatedTexture::Unload() RageVector2 AnimatedTexture::GetTextureTranslate() { - float fPercentIntoAnimation = + const auto fPercentIntoAnimation = GetSecondsIntoAnimation() / GetAnimationLengthSeconds(); - RageVector2 v = m_vTexVelocity * fPercentIntoAnimation + m_vTexOffset; + auto v = m_vTexVelocity * fPercentIntoAnimation + m_vTexOffset; if (vFrames.empty()) return v; @@ -217,7 +217,7 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, std::string sPath) { FixSlashesInPlace(sPath); - const std::string sDir = Dirname(sPath); + const auto sDir = Dirname(sPath); RageFile f; if (!f.Open(sPath)) @@ -226,11 +226,11 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, f.GetError().c_str()); std::string sLine; - int iLineNum = 0; + auto iLineNum = 0; - msAnimation& Animation = *this; + auto& Animation = *this; - bool bLoaded = false; + const auto bLoaded = false; while (f.GetLine(sLine) > 0) { iLineNum++; @@ -238,7 +238,7 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, continue; // bones - int nNumBones = 0; + auto nNumBones = 0; if (sscanf(sLine.c_str(), "Bones: %d", &nNumBones) != 1) continue; @@ -246,8 +246,8 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, Animation.Bones.resize(nNumBones); - for (int i = 0; i < nNumBones; i++) { - msBone& Bone = Animation.Bones[i]; + for (auto i = 0; i < nNumBones; i++) { + auto& Bone = Animation.Bones[i]; // name if (f.GetLine(sLine) <= 0) @@ -290,13 +290,13 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, // position key count if (f.GetLine(sLine) <= 0) THROW; - int nNumPositionKeys = 0; + auto nNumPositionKeys = 0; if (sscanf(sLine.c_str(), "%d", &nNumPositionKeys) != 1) THROW; Bone.PositionKeys.resize(nNumPositionKeys); - for (int j = 0; j < nNumPositionKeys; ++j) { + for (auto j = 0; j < nNumPositionKeys; ++j) { if (f.GetLine(sLine) <= 0) THROW; @@ -319,13 +319,13 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, // rotation key count if (f.GetLine(sLine) <= 0) THROW; - int nNumRotationKeys = 0; + auto nNumRotationKeys = 0; if (sscanf(sLine.c_str(), "%d", &nNumRotationKeys) != 1) THROW; Bone.RotationKeys.resize(nNumRotationKeys); - for (int j = 0; j < nNumRotationKeys; ++j) { + for (auto j = 0; j < nNumRotationKeys; ++j) { if (f.GetLine(sLine) <= 0) THROW; @@ -349,8 +349,8 @@ msAnimation::LoadMilkshapeAsciiBones(const std::string& sAniName, // Ignore "Frames:" in file. Calculate it ourself Animation.nTotalFrames = 0; - for (int i = 0; i < static_cast(Animation.Bones.size()); i++) { - msBone& Bone = Animation.Bones[i]; + for (auto i = 0; i < static_cast(Animation.Bones.size()); i++) { + auto& Bone = Animation.Bones[i]; for (auto& PositionKey : Bone.PositionKeys) Animation.nTotalFrames = max( Animation.nTotalFrames, static_cast(PositionKey.fTime)); diff --git a/src/Etterna/Actor/Base/ModelTypes.h b/src/Etterna/Actor/Base/ModelTypes.h index 6ff7a0ed2c..a5cc910f87 100644 --- a/src/Etterna/Actor/Base/ModelTypes.h +++ b/src/Etterna/Actor/Base/ModelTypes.h @@ -42,17 +42,17 @@ class AnimatedTexture RageTexture* GetCurrentTexture(); - int GetNumStates() const; + [[nodiscard]] int GetNumStates() const; void SetState(int iNewState); - float GetAnimationLengthSeconds() const; + [[nodiscard]] float GetAnimationLengthSeconds() const; void SetSecondsIntoAnimation(float fSeconds); - float GetSecondsIntoAnimation() const; + [[nodiscard]] float GetSecondsIntoAnimation() const; RageVector2 GetTextureTranslate(); bool m_bSphereMapped; BlendMode m_BlendMode; - bool NeedsNormals() const { return m_bSphereMapped; } + [[nodiscard]] bool NeedsNormals() const { return m_bSphereMapped; } private: RageVector2 m_vTexOffset; @@ -92,7 +92,7 @@ struct msMaterial AnimatedTexture diffuse; AnimatedTexture alpha; - bool NeedsNormals() const + [[nodiscard]] bool NeedsNormals() const { return diffuse.NeedsNormals() || alpha.NeedsNormals(); } @@ -124,7 +124,7 @@ struct msBone struct msAnimation { - int FindBoneByName(const std::string& sName) const + [[nodiscard]] int FindBoneByName(const std::string& sName) const { for (unsigned i = 0; i < Bones.size(); i++) if (Bones[i].sName == sName) diff --git a/src/Etterna/Actor/Base/Quad.cpp b/src/Etterna/Actor/Base/Quad.cpp index 36baf97cfb..f38cf686a5 100644 --- a/src/Etterna/Actor/Base/Quad.cpp +++ b/src/Etterna/Actor/Base/Quad.cpp @@ -1,4 +1,4 @@ -#include "Etterna/Globals/global.h" +#include "Etterna/Globals/global.h" #include "ActorUtil.h" #include "Quad.h" #include "RageUtil/Graphics/RageTextureManager.h" diff --git a/src/Etterna/Actor/Base/Quad.h b/src/Etterna/Actor/Base/Quad.h index 43b0061d4a..3aa431f792 100644 --- a/src/Etterna/Actor/Base/Quad.h +++ b/src/Etterna/Actor/Base/Quad.h @@ -1,4 +1,4 @@ -#ifndef QUAD_H +#ifndef QUAD_H #define QUAD_H #include "Sprite.h" @@ -15,7 +15,7 @@ class Quad : public Sprite */ void LoadFromNode(const XNode* pNode) override; /** @brief Copy the quad. */ - Quad* Copy() const override; + [[nodiscard]] Quad* Copy() const override; }; #endif diff --git a/src/Etterna/Actor/Base/RollingNumbers.cpp b/src/Etterna/Actor/Base/RollingNumbers.cpp index 371cc61e4d..046bcc4ac9 100644 --- a/src/Etterna/Actor/Base/RollingNumbers.cpp +++ b/src/Etterna/Actor/Base/RollingNumbers.cpp @@ -6,6 +6,7 @@ #include "RollingNumbers.h" #include "Etterna/Singletons/ThemeManager.h" #include "Etterna/FileTypes/XmlFile.h" + REGISTER_ACTOR_CLASS(RollingNumbers); RollingNumbers::RollingNumbers() @@ -34,7 +35,7 @@ RollingNumbers::DrawPart(RageColor const* diffuse, float crop_left, float crop_right) { - for (int i = 0; i < NUM_DIFFUSE_COLORS; ++i) { + for (auto i = 0; i < NUM_DIFFUSE_COLORS; ++i) { m_pTempState->diffuse[i] = diffuse[i]; } SetCurrStrokeColor(stroke); @@ -51,17 +52,17 @@ RollingNumbers::DrawPrimitives() } RageColor diffuse_orig[NUM_DIFFUSE_COLORS]; RageColor diffuse_temp[NUM_DIFFUSE_COLORS]; - RageColor stroke_orig = GetCurrStrokeColor(); - RageColor stroke_temp = stroke_orig * LEADING_ZERO_MULTIPLY_COLOR; - for (int i = 0; i < NUM_DIFFUSE_COLORS; ++i) { + const auto stroke_orig = GetCurrStrokeColor(); + const auto stroke_temp = stroke_orig * LEADING_ZERO_MULTIPLY_COLOR; + for (auto i = 0; i < NUM_DIFFUSE_COLORS; ++i) { diffuse_orig[i] = m_pTempState->diffuse[i]; diffuse_temp[i] = m_pTempState->diffuse[i] * LEADING_ZERO_MULTIPLY_COLOR; } - float original_crop_left = m_pTempState->crop.left; - float original_crop_right = m_pTempState->crop.right; + const auto original_crop_left = m_pTempState->crop.left; + const auto original_crop_right = m_pTempState->crop.right; - std::string s = this->GetText(); + auto s = this->GetText(); int i; // find the first non-zero non-comma character, or the last character for (i = 0; i < (int)(s.length() - 1); i++) { @@ -75,7 +76,7 @@ RollingNumbers::DrawPrimitives() if (s[i] >= '0' && s[i] <= '9') break; } - float f = i / static_cast(s.length()); + const auto f = i / static_cast(s.length()); // draw leading part DrawPart(diffuse_temp, @@ -117,7 +118,7 @@ RollingNumbers::SetTargetNumber(float fTargetNumber) if (fTargetNumber == m_fTargetNumber) // no change return; m_fTargetNumber = fTargetNumber; - float approach_secs = APPROACH_SECONDS.GetValue(); + const auto approach_secs = APPROACH_SECONDS.GetValue(); if (approach_secs > 0) { m_fScoreVelocity = (m_fTargetNumber - m_fCurrentNumber) / approach_secs; } else { @@ -131,7 +132,7 @@ RollingNumbers::UpdateText() if (!m_metrics_loaded) { return; } - std::string s = ssprintf(TEXT_FORMAT.GetValue(), m_fCurrentNumber); + auto s = ssprintf(TEXT_FORMAT.GetValue(), m_fCurrentNumber); if (COMMIFY) { s = Commify(s); } diff --git a/src/Etterna/Actor/Base/Sprite.cpp b/src/Etterna/Actor/Base/Sprite.cpp index 5ded4122a7..4900339b4d 100644 --- a/src/Etterna/Actor/Base/Sprite.cpp +++ b/src/Etterna/Actor/Base/Sprite.cpp @@ -1,6 +1,4 @@ #include "Etterna/Globals/global.h" -#include -#include #include "ActorUtil.h" #include "Etterna/Singletons/InputFilter.h" #include "Etterna/Models/Lua/LuaBinding.h" @@ -11,6 +9,9 @@ #include "Etterna/Models/Misc/ThemeMetric.h" #include "Sprite.h" +#include +#include + REGISTER_ACTOR_CLASS(Sprite); const float min_state_delay = 0.0001f; @@ -177,16 +178,16 @@ Sprite::LoadFromNode(const XNode* pNode) // frames and delays created during LoadFromTexture(). vector aStates; - const XNode* pFrames = pNode->GetChild("Frames"); + auto pFrames = pNode->GetChild("Frames"); if (pFrames != nullptr) { /* All attributes are optional. If Frame is omitted, use the * previous state's frame (or 0 if the first). Frames = { { * Delay=1.0f; Frame=0; { x=0, y=0 }, { x=1, y=1 } }; * } */ - int iFrameIndex = 0; - for (int i = 0; true; i++) { - const XNode* pFrame = pFrames->GetChild( + auto iFrameIndex = 0; + for (auto i = 0; true; i++) { + auto pFrame = pFrames->GetChild( ssprintf("%i", i + 1)); // +1 for Lua's arrays if (pFrame == nullptr) break; @@ -212,9 +213,9 @@ Sprite::LoadFromNode(const XNode* pNode) const XNode* pPoints[2] = { pFrame->GetChild("1"), pFrame->GetChild("2") }; if (pPoints[0] != nullptr && pPoints[1] != nullptr) { - RectF r = newState.rect; + const auto r = newState.rect; - float fX = 1.0f, fY = 1.0f; + auto fX = 1.0f, fY = 1.0f; pPoints[0]->GetAttrValue("x", fX); pPoints[0]->GetAttrValue("y", fY); newState.rect.left = SCALE(fX, 0.0f, 1.0f, r.left, r.right); @@ -231,10 +232,10 @@ Sprite::LoadFromNode(const XNode* pNode) aStates.push_back(newState); } } else - for (int i = 0; true; i++) { + for (auto i = 0; true; i++) { // deprecated - std::string sFrameKey = ssprintf("Frame%04d", i); - std::string sDelayKey = ssprintf("Delay%04d", i); + auto sFrameKey = ssprintf("Frame%04d", i); + auto sDelayKey = ssprintf("Delay%04d", i); State newState; int iFrameIndex; @@ -288,7 +289,7 @@ Sprite::UnloadTexture() void Sprite::EnableAnimation(bool bEnable) { - bool bWasEnabled = m_bIsAnimating; + const auto bWasEnabled = m_bIsAnimating; Actor::EnableAnimation(bEnable); if (bEnable && !bWasEnabled) { @@ -389,7 +390,7 @@ Sprite::LoadStatesFromTexture() return; } - for (int i = 0; i < m_pTexture->GetNumFrames(); ++i) { + for (auto i = 0; i < m_pTexture->GetNumFrames(); ++i) { State newState; newState.fDelay = 0.1f; newState.rect = *m_pTexture->GetTextureCoordRect(i); @@ -444,7 +445,7 @@ Sprite::Update(float fDelta) { Actor::Update(fDelta); // do tweening - const bool bSkipThisMovieUpdate = m_bSkipNextUpdate; + const auto bSkipThisMovieUpdate = m_bSkipNextUpdate; m_bSkipNextUpdate = false; if (!m_bIsAnimating) @@ -453,7 +454,7 @@ Sprite::Update(float fDelta) if (m_pTexture == nullptr) // no texture, nothing to animate return; - float fTimePassed = GetEffectDeltaTime(); + const auto fTimePassed = GetEffectDeltaTime(); m_fSecsIntoState += fTimePassed; if (m_fSecsIntoState < 0) @@ -467,7 +468,7 @@ Sprite::Update(float fDelta) // update scrolling if (m_fTexCoordVelocityX != 0 || m_fTexCoordVelocityY != 0) { - float coord_delta = fDelta; + auto coord_delta = fDelta; if (m_use_effect_clock_for_texcoords) { coord_delta = fTimePassed; } @@ -489,8 +490,8 @@ Sprite::Update(float fDelta) * texture coordinates back to 0. As long as we adjust all four * coordinates by the same amount, this won't be visible. */ if (m_bTextureWrapping) { - const float fXAdjust = floorf(fTexCoords[0]); - const float fYAdjust = floorf(fTexCoords[1]); + const auto fXAdjust = floorf(fTexCoords[0]); + const auto fYAdjust = floorf(fTexCoords[1]); fTexCoords[0] -= fXAdjust; fTexCoords[2] -= fXAdjust; fTexCoords[4] -= fXAdjust; @@ -523,7 +524,7 @@ Sprite::DrawTexture(const TweenState* state) { Actor::SetGlobalRenderStates(); // set Actor-specified render states - RectF crop = state->crop; + auto crop = state->crop; // bail if cropped all the way if (crop.left + crop.right >= 1 || crop.top + crop.bottom >= 1) return; @@ -544,7 +545,7 @@ Sprite::DrawTexture(const TweenState* state) CLAMP(crop.top, 0, 1); CLAMP(crop.bottom, 0, 1); - RectF croppedQuadVerticies = quadVerticies; + auto croppedQuadVerticies = quadVerticies; #define IF_CROP_POS(side, opp_side) \ if (state->crop.side != 0) \ croppedQuadVerticies.side = \ @@ -565,7 +566,7 @@ Sprite::DrawTexture(const TweenState* state) v[3].p = RageVector3( croppedQuadVerticies.right, croppedQuadVerticies.top, 0); // top right if (m_bUsingCustomPosCoords) { - for (int i = 0; i < 4; ++i) { + for (auto i = 0; i < 4; ++i) { v[i].p.x += m_CustomPosCoords[i * 2]; v[i].p.y += m_CustomPosCoords[(i * 2) + 1]; } @@ -593,34 +594,34 @@ Sprite::DrawTexture(const TweenState* state) }; for (auto& i : v) { - RageSpriteVertex* pVert = &i; - - float fTopX = SCALE(pVert->p.x, - quadVerticies.left, - quadVerticies.right, - texCoords[0].x, - texCoords[3].x); - float fBottomX = SCALE(pVert->p.x, - quadVerticies.left, - quadVerticies.right, - texCoords[1].x, - texCoords[2].x); + auto pVert = &i; + + const auto fTopX = SCALE(pVert->p.x, + quadVerticies.left, + quadVerticies.right, + texCoords[0].x, + texCoords[3].x); + const auto fBottomX = SCALE(pVert->p.x, + quadVerticies.left, + quadVerticies.right, + texCoords[1].x, + texCoords[2].x); pVert->t.x = SCALE(pVert->p.y, quadVerticies.top, quadVerticies.bottom, fTopX, fBottomX); - float fLeftY = SCALE(pVert->p.y, - quadVerticies.top, - quadVerticies.bottom, - texCoords[0].y, - texCoords[1].y); - float fRightY = SCALE(pVert->p.y, - quadVerticies.top, - quadVerticies.bottom, - texCoords[3].y, - texCoords[2].y); + const auto fLeftY = SCALE(pVert->p.y, + quadVerticies.top, + quadVerticies.bottom, + texCoords[0].y, + texCoords[1].y); + const auto fRightY = SCALE(pVert->p.y, + quadVerticies.top, + quadVerticies.bottom, + texCoords[3].y, + texCoords[2].y); pVert->t.y = SCALE(pVert->p.x, quadVerticies.left, quadVerticies.right, @@ -649,7 +650,7 @@ Sprite::DrawTexture(const TweenState* state) DISPLAY->PushMatrix(); DISPLAY->TranslateWorld( m_fShadowLengthX, m_fShadowLengthY, 0); // shift by 5 units - RageColor c = m_ShadowColor; + auto c = m_ShadowColor; c.a *= state->diffuse[0].a; v[0].c = v[1].c = v[2].c = v[3].c = c; // semi-transparent black DISPLAY->DrawQuad(v); @@ -687,42 +688,42 @@ Sprite::DrawPrimitives() if (m_pTempState->fade.top > 0 || m_pTempState->fade.bottom > 0 || m_pTempState->fade.left > 0 || m_pTempState->fade.right > 0) { // We're fading the edges. - const RectF& FadeDist = m_pTempState->fade; + const auto& FadeDist = m_pTempState->fade; // Actual size of the fade on each side: - RectF FadeSize = FadeDist; + auto FadeSize = FadeDist; // If the cropped size is less than the fade distance in either // dimension, clamp. - const float HorizRemaining = + const auto HorizRemaining = 1.0f - (m_pTempState->crop.left + m_pTempState->crop.right); if (FadeDist.left + FadeDist.right > 0 && HorizRemaining < FadeDist.left + FadeDist.right) { - const float LeftPercent = + const auto LeftPercent = FadeDist.left / (FadeDist.left + FadeDist.right); FadeSize.left = LeftPercent * HorizRemaining; FadeSize.right = (1.0f - LeftPercent) * HorizRemaining; } - const float VertRemaining = + const auto VertRemaining = 1.0f - (m_pTempState->crop.top + m_pTempState->crop.bottom); if (FadeDist.top + FadeDist.bottom > 0 && VertRemaining < FadeDist.top + FadeDist.bottom) { - const float TopPercent = + const auto TopPercent = FadeDist.top / (FadeDist.top + FadeDist.bottom); FadeSize.top = TopPercent * VertRemaining; FadeSize.bottom = (1.0f - TopPercent) * VertRemaining; } // Alpha value of the un-faded side of each fade rect: - const float RightAlpha = SCALE(FadeSize.right, FadeDist.right, 0, 1, 0); - const float LeftAlpha = SCALE(FadeSize.left, FadeDist.left, 0, 1, 0); - const float TopAlpha = SCALE(FadeSize.top, FadeDist.top, 0, 1, 0); - const float BottomAlpha = + const auto RightAlpha = SCALE(FadeSize.right, FadeDist.right, 0, 1, 0); + const auto LeftAlpha = SCALE(FadeSize.left, FadeDist.left, 0, 1, 0); + const auto TopAlpha = SCALE(FadeSize.top, FadeDist.top, 0, 1, 0); + const auto BottomAlpha = SCALE(FadeSize.bottom, FadeDist.bottom, 0, 1, 0); // Draw the inside: - TweenState ts = *m_pTempState; + auto ts = *m_pTempState; ts.crop.left += FadeDist.left; ts.crop.right += FadeDist.right; ts.crop.top += FadeDist.top; @@ -910,7 +911,7 @@ Sprite::SetCustomTextureCoords( { m_bUsingCustomTexCoords = true; m_bTextureWrapping = true; - for (int i = 0; i < 8; i++) + for (auto i = 0; i < 8; i++) m_CustomTexCoords[i] = fTexCoords[i]; } @@ -937,7 +938,7 @@ Sprite::SetCustomImageCoords(float fImageCoords[8]) // order: top left, bottom // right { // convert image coords to texture coords in place - for (int i = 0; i < 8; i += 2) { + for (auto i = 0; i < 8; i += 2) { fImageCoords[i + 0] *= m_pTexture->GetImageWidth() / static_cast(m_pTexture->GetTextureWidth()); @@ -954,7 +955,7 @@ Sprite::SetCustomPosCoords( float fPosCoords[8]) // order: top left, bottom left, bottom right, top right { m_bUsingCustomPosCoords = true; - for (int i = 0; i < 8; ++i) { + for (auto i = 0; i < 8; ++i) { m_CustomPosCoords[i] = fPosCoords[i]; } } @@ -983,11 +984,11 @@ Sprite::GetActiveTextureCoords(float fTexCoordsOut[8]) const { if (m_bUsingCustomTexCoords) { // GetCustomTextureCoords - for (int i = 0; i < 8; i++) + for (auto i = 0; i < 8; i++) fTexCoordsOut[i] = m_CustomTexCoords[i]; } else { // GetCurrentTextureCoords - const RectF* pTexCoordRect = GetCurrentTextureCoordRect(); + auto pTexCoordRect = GetCurrentTextureCoordRect(); TexCoordArrayFromRect(fTexCoordsOut, *pTexCoordRect); } } @@ -1020,12 +1021,12 @@ Sprite::ScaleToClipped(float fWidth, float fHeight) if (m_pTexture == nullptr) return; - float fScaleFudgePercent = + const auto fScaleFudgePercent = 0.15f; // scale up to this amount in one dimension to avoid clipping. // save the original X and Y. We're going to restore them later. - float fOriginalX = GetX(); - float fOriginalY = GetY(); + const auto fOriginalX = GetX(); + const auto fOriginalY = GetY(); if (fWidth != -1 && fHeight != -1) { // this is probably a background graphic or something not intended to be @@ -1035,35 +1036,35 @@ Sprite::ScaleToClipped(float fWidth, float fHeight) // first find the correct zoom Sprite::ScaleToCover(RectF(0, 0, fWidth, fHeight)); // find which dimension is larger - bool bXDimNeedsToBeCropped = GetZoomedWidth() > fWidth + 0.01; + const auto bXDimNeedsToBeCropped = GetZoomedWidth() > fWidth + 0.01; if (bXDimNeedsToBeCropped) // crop X { - float fPercentageToCutOff = + auto fPercentageToCutOff = (this->GetZoomedWidth() - fWidth) / this->GetZoomedWidth(); fPercentageToCutOff = max(fPercentageToCutOff - fScaleFudgePercent, 0); - float fPercentageToCutOffEachSide = fPercentageToCutOff / 2; + const auto fPercentageToCutOffEachSide = fPercentageToCutOff / 2; // generate a rectangle with new texture coordinates - RectF fCustomImageRect(fPercentageToCutOffEachSide, - 0, - 1 - fPercentageToCutOffEachSide, - 1); + const RectF fCustomImageRect(fPercentageToCutOffEachSide, + 0, + 1 - fPercentageToCutOffEachSide, + 1); SetCustomImageRect(fCustomImageRect); } else // crop Y { - float fPercentageToCutOff = + auto fPercentageToCutOff = (this->GetZoomedHeight() - fHeight) / this->GetZoomedHeight(); fPercentageToCutOff = max(fPercentageToCutOff - fScaleFudgePercent, 0); - float fPercentageToCutOffEachSide = fPercentageToCutOff / 2; + const auto fPercentageToCutOffEachSide = fPercentageToCutOff / 2; // generate a rectangle with new texture coordinates - RectF fCustomImageRect(0, - fPercentageToCutOffEachSide, - 1, - 1 - fPercentageToCutOffEachSide); + const RectF fCustomImageRect(0, + fPercentageToCutOffEachSide, + 1, + 1 - fPercentageToCutOffEachSide); SetCustomImageRect(fCustomImageRect); } m_size = RageVector2(fWidth, fHeight); @@ -1086,8 +1087,8 @@ Sprite::CropTo(float fWidth, float fHeight) return; // save the original X&Y. We're going to restore them later. - float fOriginalX = GetX(); - float fOriginalY = GetY(); + const auto fOriginalX = GetX(); + const auto fOriginalY = GetY(); if (fWidth != -1 && fHeight != -1) { // this is probably a background graphic or something not intended to be @@ -1097,31 +1098,31 @@ Sprite::CropTo(float fWidth, float fHeight) // first find the correct zoom Sprite::ScaleToCover(RectF(0, 0, fWidth, fHeight)); // find which dimension is larger - bool bXDimNeedsToBeCropped = GetZoomedWidth() > fWidth + 0.01; + const auto bXDimNeedsToBeCropped = GetZoomedWidth() > fWidth + 0.01; if (bXDimNeedsToBeCropped) // crop X { - float fPercentageToCutOff = + const auto fPercentageToCutOff = (this->GetZoomedWidth() - fWidth) / this->GetZoomedWidth(); - float fPercentageToCutOffEachSide = fPercentageToCutOff / 2; + const auto fPercentageToCutOffEachSide = fPercentageToCutOff / 2; // generate a rectangle with new texture coordinates - RectF fCustomImageRect(fPercentageToCutOffEachSide, - 0, - 1 - fPercentageToCutOffEachSide, - 1); + const RectF fCustomImageRect(fPercentageToCutOffEachSide, + 0, + 1 - fPercentageToCutOffEachSide, + 1); SetCustomImageRect(fCustomImageRect); } else // crop Y { - float fPercentageToCutOff = + const auto fPercentageToCutOff = (this->GetZoomedHeight() - fHeight) / this->GetZoomedHeight(); - float fPercentageToCutOffEachSide = fPercentageToCutOff / 2; + const auto fPercentageToCutOffEachSide = fPercentageToCutOff / 2; // generate a rectangle with new texture coordinates - RectF fCustomImageRect(0, - fPercentageToCutOffEachSide, - 1, - 1 - fPercentageToCutOffEachSide); + const RectF fCustomImageRect(0, + fPercentageToCutOffEachSide, + 1, + 1 - fPercentageToCutOffEachSide); SetCustomImageRect(fCustomImageRect); } m_size = RageVector2(fWidth, fHeight); @@ -1139,7 +1140,7 @@ Sprite::StretchTexCoords(float fX, float fY) float fTexCoords[8]; GetActiveTextureCoords(fTexCoords); - for (int j = 0; j < 8; j += 2) { + for (auto j = 0; j < 8; j += 2) { fTexCoords[j] += fX; fTexCoords[j + 1] += fY; } @@ -1153,7 +1154,7 @@ Sprite::AddImageCoords(float fX, float fY) float fTexCoords[8]; GetActiveTextureCoords(fTexCoords); - for (int j = 0; j < 8; j += 2) { + for (auto j = 0; j < 8; j += 2) { fTexCoords[j] += fX / static_cast(m_pTexture->GetTextureWidth()); fTexCoords[j + 1] += fY / static_cast(m_pTexture->GetTextureHeight()); @@ -1174,14 +1175,14 @@ class LunaSprite : public Luna if (lua_isnil(L, 1)) { p->UnloadTexture(); } else { - RageTextureID ID(SArg(1)); + const RageTextureID ID(SArg(1)); p->Load(ID); } COMMON_RETURN_SELF; } static int LoadBackground(T* p, lua_State* L) { - RageTextureID ID(SArg(1)); + const RageTextureID ID(SArg(1)); TEXTUREMAN->DisableOddDimensionWarning(); p->Load(Sprite::SongBGTexture(ID)); TEXTUREMAN->EnableOddDimensionWarning(); @@ -1189,7 +1190,7 @@ class LunaSprite : public Luna } static int LoadBanner(T* p, lua_State* L) { - RageTextureID ID(SArg(1)); + const RageTextureID ID(SArg(1)); TEXTUREMAN->DisableOddDimensionWarning(); p->Load(Sprite::SongBannerTexture(ID)); TEXTUREMAN->EnableOddDimensionWarning(); @@ -1211,7 +1212,7 @@ class LunaSprite : public Luna static int SetCustomPosCoords(T* p, lua_State* L) { float coords[8]; - for (int i = 0; i < 8; ++i) { + for (auto i = 0; i < 8; ++i) { coords[i] = FArg(i + 1); if (isnan(coords[i])) { coords[i] = 0.0f; @@ -1283,7 +1284,7 @@ class LunaSprite : public Luna luaL_error(L, "State properties must be in a table."); } vector new_states; - size_t num_states = lua_objlen(L, 1); + const auto num_states = lua_objlen(L, 1); if (num_states == 0) { luaL_error(L, "A Sprite cannot have zero states."); } @@ -1291,7 +1292,7 @@ class LunaSprite : public Luna Sprite::State new_state; lua_rawgeti(L, 1, s + 1); lua_getfield(L, -1, "Frame"); - int frame_index = 0; + auto frame_index = 0; if (lua_isnumber(L, -1) != 0) { frame_index = IArg(-1); if (frame_index < 0 || @@ -1308,7 +1309,7 @@ class LunaSprite : public Luna new_state.fDelay = FArg(-1); } lua_pop(L, 1); - RectF r = new_state.rect; + const auto r = new_state.rect; lua_rawgeti(L, -1, 1); if (lua_istable(L, -1)) { lua_rawgeti(L, -1, 1); @@ -1357,14 +1358,14 @@ class LunaSprite : public Luna } static int SetTexture(T* p, lua_State* L) { - RageTexture* pTexture = Luna::check(L, 1); + auto pTexture = Luna::check(L, 1); pTexture = TEXTUREMAN->CopyTexture(pTexture); p->SetTexture(pTexture); COMMON_RETURN_SELF; } static int GetTexture(T* p, lua_State* L) { - RageTexture* pTexture = p->GetTexture(); + auto pTexture = p->GetTexture(); if (pTexture != nullptr) pTexture->PushSelf(L); else @@ -1373,7 +1374,7 @@ class LunaSprite : public Luna } static int SetEffectMode(T* p, lua_State* L) { - EffectMode em = Enum::Check(L, 1); + const auto em = Enum::Check(L, 1); p->SetEffectMode(em); COMMON_RETURN_SELF; } diff --git a/src/Etterna/Actor/Base/Sprite.h b/src/Etterna/Actor/Base/Sprite.h index 6ca5e1ec4d..2d8584c969 100644 --- a/src/Etterna/Actor/Base/Sprite.h +++ b/src/Etterna/Actor/Base/Sprite.h @@ -30,9 +30,9 @@ class Sprite : public Actor void InitState() override; void LoadFromNode(const XNode* pNode) override; - Sprite* Copy() const override; + [[nodiscard]] Sprite* Copy() const override; - bool EarlyAbortDraw() const override; + [[nodiscard]] bool EarlyAbortDraw() const override; void DrawPrimitives() override; void Update(float fDeltaTime) override; @@ -49,14 +49,15 @@ class Sprite : public Actor void SetTexture(RageTexture* pTexture); void UnloadTexture(); - RageTexture* GetTexture() { return m_pTexture; }; + [[nodiscard]] RageTexture* GetTexture() const { return m_pTexture; }; void EnableAnimation(bool bEnable) override; - int GetNumStates() const override; + [[nodiscard]] int GetNumStates() const override; void SetState(int iNewState) override; - int GetState() { return m_iCurState; } - float GetAnimationLengthSeconds() const override + [[nodiscard]] int GetState() const { return m_iCurState; } + + [[nodiscard]] float GetAnimationLengthSeconds() const override { return m_animation_length_seconds; } @@ -69,15 +70,15 @@ class Sprite : public Actor SetState(0); } - std::string GetTexturePath() const; + [[nodiscard]] std::string GetTexturePath() const; void SetCustomTextureRect(const RectF& new_texcoord_frect); void SetCustomTextureCoords(float fTexCoords[8]); void SetCustomImageRect(RectF rectImageCoords); // in image pixel space void SetCustomImageCoords(float fImageCoords[8]); void SetCustomPosCoords(float fPosCoords[8]); - const RectF* GetCurrentTextureCoordRect() const; - const RectF* GetTextureCoordRectForState(int iState) const; + [[nodiscard]] const RectF* GetCurrentTextureCoordRect() const; + [[nodiscard]] const RectF* GetTextureCoordRectForState(int iState) const; void StopUsingCustomCoords(); void StopUsingCustomPosCoords(); void GetActiveTextureCoords(float fTexCoordsOut[8]) const; diff --git a/src/Etterna/Actor/Base/Tween.cpp b/src/Etterna/Actor/Base/Tween.cpp index b19a705ae6..2c4e55c049 100644 --- a/src/Etterna/Actor/Base/Tween.cpp +++ b/src/Etterna/Actor/Base/Tween.cpp @@ -15,26 +15,42 @@ LuaXType(TweenType); struct TweenLinear : public ITween { - float Tween(float f) const override { return f; } - ITween* Copy() const override { return new TweenLinear(*this); } + [[nodiscard]] float Tween(float f) const override { return f; } + [[nodiscard]] ITween* Copy() const override + { + return new TweenLinear(*this); + } }; struct TweenAccelerate : public ITween { - float Tween(float f) const override { return f * f; } - ITween* Copy() const override { return new TweenAccelerate(*this); } + [[nodiscard]] float Tween(float f) const override { return f * f; } + [[nodiscard]] ITween* Copy() const override + { + return new TweenAccelerate(*this); + } }; struct TweenDecelerate : public ITween { - float Tween(float f) const override { return 1 - (1 - f) * (1 - f); } - ITween* Copy() const override { return new TweenDecelerate(*this); } + [[nodiscard]] float Tween(float f) const override + { + return 1 - (1 - f) * (1 - f); + } + [[nodiscard]] ITween* Copy() const override + { + return new TweenDecelerate(*this); + } }; struct TweenSpring : public ITween { - float Tween(float f) const override + [[nodiscard]] float Tween(float f) const override { return 1 - RageFastCos(f * PI * 2.5f) / (1 + f * 3); } - ITween* Copy() const override { return new TweenSpring(*this); } + + [[nodiscard]] ITween* Copy() const override + { + return new TweenSpring(*this); + } }; /* @@ -42,8 +58,11 @@ struct TweenSpring : public ITween */ struct InterpolateBezier1D : public ITween { - float Tween(float f) const override; - ITween* Copy() const override { return new InterpolateBezier1D(*this); } + [[nodiscard]] float Tween(float f) const override; + [[nodiscard]] ITween* Copy() const override + { + return new InterpolateBezier1D(*this); + } RageQuadratic m_Bezier; }; @@ -59,8 +78,11 @@ InterpolateBezier1D::Tween(float f) const */ struct InterpolateBezier2D : public ITween { - float Tween(float f) const override; - ITween* Copy() const override { return new InterpolateBezier2D(*this); } + [[nodiscard]] float Tween(float f) const override; + [[nodiscard]] ITween* Copy() const override + { + return new InterpolateBezier2D(*this); + } RageBezier2D m_Bezier; }; @@ -98,19 +120,19 @@ ITween::CreateFromType(TweenType tt) ITween* ITween::CreateFromStack(Lua* L, int iStackPos) { - TweenType iType = Enum::Check(L, iStackPos); + const auto iType = Enum::Check(L, iStackPos); if (iType == TWEEN_BEZIER) { luaL_checktype(L, iStackPos + 1, LUA_TTABLE); - int iArgs = lua_objlen(L, iStackPos + 1); + const int iArgs = lua_objlen(L, iStackPos + 1); if (iArgs != 4 && iArgs != 8) { LuaHelpers::ReportScriptErrorFmt("Tween::CreateFromStack: table " "argument must have 4 or 8 " "entries"); - return NULL; + return nullptr; } float fC[8]; - for (int i = 0; i < iArgs; ++i) { + for (auto i = 0; i < iArgs; ++i) { lua_rawgeti(L, iStackPos + 1, i + 1); fC[i] = static_cast(lua_tonumber(L, -1)); } diff --git a/src/Etterna/Actor/Base/Tween.h b/src/Etterna/Actor/Base/Tween.h index 00d8dd09bf..175f9d490f 100644 --- a/src/Etterna/Actor/Base/Tween.h +++ b/src/Etterna/Actor/Base/Tween.h @@ -9,12 +9,12 @@ using Lua = lua_State; /** @brief The different tweening types available. */ enum TweenType { - TWEEN_LINEAR, /**< A linear tween. */ + TWEEN_LINEAR, /**< A linear tween. */ TWEEN_ACCELERATE, /**< An accelerating tween. */ TWEEN_DECELERATE, /**< A decelerating tween. */ - TWEEN_SPRING, /**< A spring tween. */ - TWEEN_BEZIER, /**< A bezier tween. */ - NUM_TweenType, /**< The number of tween types. */ + TWEEN_SPRING, /**< A spring tween. */ + TWEEN_BEZIER, /**< A bezier tween. */ + NUM_TweenType, /**< The number of tween types. */ TweenType_Invalid }; /** @brief A custom foreach loop iterating through the tween types. */ @@ -30,8 +30,8 @@ class ITween public: /** @brief Create the initial interface. */ virtual ~ITween() = default; - virtual float Tween(float f) const = 0; - virtual ITween* Copy() const = 0; + [[nodiscard]] virtual float Tween(float f) const = 0; + [[nodiscard]] virtual ITween* Copy() const = 0; static ITween* CreateFromType(TweenType iType); static ITween* CreateFromStack(Lua* L, int iStackPos); diff --git a/src/Etterna/Actor/Gameplay/ArrowEffects.cpp b/src/Etterna/Actor/Gameplay/ArrowEffects.cpp index f85282e0e1..276314d45c 100644 --- a/src/Etterna/Actor/Gameplay/ArrowEffects.cpp +++ b/src/Etterna/Actor/Gameplay/ArrowEffects.cpp @@ -136,7 +136,7 @@ void ArrowEffects::Update() { static float fLastTime = 0; - float fTime = RageTimer::GetTimeSinceStart(); + const float fTime = RageTimer::GetTimeSinceStart(); const Style* pStyle = GAMESTATE->GetCurrentStyle(PLAYER_1); const Style::ColumnInfo* pCols = pStyle->m_ColumnInfo; @@ -168,8 +168,8 @@ ArrowEffects::Update() * could possibly have tornado enabled. * let's also take default resolution (640x480) into mind. -aj */ - bool bWideField = pStyle->m_iColsPerPlayer > 4; - int iTornadoWidth = bWideField ? 2 : 3; + const bool bWideField = pStyle->m_iColsPerPlayer > 4; + const int iTornadoWidth = bWideField ? 2 : 3; int iStartCol = iColNum - iTornadoWidth; int iEndCol = iColNum + iTornadoWidth; @@ -258,7 +258,7 @@ ArrowEffects::Update() // Update Beat if (effects[PlayerOptions::EFFECT_BEAT] != 0) { do { - float fAccelTime = 0.2f, fTotalTime = 0.5f; + const float fAccelTime = 0.2f, fTotalTime = 0.5f; float fBeat = position.m_fSongBeatVisible + fAccelTime; const bool bEvenBeat = (static_cast(fBeat) % 2) != 0; @@ -304,15 +304,16 @@ GetDisplayedBeat(const PlayerState* pPlayerState, float beat) { // do a binary search here const vector& data = pPlayerState->m_CacheDisplayedBeat; - int max = data.size() - 1; + const int max = data.size() - 1; int l = 0, r = max; while (l <= r) { - int m = (l + r) / 2; + const int m = (l + r) / 2; if ((m == 0 || data[m].beat <= beat) && (m == max || beat < data[m + 1].beat)) { return data[m].displayedBeat + data[m].velocity * (beat - data[m].beat); - } else if (data[m].beat <= beat) { + } + if (data[m].beat <= beat) { l = m + 1; } else { r = m - 1; @@ -338,7 +339,7 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, float fYOffset = 0; const SongPosition& position = pPlayerState->GetDisplayedPosition(); - float fSongBeat = position.m_fSongBeatVisible; + const float fSongBeat = position.m_fSongBeatVisible; PlayerNumber pn = pPlayerState->m_PlayerNumber; Steps* pCurSteps = GAMESTATE->m_pCurSteps; @@ -354,13 +355,14 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, } if (curr_options->m_fTimeSpacing != 0.0f) { - float fSongSeconds = GAMESTATE->m_Position.m_fMusicSecondsVisible; - float fNoteSeconds = pCurSteps->GetTimingData()->WhereUAtBro(fNoteBeat); - float fSecondsUntilStep = fNoteSeconds - fSongSeconds; - float fBPM = curr_options->m_fScrollBPM; - float fBPS = + const float fSongSeconds = GAMESTATE->m_Position.m_fMusicSecondsVisible; + const float fNoteSeconds = + pCurSteps->GetTimingData()->WhereUAtBro(fNoteBeat); + const float fSecondsUntilStep = fNoteSeconds - fSongSeconds; + const float fBPM = curr_options->m_fScrollBPM; + const float fBPS = fBPM / 60.f / GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; - float fYOffsetTimeSpacing = fSecondsUntilStep * fBPS; + const float fYOffsetTimeSpacing = fSecondsUntilStep * fBPS; fYOffset += fYOffsetTimeSpacing * curr_options->m_fTimeSpacing; } @@ -386,8 +388,8 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, float fYAdjust = 0; // fill this in depending on PlayerOptions if (fAccels[PlayerOptions::ACCEL_BOOST] != 0) { - float fEffectHeight = GetNoteFieldHeight(); - float fNewYOffset = + const float fEffectHeight = GetNoteFieldHeight(); + const float fNewYOffset = fYOffset * 1.5f / ((fYOffset + fEffectHeight / 1.2f) / fEffectHeight); float fAccelYAdjust = fAccels[PlayerOptions::ACCEL_BOOST] * (fNewYOffset - fYOffset); @@ -397,9 +399,9 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, fYAdjust += fAccelYAdjust; } if (fAccels[PlayerOptions::ACCEL_BRAKE] != 0) { - float fEffectHeight = GetNoteFieldHeight(); - float fScale = SCALE(fYOffset, 0.f, fEffectHeight, 0, 1.f); - float fNewYOffset = fYOffset * fScale; + const float fEffectHeight = GetNoteFieldHeight(); + const float fScale = SCALE(fYOffset, 0.f, fEffectHeight, 0, 1.f); + const float fNewYOffset = fYOffset * fScale; float fBrakeYAdjust = fAccels[PlayerOptions::ACCEL_BRAKE] * (fNewYOffset - fYOffset); // TRICKY: Clamp this value the same way as BOOST so that in @@ -415,7 +417,7 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, // Factor in boomerang if (fAccels[PlayerOptions::ACCEL_BOOMERANG] != 0) { - float fPeakAtYOffset = + const float fPeakAtYOffset = SCREEN_HEIGHT * BOOMERANG_PEAK_PERCENTAGE; // zero point of boomerang function fPeakYOffsetOut = @@ -433,7 +435,7 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, for (int i = 0; i < 3; ++i) seed = ((seed * 1664525u) + 1013904223u) & 0xFFFFFFFF; - float fRandom = seed / 4294967296.0f; + const float fRandom = seed / 4294967296.0f; /* Random speed always increases speed: a random speed of 10 indicates * [1,11]. This keeps it consistent with other mods: 0 means no effect. @@ -446,7 +448,7 @@ ArrowEffects::GetYOffset(const PlayerState* pPlayerState, // TODO: Don't index by PlayerNumber. PerPlayerData& data = g_EffectData; - float fExpandMultiplier = SCALE( + const float fExpandMultiplier = SCALE( RageFastCos(data.m_fExpandSeconds * EXPAND_MULTIPLIER_FREQUENCY), EXPAND_MULTIPLIER_SCALE_FROM_LOW, EXPAND_MULTIPLIER_SCALE_FROM_HIGH, @@ -472,20 +474,22 @@ ArrowGetReverseShiftAndScale(int iCol, float& fScaleOut) { // XXX: Hack: we need to scale the reverse shift by the zoom. - float fMiniPercent = curr_options->m_fEffects[PlayerOptions::EFFECT_MINI]; + const float fMiniPercent = + curr_options->m_fEffects[PlayerOptions::EFFECT_MINI]; float fZoom = 1 - fMiniPercent * 0.5f; // don't divide by 0 if (fabsf(fZoom) < 0.01) fZoom = 0.01f; - float fPercentReverse = curr_options->GetReversePercentForColumn(iCol); + const float fPercentReverse = + curr_options->GetReversePercentForColumn(iCol); fShiftOut = SCALE(fPercentReverse, 0.f, 1.f, -fYReverseOffsetPixels / fZoom / 2, fYReverseOffsetPixels / fZoom / 2); - float fPercentCentered = + const float fPercentCentered = curr_options->m_fScrolls[PlayerOptions::SCROLL_CENTERED]; fShiftOut = SCALE(fPercentCentered, 0.f, 1.f, fShiftOut, 0.0f); @@ -834,7 +838,7 @@ ArrowEffects::GetAlpha(int iCol, float fFadeInPercentOfDrawFar) { // Get the YPos without reverse (that is, factor in EFFECT_TIPSY). - float fYPosWithoutReverse = + const float fYPosWithoutReverse = ArrowEffects::GetYPos(iCol, fYOffset, fYReverseOffsetPixels, false); float fPercentVisible = ArrowGetPercentVisible(fYPosWithoutReverse); @@ -842,14 +846,14 @@ ArrowEffects::GetAlpha(int iCol, if (fPercentFadeToFail != -1) fPercentVisible = 1 - fPercentFadeToFail; - float fFullAlphaY = + const float fFullAlphaY = fDrawDistanceBeforeTargetsPixels * (1 - fFadeInPercentOfDrawFar); if (fYPosWithoutReverse > fFullAlphaY) { - float f = SCALE(fYPosWithoutReverse, - fFullAlphaY, - fDrawDistanceBeforeTargetsPixels, - 1.0f, - 0.0f); + const float f = SCALE(fYPosWithoutReverse, + fFullAlphaY, + fDrawDistanceBeforeTargetsPixels, + 1.0f, + 0.0f); return f; } return fPercentVisible; @@ -864,7 +868,7 @@ ArrowEffects::GetGlow(int iCol, float fFadeInPercentOfDrawFar) { // Get the YPos without reverse (that is, factor in EFFECT_TIPSY). - float fYPosWithoutReverse = + const float fYPosWithoutReverse = ArrowEffects::GetYPos(iCol, fYOffset, fYReverseOffsetPixels, false); float fPercentVisible = ArrowGetPercentVisible(fYPosWithoutReverse); @@ -876,16 +880,15 @@ ArrowEffects::GetGlow(int iCol, if (!PREFSMAN->m_bNoGlow) { return SCALE(fDistFromHalf, 0, 0.5f, 1.3f, 0); - } else { - return 0; } + return 0; } float ArrowEffects::GetBrightness(const PlayerState* pPlayerState, float fNoteBeat) { - float fSongBeat = pPlayerState->m_Position.m_fSongBeatVisible; - float fBeatsUntilStep = fNoteBeat - fSongBeat; + const float fSongBeat = pPlayerState->m_Position.m_fSongBeatVisible; + const float fBeatsUntilStep = fNoteBeat - fSongBeat; float fBrightness = SCALE(fBeatsUntilStep, 0, -1, 1.f, 0.f); CLAMP(fBrightness, 0, 1); @@ -959,15 +962,15 @@ ArrowEffects::GetFrameWidthScale(const PlayerState* pPlayerState, { float fFrameWidthMultiplier = 1.0f; - float fPixelsPerSecond = FRAME_WIDTH_EFFECTS_PIXELS_PER_SECOND; - float fSecond = fYOffset / fPixelsPerSecond; + const float fPixelsPerSecond = FRAME_WIDTH_EFFECTS_PIXELS_PER_SECOND; + const float fSecond = fYOffset / fPixelsPerSecond; float fWidthEffect = pPlayerState->m_EffectHistory.GetSample(fSecond); if (fWidthEffect != 0 && FRAME_WIDTH_LOCK_EFFECTS_TO_OVERLAPPING) { // Don't display effect data that happened before this hold overlapped // the top. - float fFromEndOfOverlapped = fOverlappedTime - fSecond; - float fTrailingPixels = FRAME_WIDTH_LOCK_EFFECTS_TWEEN_PIXELS; - float fTrailingSeconds = fTrailingPixels / fPixelsPerSecond; + const float fFromEndOfOverlapped = fOverlappedTime - fSecond; + const float fTrailingPixels = FRAME_WIDTH_LOCK_EFFECTS_TWEEN_PIXELS; + const float fTrailingSeconds = fTrailingPixels / fPixelsPerSecond; float fScaleEffect = SCALE(fFromEndOfOverlapped, 0.0f, fTrailingSeconds, 0.0f, 1.0f); CLAMP(fScaleEffect, 0.0f, 1.0f); @@ -1040,7 +1043,7 @@ int GetYPos(lua_State* L) { PlayerState* ps = Luna::check(L, 1); - float fYReverseOffsetPixels = YReverseOffset(L, 4); + const float fYReverseOffsetPixels = YReverseOffset(L, 4); ArrowEffects::SetCurrentOptions(&ps->m_PlayerOptions.GetCurrent()); lua_pushnumber( L, ArrowEffects::GetYPos(IArg(2) - 1, FArg(3), fYReverseOffsetPixels)); @@ -1053,7 +1056,7 @@ GetYOffsetFromYPos(lua_State* L) { PlayerState* ps = Luna::check(L, 1); ArrowEffects::SetCurrentOptions(&ps->m_PlayerOptions.GetCurrent()); - float fYReverseOffsetPixels = YReverseOffset(L, 4); + const float fYReverseOffsetPixels = YReverseOffset(L, 4); lua_pushnumber(L, ArrowEffects::GetYOffsetFromYPos( IArg(2) - 1, FArg(3), fYReverseOffsetPixels)); @@ -1135,7 +1138,7 @@ GetAlpha(lua_State* L) ArrowEffects::SetCurrentOptions(&ps->m_PlayerOptions.GetCurrent()); // Provide reasonable default values. float fPercentFadeToFail = -1; - float fYReverseOffsetPixels = YReverseOffset(L, 5); + const float fYReverseOffsetPixels = YReverseOffset(L, 5); float fDrawDistanceBeforeTargetsPixels = DRAW_DISTANCE_BEFORE_TARGET_PIXELS; float fFadeInPercentOfDrawFar = FADE_BEFORE_TARGETS_PERCENT; if (lua_gettop(L) >= 4 && !lua_isnil(L, 4)) { @@ -1167,7 +1170,7 @@ GetGlow(lua_State* L) ArrowEffects::SetCurrentOptions(&ps->m_PlayerOptions.GetCurrent()); // Provide reasonable default values. float fPercentFadeToFail = -1; // - float fYReverseOffsetPixels = YReverseOffset(L, 5); + const float fYReverseOffsetPixels = YReverseOffset(L, 5); float fDrawDistanceBeforeTargetsPixels = DRAW_DISTANCE_BEFORE_TARGET_PIXELS; float fFadeInPercentOfDrawFar = FADE_BEFORE_TARGETS_PERCENT; if (lua_gettop(L) >= 4 && !lua_isnil(L, 4)) { diff --git a/src/Etterna/Actor/Gameplay/Background.cpp b/src/Etterna/Actor/Gameplay/Background.cpp index 0136fdf19c..17f1f6acdd 100644 --- a/src/Etterna/Actor/Gameplay/Background.cpp +++ b/src/Etterna/Actor/Gameplay/Background.cpp @@ -18,10 +18,11 @@ #include "Etterna/Models/Misc/ThemeMetric.h" #include "Etterna/FileTypes/XmlFile.h" #include "Etterna/FileTypes/XmlFileUtil.h" -#include #include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Songs/SongOptions.h" +#include + static ThemeMetric LEFT_EDGE("Background", "LeftEdge"); static ThemeMetric TOP_EDGE("Background", "TopEdge"); static ThemeMetric RIGHT_EDGE("Background", "RightEdge"); @@ -153,8 +154,8 @@ class BackgroundImpl : public ActorFrame static RageColor GetBrightnessColor(float fBrightnessPercent) { - RageColor cBrightness = RageColor(0, 0, 0, 1 - fBrightnessPercent); - RageColor cClamp = RageColor(0.5f, 0.5f, 0.5f, CLAMP_OUTPUT_PERCENT); + auto cBrightness = RageColor(0, 0, 0, 1 - fBrightnessPercent); + const auto cClamp = RageColor(0.5f, 0.5f, 0.5f, CLAMP_OUTPUT_PERCENT); // blend the two colors above as if cBrightness is drawn, then cClamp drawn // on top @@ -203,16 +204,16 @@ BackgroundImpl::Init() vector vsPaths, vsNames; BackgroundUtil::GetBackgroundTransitions("", vsPaths, vsNames); for (unsigned i = 0; i < vsPaths.size(); i++) { - const std::string& sPath = vsPaths[i]; - const std::string& sName = vsNames[i]; + const auto& sPath = vsPaths[i]; + const auto& sName = vsNames[i]; XNode xml; XmlFileUtil::LoadFromFileShowErrors(xml, sPath); ASSERT(xml.GetName() == "BackgroundTransition"); - BackgroundTransition& bgt = m_mapNameToTransition[sName]; + auto& bgt = m_mapNameToTransition[sName]; std::string sCmdLeaves; - bool bSuccess = xml.GetAttrValue("LeavesCommand", sCmdLeaves); + auto bSuccess = xml.GetAttrValue("LeavesCommand", sCmdLeaves); ASSERT(bSuccess); bgt.cmdLeaves = ActorUtil::ParseActorCommands(sCmdLeaves); @@ -223,7 +224,7 @@ BackgroundImpl::Init() } } - RageColor c = GetBrightnessColor(0); + const auto c = GetBrightnessColor(0); m_quadBorderLeft.StretchTo( RectF(SCREEN_LEFT, SCREEN_TOP, LEFT_EDGE, SCREEN_BOTTOM)); @@ -291,13 +292,12 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, vsResolvedRef.resize(vsToResolve.size()); for (unsigned i = 0; i < vsToResolve.size(); i++) { - const std::string& sToResolve = vsToResolve[i]; + const auto& sToResolve = vsToResolve[i]; if (sToResolve.empty()) { if (i == 0) return false; - else - continue; + continue; } /* Look for vsFileToResolve[i] in: @@ -326,7 +326,7 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, BackgroundUtil::GetGlobalBGAnimations( pSong, sToResolve, vsPaths, vsThrowAway); - std::string& sResolved = vsResolved[i]; + auto& sResolved = vsResolved[i]; if (!vsPaths.empty()) { sResolved = vsPaths[0]; @@ -334,8 +334,7 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, // If the main background file is missing, we failed. if (i == 0) return false; - else - sResolved = "../" + ThemeManager::GetBlankGraphicPath(); + sResolved = "../" + ThemeManager::GetBlankGraphicPath(); } ASSERT(!sResolved.empty()); @@ -344,9 +343,9 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, new LuaThreadVariable(ssprintf("File%d", i + 1), sResolved); } - std::string sEffect = bd.m_sEffect; + auto sEffect = bd.m_sEffect; if (sEffect.empty()) { - FileType ft = ActorUtil::GetFileType(vsResolved[0]); + const auto ft = ActorUtil::GetFileType(vsResolved[0]); switch (ft) { default: LuaHelpers::ReportScriptErrorFmt( @@ -383,7 +382,7 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, // Resolve the effect file. std::string sEffectFile; - for (int i = 0; i < 2; i++) { + for (auto i = 0; i < 2; i++) { vector vsPaths, vsThrowAway; BackgroundUtil::GetBackgroundEffects(sEffect, vsPaths, vsThrowAway); if (vsPaths.empty()) { @@ -402,7 +401,7 @@ BackgroundImpl::Layer::CreateBackground(const Song* pSong, } ASSERT(!sEffectFile.empty()); - Actor* pActor = ActorUtil::MakeActor(sEffectFile); + auto* pActor = ActorUtil::MakeActor(sEffectFile); if (pActor == nullptr) pActor = new Actor; @@ -433,18 +432,19 @@ BackgroundImpl::Layer::CreateRandomBGA(const Song* pSong, /* XXX: every time we fully loop, shuffle, so we don't play the same * sequence over and over; and nudge the shuffle so the next one won't be a * repeat */ - BackgroundDef bd = RandomBGAnimations.front(); + auto bd = RandomBGAnimations.front(); RandomBGAnimations.push_back(RandomBGAnimations.front()); RandomBGAnimations.pop_front(); if (!sEffect.empty()) bd.m_sEffect = sEffect; - map::const_iterator iter = m_BGAnimations.find(bd); + const map::const_iterator iter = + m_BGAnimations.find(bd); // create the background if it's not already created if (iter == m_BGAnimations.end()) { - bool bSuccess = CreateBackground(pSong, bd, pParent); + const auto bSuccess = CreateBackground(pSong, bd, pParent); ASSERT(bSuccess); // we fed it valid files, so this shouldn't fail } return bd; @@ -455,30 +455,29 @@ BackgroundImpl::LoadFromRandom(float fFirstBeat, float fEndBeat, const BackgroundChange& change) { - int iStartRow = BeatToNoteRow(fFirstBeat); - int iEndRow = BeatToNoteRow(fEndBeat); + auto iStartRow = BeatToNoteRow(fFirstBeat); + auto iEndRow = BeatToNoteRow(fEndBeat); - const TimingData& timing = m_pSong->m_SongTiming; + const auto& timing = m_pSong->m_SongTiming; // change BG every time signature change or 4 measures - const vector& tSigs = - timing.GetTimingSegments(SEGMENT_TIME_SIG); + const auto& tSigs = timing.GetTimingSegments(SEGMENT_TIME_SIG); for (unsigned i = 0; i < tSigs.size(); i++) { - TimeSignatureSegment* ts = static_cast(tSigs[i]); - int iSegmentEndRow = + auto* ts = static_cast(tSigs[i]); + auto iSegmentEndRow = (i + 1 == tSigs.size()) ? iEndRow : tSigs[i + 1]->GetRow(); - int time_signature_start = max(ts->GetRow(), iStartRow); - for (int j = time_signature_start; j < min(iEndRow, iSegmentEndRow); + auto time_signature_start = max(ts->GetRow(), iStartRow); + for (auto j = time_signature_start; j < min(iEndRow, iSegmentEndRow); j += static_cast(RAND_BG_CHANGE_MEASURES * ts->GetNoteRowsPerMeasure())) { // Don't fade. It causes frame rate dip, especially on slower // machines. - BackgroundDef bd = m_Layer[0].CreateRandomBGA( + auto bd = m_Layer[0].CreateRandomBGA( m_pSong, change.m_def.m_sEffect, m_RandomBGAnimations, this); if (!bd.IsEmpty()) { - BackgroundChange c = change; + auto c = change; c.m_def = bd; if (j == time_signature_start && i == 0) { c.m_fStartBeat = RAND_BG_START_BEAT; @@ -492,13 +491,11 @@ BackgroundImpl::LoadFromRandom(float fFirstBeat, if (RAND_BG_CHANGES_WHEN_BPM_CHANGES) { // change BG every BPM change that is at the beginning of a measure - const vector& bpms = - timing.GetTimingSegments(SEGMENT_BPM); - for (auto bpm : bpms) { - bool bAtBeginningOfMeasure = false; - for (auto tSig : tSigs) { - TimeSignatureSegment* ts = - static_cast(tSig); + const auto& bpms = timing.GetTimingSegments(SEGMENT_BPM); + for (auto* bpm : bpms) { + auto bAtBeginningOfMeasure = false; + for (auto* tSig : tSigs) { + auto* ts = static_cast(tSig); if ((bpm->GetRow() - ts->GetRow()) % ts->GetNoteRowsPerMeasure() == 0) { @@ -511,15 +508,15 @@ BackgroundImpl::LoadFromRandom(float fFirstBeat, continue; // skip // start so that we don't create a BGChange right on top of fEndBeat - bool bInRange = + auto bInRange = bpm->GetRow() >= iStartRow && bpm->GetRow() < iEndRow; if (!bInRange) continue; // skip - BackgroundDef bd = m_Layer[0].CreateRandomBGA( + auto bd = m_Layer[0].CreateRandomBGA( m_pSong, change.m_def.m_sEffect, m_RandomBGAnimations, this); if (!bd.IsEmpty()) { - BackgroundChange c = change; + auto c = change; c.m_def.m_sFile1 = bd.m_sFile1; c.m_def.m_sFile2 = bd.m_sFile2; c.m_fStartBeat = bpm->GetBeat(); @@ -560,8 +557,8 @@ BackgroundImpl::LoadFromSong(const Song* pSong) // Pick the same random items every time the song is played. RandomGen rnd(GetHashForString(pSong->GetSongDir())); std::shuffle(vsNames.begin(), vsNames.end(), rnd); - int iSize = min(static_cast(g_iNumBackgrounds), - static_cast(vsNames.size())); + auto iSize = min(static_cast(g_iNumBackgrounds), + static_cast(vsNames.size())); vsNames.resize(iSize); for (auto& s : vsNames) { @@ -573,7 +570,7 @@ BackgroundImpl::LoadFromSong(const Song* pSong) /* Song backgrounds (even just background stills) can get very big; never * keep them in memory. */ - RageTextureID::TexPolicy OldPolicy = TEXTUREMAN->GetDefaultTexturePolicy(); + auto OldPolicy = TEXTUREMAN->GetDefaultTexturePolicy(); TEXTUREMAN->SetDefaultTexturePolicy(RageTextureID::TEX_VOLATILE); TEXTUREMAN->DisableOddDimensionWarning(); @@ -594,21 +591,20 @@ BackgroundImpl::LoadFromSong(const Song* pSong) !GAMESTATE->m_SongOptions.GetCurrent().m_bRandomBGOnly) { FOREACH_BackgroundLayer(i) { - Layer& layer = m_Layer[i]; + auto& layer = m_Layer[i]; // Load all song-specified backgrounds FOREACH_CONST(BackgroundChange, pSong->GetBackgroundChanges(i), bgc) { - BackgroundChange change = *bgc; - BackgroundDef& bd = change.m_def; + auto change = *bgc; + auto& bd = change.m_def; - bool bIsAlreadyLoaded = + auto bIsAlreadyLoaded = layer.m_BGAnimations.find(bd) != layer.m_BGAnimations.end(); if (bd.m_sFile1 != RANDOM_BACKGROUND_FILE && !bIsAlreadyLoaded) { if (layer.CreateBackground(m_pSong, bd, this)) { - ; // do nothing. Create was successful. } else { if (i == BACKGROUND_LAYER_1) { // The background was not found. Try to use a random @@ -629,9 +625,9 @@ BackgroundImpl::LoadFromSong(const Song* pSong) } } else // pSong doesn't have an animation plan { - Layer& layer = m_Layer[0]; - float firstBeat = pSong->GetFirstBeat(); - float lastBeat = pSong->GetLastBeat(); + auto& layer = m_Layer[0]; + auto firstBeat = pSong->GetFirstBeat(); + auto lastBeat = pSong->GetLastBeat(); LoadFromRandom(firstBeat, lastBeat, BackgroundChange()); @@ -647,11 +643,11 @@ BackgroundImpl::LoadFromSong(const Song* pSong) // sort segments FOREACH_BackgroundLayer(i) { - Layer& layer = m_Layer[i]; + auto& layer = m_Layer[i]; BackgroundUtil::SortBackgroundChangesArray(layer.m_aBGChanges); } - Layer& mainlayer = m_Layer[0]; + auto& mainlayer = m_Layer[0]; BackgroundChange change; change.m_def = m_StaticBackgroundDef; @@ -659,13 +655,13 @@ BackgroundImpl::LoadFromSong(const Song* pSong) mainlayer.m_aBGChanges.insert(mainlayer.m_aBGChanges.begin(), change); // If any BGChanges use the background image, load it. - bool bStaticBackgroundUsed = false; + auto bStaticBackgroundUsed = false; FOREACH_BackgroundLayer(i) { - Layer& layer = m_Layer[i]; + auto& layer = m_Layer[i]; FOREACH_CONST(BackgroundChange, layer.m_aBGChanges, bgc) { - const BackgroundDef& bd = bgc->m_def; + const auto& bd = bgc->m_def; if (bd == m_StaticBackgroundDef) { bStaticBackgroundUsed = true; break; @@ -676,11 +672,11 @@ BackgroundImpl::LoadFromSong(const Song* pSong) } if (bStaticBackgroundUsed) { - bool bIsAlreadyLoaded = + auto bIsAlreadyLoaded = mainlayer.m_BGAnimations.find(m_StaticBackgroundDef) != mainlayer.m_BGAnimations.end(); if (!bIsAlreadyLoaded) { - bool bSuccess = + auto bSuccess = mainlayer.CreateBackground(m_pSong, m_StaticBackgroundDef, this); ASSERT(bSuccess); } @@ -689,12 +685,12 @@ BackgroundImpl::LoadFromSong(const Song* pSong) // Look for the random file marker, and replace the segment with // LoadFromRandom. for (unsigned i = 0; i < mainlayer.m_aBGChanges.size(); i++) { - const BackgroundChange change = mainlayer.m_aBGChanges[i]; + const auto change = mainlayer.m_aBGChanges[i]; if (change.m_def.m_sFile1 != RANDOM_BACKGROUND_FILE) continue; - float fStartBeat = change.m_fStartBeat; - float fEndBeat = pSong->GetLastBeat(); + auto fStartBeat = change.m_fStartBeat; + auto fEndBeat = pSong->GetLastBeat(); if (i + 1 < mainlayer.m_aBGChanges.size()) fEndBeat = mainlayer.m_aBGChanges[i + 1].m_fStartBeat; @@ -754,33 +750,32 @@ BackgroundImpl::Layer::UpdateCurBGChange( // Calls to Update() should *not* be scaled by music rate; fCurrentTime is. // Undo it. - const float fRate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; + const auto fRate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; // Find the BGSegment we're in - const int i = FindBGSegmentForBeat(beat_info.beat); + const auto i = FindBGSegmentForBeat(beat_info.beat); - float fDeltaTime = fCurrentTime - fLastMusicSeconds; + auto fDeltaTime = fCurrentTime - fLastMusicSeconds; if (i != -1 && i != m_iCurBGChangeIndex) // we're changing backgrounds { // LOG->Trace( "old bga %d -> new bga %d (%s), %f, %f", // m_iCurBGChangeIndex, i, m_aBGChanges[i].GetTextDescription().c_str(), // m_aBGChanges[i].m_fStartBeat, fBeat ); - BackgroundChange oldChange; if (m_iCurBGChangeIndex != -1) - oldChange = m_aBGChanges[m_iCurBGChangeIndex]; + BackgroundChange oldChange = m_aBGChanges[m_iCurBGChangeIndex]; m_iCurBGChangeIndex = i; - const BackgroundChange& change = m_aBGChanges[i]; + const auto& change = m_aBGChanges[i]; m_pFadingBGA = m_pCurrentBGA; - map::const_iterator iter = + const map::const_iterator iter = m_BGAnimations.find(change.m_def); if (iter == m_BGAnimations.end()) { - XNode* pNode = change.m_def.CreateNode(); - std::string xml = XmlFileUtil::GetXML(pNode); + auto* pNode = change.m_def.CreateNode(); + auto xml = XmlFileUtil::GetXML(pNode); Trim(xml); LuaHelpers::ReportScriptErrorFmt( "Tried to switch to a background that was never loaded:\n%s", @@ -799,15 +794,15 @@ BackgroundImpl::Layer::UpdateCurBGChange( m_pFadingBGA->PlayCommand("LoseFocus"); if (!change.m_sTransition.empty()) { - map::const_iterator - lIter = mapNameToTransition.find(change.m_sTransition); + const auto lIter = + mapNameToTransition.find(change.m_sTransition); if (lIter == mapNameToTransition.end()) { LuaHelpers::ReportScriptErrorFmt( "'%s' is not the name of a BackgroundTransition " "file.", change.m_sTransition.c_str()); } else { - const BackgroundTransition& bt = lIter->second; + const auto& bt = lIter->second; m_pFadingBGA->RunCommandsOnLeaves(*bt.cmdLeaves); m_pFadingBGA->RunCommands(*bt.cmdRoot); } @@ -823,7 +818,7 @@ BackgroundImpl::Layer::UpdateCurBGChange( /* How much time of this BGA have we skipped? (This happens with * SetSeconds.) */ - const float fStartSecond = + const auto fStartSecond = pSong->m_SongTiming.WhereUAtBro(change.m_fStartBeat); /* This is affected by the music rate. */ @@ -836,7 +831,7 @@ BackgroundImpl::Layer::UpdateCurBGChange( } /* This is unaffected by the music rate. */ - float fDeltaTimeNoMusicRate = max(fDeltaTime / fRate, 0); + const auto fDeltaTimeNoMusicRate = max(fDeltaTime / fRate, 0); if (m_pCurrentBGA != nullptr) m_pCurrentBGA->Update(fDeltaTimeNoMusicRate); @@ -850,7 +845,7 @@ BackgroundImpl::Update(float fDeltaTime) ActorFrame::Update(fDeltaTime); { - bool bVisible = IsDangerAllVisible(); + const auto bVisible = IsDangerAllVisible(); if (m_bDangerAllWasVisible != bVisible) MESSAGEMAN->Broadcast(bVisible ? "ShowDangerAll" : "HideDangerAll"); m_bDangerAllWasVisible = bVisible; @@ -858,7 +853,7 @@ BackgroundImpl::Update(float fDeltaTime) FOREACH_BackgroundLayer(i) { - Layer& layer = m_Layer[i]; + auto& layer = m_Layer[i]; layer.UpdateCurBGChange(m_pSong, m_fLastMusicSeconds, GAMESTATE->m_Position.m_fMusicSeconds, @@ -876,7 +871,7 @@ BackgroundImpl::DrawPrimitives() { FOREACH_BackgroundLayer(i) { - Layer& layer = m_Layer[i]; + auto& layer = m_Layer[i]; if (layer.m_pCurrentBGA != nullptr) layer.m_pCurrentBGA->Draw(); if (layer.m_pFadingBGA != nullptr) @@ -914,7 +909,7 @@ BackgroundImpl::IsDangerAllVisible() BrightnessOverlay::BrightnessOverlay() { - float fQuadWidth = (RIGHT_EDGE - LEFT_EDGE); + const auto fQuadWidth = (RIGHT_EDGE - LEFT_EDGE); m_quadBGBrightness.StretchTo( RectF(LEFT_EDGE, TOP_EDGE, LEFT_EDGE + fQuadWidth, BOTTOM_EDGE)); @@ -945,12 +940,12 @@ BrightnessOverlay::Update(float fDeltaTime) void BrightnessOverlay::SetActualBrightness() { - float fLeftBrightness = + auto fLeftBrightness = 1 - GAMESTATE->m_pPlayerState->m_PlayerOptions.GetCurrent().m_fCover; - float fRightBrightness = + auto fRightBrightness = 1 - GAMESTATE->m_pPlayerState->m_PlayerOptions.GetCurrent().m_fCover; - float fBaseBGBrightness = g_fBGBrightness; + const float fBaseBGBrightness = g_fBGBrightness; // Revision: Themes that implement a training mode should handle the // brightness for it. The engine should not force the brightness for @@ -967,8 +962,8 @@ BrightnessOverlay::SetActualBrightness() if (!GAMESTATE->IsHumanPlayer(PLAYER_1)) fLeftBrightness = fRightBrightness; - RageColor LeftColor = GetBrightnessColor(fLeftBrightness); - RageColor RightColor = GetBrightnessColor(fRightBrightness); + const auto LeftColor = GetBrightnessColor(fLeftBrightness); + const auto RightColor = GetBrightnessColor(fRightBrightness); m_quadBGBrightness.SetDiffuse(LeftColor); m_quadBGBrightnessFade.SetDiffuseLeftEdge(LeftColor); @@ -978,7 +973,7 @@ BrightnessOverlay::SetActualBrightness() void BrightnessOverlay::Set(float fBrightness) { - RageColor c = GetBrightnessColor(fBrightness); + const auto c = GetBrightnessColor(fBrightness); m_quadBGBrightness.SetDiffuse(c); m_quadBGBrightnessFade.SetDiffuse(c); diff --git a/src/Etterna/Actor/Gameplay/Foreground.cpp b/src/Etterna/Actor/Gameplay/Foreground.cpp index a099b9f7bc..48be6f199e 100644 --- a/src/Etterna/Actor/Gameplay/Foreground.cpp +++ b/src/Etterna/Actor/Gameplay/Foreground.cpp @@ -1,7 +1,6 @@ #include "Etterna/Globals/global.h" #include "Etterna/Actor/Base/ActorUtil.h" #include "Etterna/Models/Misc/BackgroundUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Foreground.h" #include "Etterna/Singletons/GameState.h" #include "RageUtil/Graphics/RageTextureManager.h" @@ -17,33 +16,32 @@ Foreground::~Foreground() void Foreground::Unload() { - for (unsigned i = 0; i < m_BGAnimations.size(); ++i) - delete m_BGAnimations[i].m_bga; + for (auto& m_BGAnimation : m_BGAnimations) + delete m_BGAnimation.m_bga; m_BGAnimations.clear(); m_SubActors.clear(); m_fLastMusicSeconds = -9999; - m_pSong = NULL; + m_pSong = nullptr; } void Foreground::LoadFromSong(const Song* pSong) { // Song graphics can get very big; never keep them in memory. - RageTextureID::TexPolicy OldPolicy = TEXTUREMAN->GetDefaultTexturePolicy(); + const auto OldPolicy = TEXTUREMAN->GetDefaultTexturePolicy(); TEXTUREMAN->SetDefaultTexturePolicy(RageTextureID::TEX_VOLATILE); m_pSong = pSong; - FOREACH_CONST(BackgroundChange, pSong->GetForegroundChanges(), bgc) - { - const BackgroundChange& change = *bgc; - std::string sBGName = change.m_def.m_sFile1, - sLuaFile = pSong->GetSongDir() + sBGName + "/default.lua", - sXmlFile = pSong->GetSongDir() + sBGName + "/default.xml"; + for (const auto& bgc : pSong->GetForegroundChanges()) { + const auto& change = bgc; + auto sBGName = change.m_def.m_sFile1, + sLuaFile = pSong->GetSongDir() + sBGName + "/default.lua", + sXmlFile = pSong->GetSongDir() + sBGName + "/default.xml"; LoadedBGA bga; if (DoesFileExist(sLuaFile)) { LOG->Warn("Mod map detected, invalidating sequential assumption."); - TimingData* td = GAMESTATE->m_pCurSteps->GetTimingData(); + auto* td = GAMESTATE->m_pCurSteps->GetTimingData(); td->InvalidateSequentialAssmption(); bga.m_bga = ActorUtil::MakeActor(sLuaFile, this); @@ -51,7 +49,7 @@ Foreground::LoadFromSong(const Song* pSong) bga.m_bga = ActorUtil::MakeActor(pSong->GetSongDir() + sBGName, this); } - if (bga.m_bga == NULL) + if (bga.m_bga == nullptr) continue; bga.m_bga->SetName(sBGName); // ActorUtil::MakeActor calls LoadFromNode to load the actor, and @@ -75,11 +73,9 @@ void Foreground::Update(float fDeltaTime) { // Calls to Update() should *not* be scaled by music rate. Undo it. - const float fRate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; - - for (unsigned i = 0; i < m_BGAnimations.size(); ++i) { - LoadedBGA& bga = m_BGAnimations[i]; + const auto fRate = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; + for (auto& bga : m_BGAnimations) { if (GAMESTATE->m_Position.m_fSongBeat < bga.m_fStartBeat) { // The animation hasn't started yet. continue; @@ -95,9 +91,9 @@ Foreground::Update(float fDeltaTime) bga.m_bga->SetVisible(true); bga.m_bga->PlayCommand("On"); - const float fStartSecond = + const auto fStartSecond = m_pSong->m_SongTiming.WhereUAtBro(bga.m_fStartBeat); - const float fStopSecond = + const auto fStopSecond = fStartSecond + bga.m_bga->GetTweenTimeLeft(); bga.m_fStopBeat = m_pSong->m_SongTiming.GetBeatFromElapsedTime(fStopSecond); @@ -117,7 +113,6 @@ Foreground::Update(float fDeltaTime) // Finished. bga.m_bga->SetVisible(false); bga.m_bFinished = true; - continue; } } diff --git a/src/Etterna/Actor/Gameplay/GhostArrowRow.cpp b/src/Etterna/Actor/Gameplay/GhostArrowRow.cpp index fd8cff4f4f..3f2e096038 100644 --- a/src/Etterna/Actor/Gameplay/GhostArrowRow.cpp +++ b/src/Etterna/Actor/Gameplay/GhostArrowRow.cpp @@ -47,8 +47,8 @@ GhostArrowRow::SetColumnRenderers(vector& renderers) GhostArrowRow::~GhostArrowRow() { - for (unsigned i = 0; i < m_Ghost.size(); ++i) - delete m_Ghost[i]; + for (auto& i : m_Ghost) + delete i; } void diff --git a/src/Etterna/Actor/Gameplay/LifeMeterBar.cpp b/src/Etterna/Actor/Gameplay/LifeMeterBar.cpp index a021645faf..91328b7e8a 100644 --- a/src/Etterna/Actor/Gameplay/LifeMeterBar.cpp +++ b/src/Etterna/Actor/Gameplay/LifeMeterBar.cpp @@ -19,7 +19,7 @@ LIFE_PERCENT_CHANGE_NAME(size_t i) float LifeMeterBar::MapTNSToDeltaLife(TapNoteScore score) { - float fDeltaLife = 0.f; + auto fDeltaLife = 0.f; switch (score) { DEFAULT_FAIL(score); @@ -67,7 +67,7 @@ LifeMeterBar::MapTNSToDeltaLife(TapNoteScore score) float LifeMeterBar::MapHNSToDeltaLife(HoldNoteScore score) { - float fDeltaLife = 0.f; + auto fDeltaLife = 0.f; switch (score) { case HNS_Held: fDeltaLife = 0.f; @@ -161,8 +161,7 @@ LifeMeterBar::Load(const PlayerState* pPlayerState, { LifeMeter::Load(pPlayerState, pPlayerStageStats); - const DrainType dtype = - pPlayerState->m_PlayerOptions.GetStage().m_DrainType; + const auto dtype = pPlayerState->m_PlayerOptions.GetStage().m_DrainType; switch (dtype) { case DrainType_Normal: m_fLifePercentage = INITIAL_VALUE; @@ -182,7 +181,7 @@ LifeMeterBar::Load(const PlayerState* pPlayerState, void LifeMeterBar::ChangeLife(TapNoteScore score) { - float fDeltaLife = 0.f; + auto fDeltaLife = 0.f; switch (score) { DEFAULT_FAIL(score); @@ -246,9 +245,8 @@ LifeMeterBar::ChangeLife(TapNoteScore score) void LifeMeterBar::ChangeLife(HoldNoteScore score, TapNoteScore tscore) { - float fDeltaLife = 0.f; - const DrainType dtype = - m_pPlayerState->m_PlayerOptions.GetSong().m_DrainType; + auto fDeltaLife = 0.f; + const auto dtype = m_pPlayerState->m_PlayerOptions.GetSong().m_DrainType; switch (dtype) { case DrainType_Normal: switch (score) { @@ -329,7 +327,7 @@ LifeMeterBar::ChangeLife(float fDeltaLife) break; } - const float InitialLife = m_fLifePercentage; + const auto InitialLife = m_fLifePercentage; m_fLifePercentage += fDeltaLife; @@ -414,8 +412,8 @@ LifeMeterBar::FillForHowToPlay(int NumW2s, int NumMisses) { m_iProgressiveLifebar = 0; // disable progressive lifebar - const float AmountForW2 = NumW2s * m_fLifeDifficulty * 0.008f; - const float AmountForMiss = NumMisses / m_fLifeDifficulty * 0.08f; + const auto AmountForW2 = NumW2s * m_fLifeDifficulty * 0.008f; + const auto AmountForMiss = NumMisses / m_fLifeDifficulty * 0.08f; m_fLifePercentage = AmountForMiss - AmountForW2; CLAMP(m_fLifePercentage, 0.0f, 1.0f); diff --git a/src/Etterna/Actor/Gameplay/LyricDisplay.cpp b/src/Etterna/Actor/Gameplay/LyricDisplay.cpp index 01d7106ef1..2f38ec6b05 100644 --- a/src/Etterna/Actor/Gameplay/LyricDisplay.cpp +++ b/src/Etterna/Actor/Gameplay/LyricDisplay.cpp @@ -27,8 +27,8 @@ LyricDisplay::LyricDisplay() void LyricDisplay::Init() { - for (int i = 0; i < 2; i++) - m_textLyrics[i].SetText(""); + for (auto& m_textLyric : m_textLyrics) + m_textLyric.SetText(""); m_iCurLyricNumber = 0; m_fLastSecond = -500; @@ -61,7 +61,7 @@ LyricDisplay::Update(float fDeltaTime) return; const Song* pSong = GAMESTATE->m_pCurSong; - const float fStartTime = + const auto fStartTime = (pSong->m_LyricSegments[m_iCurLyricNumber].m_fStartTime) - IN_LENGTH.GetValue(); @@ -75,20 +75,19 @@ LyricDisplay::Update(float fDeltaTime) else fEndTime = pSong->GetLastSecond(); - const float fDistance = + const auto fDistance = fEndTime - pSong->m_LyricSegments[m_iCurLyricNumber].m_fStartTime; - const float fTweenBufferTime = IN_LENGTH.GetValue() + OUT_LENGTH.GetValue(); + const auto fTweenBufferTime = IN_LENGTH.GetValue() + OUT_LENGTH.GetValue(); /* If it's negative, two lyrics are so close together that there's no time * to tween properly. Lyrics should never be this brief, anyway, so just * skip it. */ - float fShowLength = max(fDistance - fTweenBufferTime, 0.0f); + auto fShowLength = max(fDistance - fTweenBufferTime, 0.0f); // Make lyrics show faster for faster song rates. fShowLength /= GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; - const LyricSegment& seg = - GAMESTATE->m_pCurSong->m_LyricSegments[m_iCurLyricNumber]; + const auto& seg = GAMESTATE->m_pCurSong->m_LyricSegments[m_iCurLyricNumber]; LuaThreadVariable var1("LyricText", seg.m_sLyric); LuaThreadVariable var2("LyricDuration", LuaReference::Create(fShowLength)); diff --git a/src/Etterna/Actor/Gameplay/NoteDisplay.cpp b/src/Etterna/Actor/Gameplay/NoteDisplay.cpp index 36c6dde0e3..d3829d79ed 100644 --- a/src/Etterna/Actor/Gameplay/NoteDisplay.cpp +++ b/src/Etterna/Actor/Gameplay/NoteDisplay.cpp @@ -16,6 +16,8 @@ #include "Etterna/Actor/Base/Sprite.h" #include "Etterna/Models/StepsAndStyles/Style.h" +#include + static const double PI_180 = PI / 180.0; static const double PI_180R = 180.0 / PI; @@ -96,7 +98,7 @@ NoteMetricCache_t::Load(const std::string& sButton) NOTESKIN->GetMetricB(sButton, "TapHoldRollOnRowMeansHold"); FOREACH_NotePart(p) { - const std::string& s = NotePartToString(p); + const auto& s = NotePartToString(p); m_fAnimationLength[p] = NOTESKIN->GetMetricF(sButton, s + "AnimationLength"); m_bAnimationIsVivid[p] = @@ -112,7 +114,7 @@ NoteMetricCache_t::Load(const std::string& sButton) m_iNoteColorCount[p] = NOTESKIN->GetMetricI(sButton, s + "NoteColorCount"); - std::string ct = NOTESKIN->GetMetric(sButton, s + "NoteColorType"); + auto ct = NOTESKIN->GetMetric(sButton, s + "NoteColorType"); m_NoteColorType[p] = StringToNoteColorType(ct); } // I was here -DaisuMaster @@ -142,12 +144,12 @@ NoteMetricCache_t::Load(const std::string& sButton) struct NoteSkinAndPath { - NoteSkinAndPath(const std::string& sNoteSkin_, - const std::string& sPath_, + NoteSkinAndPath(std::string sNoteSkin_, + std::string sPath_, const PlayerNumber& pn_, const GameController& gc_) - : sNoteSkin(sNoteSkin_) - , sPath(sPath_) + : sNoteSkin(std::move(sNoteSkin_)) + , sPath(std::move(sPath_)) , pn(pn_) , gc(gc_) { @@ -158,7 +160,7 @@ struct NoteSkinAndPath GameController gc; bool operator<(const NoteSkinAndPath& other) const { - int cmp = strcmp(sNoteSkin.c_str(), other.sNoteSkin.c_str()); + const auto cmp = strcmp(sNoteSkin.c_str(), other.sNoteSkin.c_str()); if (cmp < 0) { return true; @@ -173,23 +175,21 @@ struct NoteSkinAndPath if (pn == other.pn) return gc < other.gc; - return false; - } else { return false; } - } else { return false; } + return false; } }; struct NoteResource { - explicit NoteResource(const NoteSkinAndPath& nsap) - : m_nsap(nsap) + explicit NoteResource(NoteSkinAndPath nsap) + : m_nsap(std::move(nsap)) { m_iRefCount = 0; - m_pActor = NULL; + m_pActor = nullptr; } ~NoteResource() { delete m_pActor; } @@ -210,9 +210,9 @@ MakeNoteResource(const std::string& sButton, bool bSpriteOnly, std::string Color) { - std::string sElementAndType = + const auto sElementAndType = ssprintf("%s, %s", sButton.c_str(), sElement.c_str()); - NoteSkinAndPath nsap( + const NoteSkinAndPath nsap( NOTESKIN->GetCurrentNoteSkin(), sElementAndType, pn, gc); /* In its current state, the color feature here produces 9 times the actors @@ -224,8 +224,7 @@ MakeNoteResource(const std::string& sButton, if (PREFSMAN->m_FastNoteRendering) Color = "4th"; - map::iterator it = - g_NoteResource[Color].find(nsap); + auto it = g_NoteResource[Color].find(nsap); if (it == g_NoteResource[Color].end()) { auto* pRes = new NoteResource(nsap); @@ -233,14 +232,14 @@ MakeNoteResource(const std::string& sButton, NOTESKIN->SetGameController(gc); pRes->m_pActor = - NOTESKIN->LoadActor(sButton, sElement, NULL, bSpriteOnly, Color); + NOTESKIN->LoadActor(sButton, sElement, nullptr, bSpriteOnly, Color); ASSERT(pRes->m_pActor != NULL); g_NoteResource[Color][nsap] = pRes; it = g_NoteResource[Color].find(nsap); } - NoteResource* pRet = it->second; + auto* pRet = it->second; ++pRet->m_iRefCount; return pRet; } @@ -248,7 +247,7 @@ MakeNoteResource(const std::string& sButton, static void DeleteNoteResource(NoteResource* pRes) { - ASSERT(pRes != NULL); + ASSERT(pRes != nullptr); ASSERT_M(pRes->m_iRefCount > 0, ssprintf("RefCount %i > 0", pRes->m_iRefCount)); @@ -256,9 +255,8 @@ DeleteNoteResource(NoteResource* pRes) if (pRes->m_iRefCount != 0) return; - map>::iterator it; - for (it = g_NoteResource.begin(); it != g_NoteResource.end(); it++) - it->second.erase(pRes->m_nsap); + for (auto& it : g_NoteResource) + it.second.erase(pRes->m_nsap); delete pRes; } @@ -271,10 +269,9 @@ NoteColorActor::NoteColorActor() NoteColorActor::~NoteColorActor() { - map::iterator it; - for (it = g_p.begin(); it != g_p.end(); it++) - if (it->second) - DeleteNoteResource(it->second); + for (auto& it : g_p) + if (it.second) + DeleteNoteResource(it.second); g_p.clear(); } @@ -283,13 +280,13 @@ NoteColorActor::Load(const std::string& sButton, const std::string& sElement, PlayerNumber pn, GameController gc, - std::string Color) + const std::string& Color) { g_p[Color] = MakeNoteResource(sButton, sElement, pn, gc, false, Color); } Actor* -NoteColorActor::Get(std::string Color) +NoteColorActor::Get(const std::string& Color) { return g_p[Color]->m_pActor; } @@ -303,10 +300,9 @@ NoteColorSprite::NoteColorSprite() NoteColorSprite::~NoteColorSprite() { - map::iterator it; - for (it = g_p.begin(); it != g_p.end(); it++) - if (it->second) - DeleteNoteResource(it->second); + for (auto& it : g_p) + if (it.second) + DeleteNoteResource(it.second); g_p.clear(); } @@ -315,13 +311,13 @@ NoteColorSprite::Load(const std::string& sButton, const std::string& sElement, PlayerNumber pn, GameController gc, - std::string Color) + const std::string& Color) { g_p[Color] = MakeNoteResource(sButton, sElement, pn, gc, true, Color); } Sprite* -NoteColorSprite::Get(std::string Color) +NoteColorSprite::Get(const std::string& Color) { return dynamic_cast(g_p[Color]->m_pActor); } @@ -342,7 +338,7 @@ XToString(ActiveType); float NCSplineHandler::BeatToTValue(float song_beat, float note_beat) const { - float relative_beat = note_beat; + auto relative_beat = note_beat; // This allows someone to do something really fancy like having a spline // that extends the length of the song. Think of arrows tracing a path // as the song progresses. -Kyz @@ -358,7 +354,7 @@ NCSplineHandler::EvalForBeat(float song_beat, float note_beat, RageVector3& ret) const { - float t_value = BeatToTValue(song_beat, note_beat); + const auto t_value = BeatToTValue(song_beat, note_beat); m_spline.evaluate(t_value, ret); } @@ -367,14 +363,14 @@ NCSplineHandler::EvalDerivForBeat(float song_beat, float note_beat, RageVector3& ret) const { - float t_value = BeatToTValue(song_beat, note_beat); + const auto t_value = BeatToTValue(song_beat, note_beat); m_spline.evaluate_derivative(t_value, ret); } void NCSplineHandler::EvalForReceptor(float song_beat, RageVector3& ret) const { - float t_value = m_receptor_t; + auto t_value = m_receptor_t; if (!m_subtract_song_beat_from_curr) { t_value = song_beat / m_beats_per_t; } @@ -454,7 +450,7 @@ NoteColumnRenderArgs::SetPRZForActor(Actor* actor, const RageVector3& sp_rot, const RageVector3& ae_rot, const RageVector3& sp_zoom, - const RageVector3& ae_zoom) const + const RageVector3& ae_zoom) { actor->SetX(sp_pos.x + ae_pos.x); actor->SetY(sp_pos.y + ae_pos.y); @@ -469,7 +465,7 @@ NoteColumnRenderArgs::SetPRZForActor(Actor* actor, NoteDisplay::NoteDisplay() { - m_pPlayerState = NULL; + m_pPlayerState = nullptr; m_fYReverseOffsetPixels = 0.f; cache = new NoteMetricCache_t; } @@ -487,27 +483,26 @@ NoteDisplay::Load(int iColNum, m_pPlayerState = pPlayerState; m_fYReverseOffsetPixels = fYReverseOffsetPixels; - const PlayerNumber pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; vector GameI; GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber) ->StyleInputToGameInput(iColNum, pn, GameI); - const std::string& sButton = + const auto& sButton = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber) ->ColToButtonName(iColNum); cache->Load(sButton); vector Colors = { "4th", "8th", "12th", "16th", "24th", - "32nd", "48th", "64th", "192nd" }; + "32nd", "48th", "64th", "192nd" }; - vector::iterator Color; - for (Color = Colors.begin(); Color != Colors.end(); Color++) { + for (auto& Color : Colors) { // "normal" note types - m_TapNote.Load(sButton, "Tap Note", pn, GameI[0].controller, *Color); - m_TapMine.Load(sButton, "Tap Mine", pn, GameI[0].controller, *Color); - m_TapLift.Load(sButton, "Tap Lift", pn, GameI[0].controller, *Color); - m_TapFake.Load(sButton, "Tap Fake", pn, GameI[0].controller, *Color); + m_TapNote.Load(sButton, "Tap Note", pn, GameI[0].controller, Color); + m_TapMine.Load(sButton, "Tap Mine", pn, GameI[0].controller, Color); + m_TapLift.Load(sButton, "Tap Lift", pn, GameI[0].controller, Color); + m_TapFake.Load(sButton, "Tap Fake", pn, GameI[0].controller, Color); // hold types FOREACH_HoldType(ht) @@ -519,31 +514,31 @@ NoteDisplay::Load(int iColNum, ActiveTypeToString(at), pn, GameI[0].controller, - *Color); + Color); m_HoldTopCap[ht][at].Load(sButton, HoldTypeToString(ht) + " Topcap " + ActiveTypeToString(at), pn, GameI[0].controller, - *Color); + Color); m_HoldBody[ht][at].Load(sButton, HoldTypeToString(ht) + " Body " + ActiveTypeToString(at), pn, GameI[0].controller, - *Color); + Color); m_HoldBottomCap[ht][at].Load( sButton, HoldTypeToString(ht) + " Bottomcap " + ActiveTypeToString(at), pn, GameI[0].controller, - *Color); + Color); m_HoldTail[ht][at].Load(sButton, HoldTypeToString(ht) + " Tail " + ActiveTypeToString(at), pn, GameI[0].controller, - *Color); + Color); } } } @@ -561,52 +556,51 @@ NoteDisplay::DrawHoldsInRange( const NoteColumnRenderArgs& column_args, const vector& tap_set) { - bool any_upcoming = false; - for (vector::const_iterator tapit = - tap_set.begin(); - tapit != tap_set.end(); - ++tapit) { - const TapNote& tn = (*tapit)->second; - const HoldNoteResult& result = tn.HoldResult; - int start_row = (*tapit)->first; - int end_row = start_row + tn.iDuration; + auto any_upcoming = false; + for (const auto tapit : tap_set) { + const auto& tn = tapit->second; + const auto& result = tn.HoldResult; + const auto start_row = tapit->first; + const auto end_row = start_row + tn.iDuration; // TRICKY: If boomerang is on, then all notes in the range // [first_row,last_row] aren't necessarily visible. // Test every note to make sure it's on screen before drawing float throw_away; - bool start_past_peak = false; - bool end_past_peak = false; - float start_y = ArrowEffects::GetYOffset( + auto start_past_peak = false; + auto end_past_peak = false; + const auto start_y = ArrowEffects::GetYOffset( m_pPlayerState, column_args.column, NoteRowToVisibleBeat(m_pPlayerState, start_row), throw_away, start_past_peak); - float end_y = ArrowEffects::GetYOffset( + const auto end_y = ArrowEffects::GetYOffset( m_pPlayerState, column_args.column, NoteRowToVisibleBeat(m_pPlayerState, end_row), throw_away, end_past_peak); - bool tail_visible = field_args.draw_pixels_after_targets <= end_y && - end_y <= field_args.draw_pixels_before_targets; - bool head_visible = field_args.draw_pixels_after_targets <= start_y && - start_y <= field_args.draw_pixels_before_targets; - bool straddling_visible = + const auto tail_visible = + field_args.draw_pixels_after_targets <= end_y && + end_y <= field_args.draw_pixels_before_targets; + const auto head_visible = + field_args.draw_pixels_after_targets <= start_y && + start_y <= field_args.draw_pixels_before_targets; + const auto straddling_visible = start_y <= field_args.draw_pixels_after_targets && field_args.draw_pixels_before_targets <= end_y; - bool straddling_peak = start_past_peak && !end_past_peak; + const auto straddling_peak = start_past_peak && !end_past_peak; if (!(tail_visible || head_visible || straddling_visible || straddling_peak)) { // LOG->Trace( "skip drawing this hold." ); continue; // skip } - bool is_addition = (tn.source == TapNoteSource_Addition); - const bool hold_ghost_showing = + const auto is_addition = (tn.source == TapNoteSource_Addition); + const auto hold_ghost_showing = tn.HoldResult.bActive && tn.HoldResult.fLife > 0; - const bool is_holding = tn.HoldResult.bHeld; + const auto is_holding = tn.HoldResult.bHeld; if (hold_ghost_showing) { field_args.ghost_row->SetHoldShowing(column_args.column, tn); } @@ -614,7 +608,7 @@ NoteDisplay::DrawHoldsInRange( ASSERT_M(NoteRowToBeat(start_row) > -2000, ssprintf("%i %i %i", start_row, end_row, column_args.column)); - bool in_selection_range = false; + auto in_selection_range = false; if (*field_args.selection_begin_marker != -1 && *field_args.selection_end_marker != -1) { in_selection_range = @@ -632,8 +626,9 @@ NoteDisplay::DrawHoldsInRange( in_selection_range ? field_args.selection_glow : field_args.fail_fade); - bool note_upcoming = NoteRowToBeat(start_row) > - m_pPlayerState->GetDisplayedPosition().m_fSongBeat; + const auto note_upcoming = + NoteRowToBeat(start_row) > + m_pPlayerState->GetDisplayedPosition().m_fSongBeat; any_upcoming |= note_upcoming; } return any_upcoming; @@ -645,14 +640,11 @@ NoteDisplay::DrawTapsInRange( const NoteColumnRenderArgs& column_args, const vector& tap_set) { - bool any_upcoming = false; + auto any_upcoming = false; // draw notes from furthest to closest - for (vector::const_iterator tapit = - tap_set.begin(); - tapit != tap_set.end(); - ++tapit) { - int tap_row = (*tapit)->first; - const TapNote& tn = (*tapit)->second; + for (const auto tapit : tap_set) { + auto tap_row = tapit->first; + const auto& tn = tapit->second; if (tap_row < field_args.first_row || tap_row > field_args.last_row) { continue; // skip @@ -671,11 +663,10 @@ NoteDisplay::DrawTapsInRange( // See if there is a hold step that begins on this index. // Only do this if the noteskin cares. - bool hold_begins_on_this_beat = false; + auto hold_begins_on_this_beat = false; if (DrawHoldHeadForTapsOnSameRow()) { - for (int c2 = 0; c2 < field_args.note_data->GetNumTracks(); ++c2) { - const TapNote& tmp = - field_args.note_data->GetTapNote(c2, tap_row); + for (auto c2 = 0; c2 < field_args.note_data->GetNumTracks(); ++c2) { + const auto& tmp = field_args.note_data->GetTapNote(c2, tap_row); if (tmp.type == TapNoteType_HoldHead && tmp.subType == TapNoteSubType_Hold) { hold_begins_on_this_beat = true; @@ -685,11 +676,10 @@ NoteDisplay::DrawTapsInRange( } // do the same for a roll. - bool roll_begins_on_this_beat = false; + auto roll_begins_on_this_beat = false; if (DrawRollHeadForTapsOnSameRow()) { - for (int c2 = 0; c2 < field_args.note_data->GetNumTracks(); ++c2) { - const TapNote& tmp = - field_args.note_data->GetTapNote(c2, tap_row); + for (auto c2 = 0; c2 < field_args.note_data->GetNumTracks(); ++c2) { + const auto& tmp = field_args.note_data->GetTapNote(c2, tap_row); if (tmp.type == TapNoteType_HoldHead && tmp.subType == TapNoteSubType_Roll) { roll_begins_on_this_beat = true; @@ -698,7 +688,7 @@ NoteDisplay::DrawTapsInRange( } } - bool in_selection_range = false; + auto in_selection_range = false; if (*field_args.selection_begin_marker != -1 && *field_args.selection_end_marker != -1) { in_selection_range = @@ -706,7 +696,7 @@ NoteDisplay::DrawTapsInRange( tap_row < *field_args.selection_end_marker; } - bool is_addition = (tn.source == TapNoteSource_Addition); + const auto is_addition = (tn.source == TapNoteSource_Addition); DrawTap(tn, field_args, column_args, @@ -753,24 +743,24 @@ void NoteDisplay::SetActiveFrame(float fNoteBeat, Actor& actorToSet, float fAnimationLength, - bool bVivid) + bool bVivid) const { if (fAnimationLength == 0) return; /* -inf ... inf */ - float fBeatOrSecond = cache->m_bAnimationBasedOnBeats - ? m_pPlayerState->m_Position.m_fSongBeat - : m_pPlayerState->m_Position.m_fMusicSeconds; + const auto fBeatOrSecond = cache->m_bAnimationBasedOnBeats + ? m_pPlayerState->m_Position.m_fSongBeat + : m_pPlayerState->m_Position.m_fMusicSeconds; /* -len ... +len */ - float fPercentIntoAnimation = fmodf(fBeatOrSecond, fAnimationLength); + auto fPercentIntoAnimation = fmodf(fBeatOrSecond, fAnimationLength); /* -1 ... 1 */ fPercentIntoAnimation /= fAnimationLength; if (bVivid) { - float fNoteBeatFraction = fmodf(fNoteBeat, 1.0f); + const auto fNoteBeatFraction = fmodf(fNoteBeat, 1.0f); - const float fInterval = 1.f / fAnimationLength; + const auto fInterval = 1.f / fAnimationLength; fPercentIntoAnimation += QuantizeDown(fNoteBeatFraction, fInterval); // just in case somehow we're majorly negative with the subtraction @@ -781,15 +771,17 @@ NoteDisplay::SetActiveFrame(float fNoteBeat, fPercentIntoAnimation += 1.0f; } - float fLengthSeconds = actorToSet.GetAnimationLengthSeconds(); + const auto fLengthSeconds = actorToSet.GetAnimationLengthSeconds(); actorToSet.SetSecondsIntoAnimation(fPercentIntoAnimation * fLengthSeconds); } Actor* -NoteDisplay::GetTapActor(NoteColorActor& nca, NotePart part, float fNoteBeat) +NoteDisplay::GetTapActor(NoteColorActor& nca, + NotePart part, + float fNoteBeat) const { - std::string Color = NoteTypeToString(BeatToNoteType(fNoteBeat)); - Actor* pActorOut = nca.Get(Color); + const auto& Color = NoteTypeToString(BeatToNoteType(fNoteBeat)); + auto* const pActorOut = nca.Get(Color); SetActiveFrame(fNoteBeat, *pActorOut, @@ -803,7 +795,7 @@ NoteDisplay::GetHoldActor(NoteColorActor nca[NUM_HoldType][NUM_ActiveType], NotePart part, float fNoteBeat, bool bIsRoll, - bool bIsBeingHeld) + bool bIsBeingHeld) const { return GetTapActor( nca[bIsRoll ? roll : hold][bIsBeingHeld ? active : inactive], @@ -816,10 +808,10 @@ NoteDisplay::GetHoldSprite(NoteColorSprite ncs[NUM_HoldType][NUM_ActiveType], NotePart part, float fNoteBeat, bool bIsRoll, - bool bIsBeingHeld) + bool bIsBeingHeld) const { - std::string Color = NoteTypeToString(BeatToNoteType(fNoteBeat)); - Sprite* pSpriteOut = + const auto& Color = NoteTypeToString(BeatToNoteType(fNoteBeat)); + auto* const pSpriteOut = ncs[bIsRoll ? roll : hold][bIsBeingHeld ? active : inactive].Get(Color); SetActiveFrame(fNoteBeat, @@ -871,7 +863,7 @@ struct StripBuffer ~StripBuffer() { free(buf); } void Init() { v = buf; } - void Draw() { DISPLAY->DrawSymmetricQuadStrip(buf, v - buf); } + void Draw() const { DISPLAY->DrawSymmetricQuadStrip(buf, v - buf); } int Used() const { return v - buf; } int Free() const { return size - Used(); } }; @@ -889,19 +881,19 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, const NoteColumnRenderArgs& column_args, const draw_hold_part_args& part_args, bool glow, - int part_type) + int part_type) const { ASSERT(!vpSpr.empty()); - float ae_zoom = ArrowEffects::GetZoom(m_pPlayerState); - Sprite* pSprite = vpSpr.front(); + auto ae_zoom = ArrowEffects::GetZoom(m_pPlayerState); + auto* pSprite = vpSpr.front(); // draw manually in small segments - RectF rect = *pSprite->GetCurrentTextureCoordRect(); + auto rect = *pSprite->GetCurrentTextureCoordRect(); if (part_args.flip_texture_vertically) swap(rect.top, rect.bottom); - const float fFrameWidth = pSprite->GetUnzoomedWidth(); - float unzoomed_frame_height = pSprite->GetUnzoomedHeight(); + const auto fFrameWidth = pSprite->GetUnzoomedWidth(); + auto unzoomed_frame_height = pSprite->GetUnzoomedHeight(); if (part_type == hpt_body && cache->m_UseStretchHolds) unzoomed_frame_height = part_args.y_length; @@ -910,40 +902,40 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, * change part_args.y_top or part_args.y_bottom; they need to be left alone * to calculate texture coordinates. */ // If hold body, draw texture to the outside screen.(fix by A.C) - float y_start_pos = (part_type == hpt_body) - ? part_args.y_top - : max(part_args.y_top, part_args.y_start_pos); + auto y_start_pos = (part_type == hpt_body) + ? part_args.y_top + : max(part_args.y_top, part_args.y_start_pos); if (part_args.y_top < part_args.y_start_pos - unzoomed_frame_height) { y_start_pos = fmod((y_start_pos - part_args.y_start_pos), unzoomed_frame_height) + part_args.y_start_pos; } - float y_end_pos = min(part_args.y_bottom, part_args.y_end_pos); - const float color_scale = glow ? 1 : part_args.color_scale; + auto y_end_pos = min(part_args.y_bottom, part_args.y_end_pos); + const auto color_scale = glow ? 1 : part_args.color_scale; // top to bottom - bool bAllAreTransparent = true; - bool last_vert_set = false; - bool first_vert_set = true; + auto bAllAreTransparent = true; + auto last_vert_set = false; + auto first_vert_set = true; float add_to_tex_coord = 0; // The caps should always use the full texture. if (part_type == hpt_body) { if (!part_args.anchor_to_top) { - float tex_coord_bottom = SCALE(part_args.y_bottom - part_args.y_top, - 0, - unzoomed_frame_height, - rect.top, - rect.bottom); - float want_tex_coord_bottom = ceilf(tex_coord_bottom - 0.0001f); + auto tex_coord_bottom = SCALE(part_args.y_bottom - part_args.y_top, + 0, + unzoomed_frame_height, + rect.top, + rect.bottom); + auto want_tex_coord_bottom = ceilf(tex_coord_bottom - 0.0001f); add_to_tex_coord = want_tex_coord_bottom - tex_coord_bottom; } if (part_args.wrapping) { /* For very large hold notes, shift the texture coordinates to be * near 0, so we don't send very large values to the renderer. */ - const float fDistFromTop = y_start_pos - part_args.y_top; - float fTexCoordTop = SCALE( + const auto fDistFromTop = y_start_pos - part_args.y_top; + auto fTexCoordTop = SCALE( fDistFromTop, 0, unzoomed_frame_height, rect.top, rect.bottom); fTexCoordTop += add_to_tex_coord; add_to_tex_coord -= floorf(fTexCoordTop); @@ -953,7 +945,7 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, // shifted by one pixel or there is a seam. -Kyz if (part_type == hpt_bottom) { if (!part_args.anchor_to_top) { - float offset = + auto offset = unzoomed_frame_height - (y_end_pos - y_start_pos) / ae_zoom; // ロングノート本体の長さがunzoomed_frame_height→0のときに、add_to_tex_coordを0→1にすればOK // つまり、offsetを0→unzoomed_frame_heightにすると理想通りの表示になる @@ -968,24 +960,24 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, } } - const float fTexCoordLeft = rect.left; - const float fTexCoordRight = rect.right; - const float fTexCoordCenter = (fTexCoordLeft + fTexCoordRight) / 2; + const auto fTexCoordLeft = rect.left; + const auto fTexCoordRight = rect.right; + const auto fTexCoordCenter = (fTexCoordLeft + fTexCoordRight) / 2; // pos_z_vec will be used later to orient the hold. Read below. -Kyz static const RageVector3 pos_z_vec(0.0f, 0.0f, 1.0f); static const RageVector3 pos_y_vec(0.0f, 1.0f, 0.0f); StripBuffer queue; - for (float fY = y_start_pos; !last_vert_set; fY += part_args.y_step) { + for (auto fY = y_start_pos; !last_vert_set; fY += part_args.y_step) { if (fY >= y_end_pos) { fY = y_end_pos; last_vert_set = true; } - const float fYOffset = ArrowEffects::GetYOffsetFromYPos( + const auto fYOffset = ArrowEffects::GetYOffsetFromYPos( column_args.column, fY, m_fYReverseOffsetPixels); - float cur_beat = part_args.top_beat; + auto cur_beat = part_args.top_beat; if (part_args.top_beat != part_args.bottom_beat) { cur_beat = SCALE(fY, part_args.y_top, @@ -1067,7 +1059,7 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, // Holds are only affected by the x axis of the zoom spline because they // are flat sprites. -Kyz - float render_width = fFrameWidth; + auto render_width = fFrameWidth; switch (column_args.zoom_handler->m_spline_mode) { case NCSM_Disabled: render_width = fFrameWidth * ae_zoom; @@ -1086,9 +1078,9 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, break; } - const float fFrameWidthScale = ArrowEffects::GetFrameWidthScale( + const auto fFrameWidthScale = ArrowEffects::GetFrameWidthScale( m_pPlayerState, fYOffset, part_args.overlapped_time); - const float fScaledFrameWidth = render_width * fFrameWidthScale; + const auto fScaledFrameWidth = render_width * fFrameWidthScale; // Can't use the same code as for taps because hold bodies can only // rotate around the y axis. -Kyz @@ -1123,7 +1115,7 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, center_vert.z += render_forward.z; } - const float render_roty = (sp_rot.y + ae_rot.y); + const auto render_roty = (sp_rot.y + ae_rot.y); // (step 2 of vector handling) RageVector3 render_left; @@ -1134,7 +1126,7 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, RageVec3Cross(&render_left, &pos_z_vec, &render_forward); } RageAARotate(&render_left, &render_forward, render_roty); - const float half_width = fScaledFrameWidth * .5f; + const auto half_width = fScaledFrameWidth * .5f; render_left.x *= half_width; render_left.y *= half_width; render_left.z *= half_width; @@ -1146,12 +1138,12 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, center_vert.y - render_left.y, center_vert.z - render_left.z); - const float fDistFromTop = (fY - y_start_pos) / ae_zoom; - float fTexCoordTop = + const auto fDistFromTop = (fY - y_start_pos) / ae_zoom; + auto fTexCoordTop = SCALE(fDistFromTop, 0, unzoomed_frame_height, rect.top, rect.bottom); fTexCoordTop += add_to_tex_coord; - const float fAlpha = + const auto fAlpha = ArrowGetAlphaOrGlow(glow, m_pPlayerState, column_args.column, @@ -1160,10 +1152,10 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, m_fYReverseOffsetPixels, field_args.draw_pixels_before_targets, field_args.fade_before_targets); - const RageColor color = RageColor(column_args.diffuse.r * color_scale, - column_args.diffuse.g * color_scale, - column_args.diffuse.b * color_scale, - column_args.diffuse.a * fAlpha); + const auto color = RageColor(column_args.diffuse.r * color_scale, + column_args.diffuse.g * color_scale, + column_args.diffuse.b * color_scale, + column_args.diffuse.a * fAlpha); if (fAlpha > 0) bAllAreTransparent = false; @@ -1184,7 +1176,7 @@ NoteDisplay::DrawHoldPart(vector& vpSpr, if (!bAllAreTransparent) { FOREACH(Sprite*, vpSpr, spr) { - RageTexture* pTexture = (*spr)->GetTexture(); + auto* pTexture = (*spr)->GetTexture(); DISPLAY->SetTexture(TextureUnit_1, pTexture->GetTexHandle()); DISPLAY->SetBlendMode(spr == vpSpr.begin() ? BLEND_NORMAL @@ -1216,7 +1208,7 @@ NoteDisplay::DrawHoldBodyInternal(vector& sprite_top, const float y_length, const float top_beat, const float bottom_beat, - bool glow) + bool glow) const { if (y_head < y_tail) { // Draw the top cap @@ -1268,7 +1260,7 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, part_args.color_scale = color_scale; part_args.overlapped_time = tn.HoldResult.fOverlappedTime; vector vpSprTop; - Sprite* pSpriteTop = + auto* pSpriteTop = GetHoldSprite(m_HoldTopCap, NotePart_HoldTopCap, beat, @@ -1277,7 +1269,7 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, vpSprTop.push_back(pSpriteTop); vector vpSprBody; - Sprite* pSpriteBody = + auto* const pSpriteBody = GetHoldSprite(m_HoldBody, NotePart_HoldBody, beat, @@ -1286,7 +1278,7 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, vpSprBody.push_back(pSpriteBody); vector vpSprBottom; - Sprite* pSpriteBottom = + auto* pSpriteBottom = GetHoldSprite(m_HoldBottomCap, NotePart_HoldBottomCap, beat, @@ -1295,27 +1287,28 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, vpSprBottom.push_back(pSpriteBottom); if (being_held && cache->m_bHoldActiveIsAddLayer) { - Sprite* pSprTop = GetHoldSprite(m_HoldTopCap, - NotePart_HoldTopCap, - beat, - tn.subType == TapNoteSubType_Roll, - true); + auto* const pSprTop = GetHoldSprite(m_HoldTopCap, + NotePart_HoldTopCap, + beat, + tn.subType == TapNoteSubType_Roll, + true); vpSprTop.push_back(pSprTop); - Sprite* pSprBody = GetHoldSprite(m_HoldBody, - NotePart_HoldBody, - beat, - tn.subType == TapNoteSubType_Roll, - true); + auto* const pSprBody = GetHoldSprite(m_HoldBody, + NotePart_HoldBody, + beat, + tn.subType == TapNoteSubType_Roll, + true); vpSprBody.push_back(pSprBody); - Sprite* pSprBottom = GetHoldSprite(m_HoldBottomCap, - NotePart_HoldBottomCap, - beat, - tn.subType == TapNoteSubType_Roll, - true); + auto* const pSprBottom = + GetHoldSprite(m_HoldBottomCap, + NotePart_HoldBottomCap, + beat, + tn.subType == TapNoteSubType_Roll, + true); vpSprBottom.push_back(pSprBottom); } - const bool reverse = + const auto reverse = m_pPlayerState->m_PlayerOptions.GetCurrent().GetReversePercentForColumn( column_args.column) > 0.5f; part_args.flip_texture_vertically = @@ -1325,7 +1318,7 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, swap(pSpriteTop, pSpriteBottom); } - const bool bWavyPartsNeedZBuffer = ArrowEffects::NeedZBuffer(); + const auto bWavyPartsNeedZBuffer = ArrowEffects::NeedZBuffer(); DISPLAY->SetZTestMode(bWavyPartsNeedZBuffer ? ZTEST_WRITE_ON_PASS : ZTEST_OFF); DISPLAY->SetZWrite(bWavyPartsNeedZBuffer); @@ -1342,9 +1335,9 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, y_tail += cache->m_iStopDrawingHoldBodyOffsetFromTail; } - float ae_zoom = ArrowEffects::GetZoom(m_pPlayerState); - const float frame_height_top = pSpriteTop->GetUnzoomedHeight() * ae_zoom; - const float frame_height_bottom = + const auto ae_zoom = ArrowEffects::GetZoom(m_pPlayerState); + const auto frame_height_top = pSpriteTop->GetUnzoomedHeight() * ae_zoom; + const auto frame_height_bottom = pSpriteBottom->GetUnzoomedHeight() * ae_zoom; part_args.y_start_pos = @@ -1359,9 +1352,9 @@ NoteDisplay::DrawHoldBody(const TapNote& tn, swap(part_args.y_start_pos, part_args.y_end_pos); } // So that part_args.y_start_pos can be changed when drawing the bottom. - const float original_y_start_pos = part_args.y_start_pos; - const float head_minus_top = y_head - frame_height_top; - const float tail_plus_bottom = y_tail + frame_height_bottom; + const auto original_y_start_pos = part_args.y_start_pos; + const auto head_minus_top = y_head - frame_height_top; + const auto tail_plus_bottom = y_tail + frame_height_bottom; part_args.anchor_to_top = reverse && cache->m_bTopHoldAnchorWhenReverse; @@ -1415,9 +1408,9 @@ NoteDisplay::DrawHold(const TapNote& tn, bool bIsAddition, float fPercentFadeToFail) { - int iEndRow = iRow + tn.iDuration; - float top_beat = NoteRowToVisibleBeat(m_pPlayerState, iRow); - float bottom_beat = NoteRowToVisibleBeat(m_pPlayerState, iEndRow); + const auto iEndRow = iRow + tn.iDuration; + auto top_beat = NoteRowToVisibleBeat(m_pPlayerState, iRow); + const auto bottom_beat = NoteRowToVisibleBeat(m_pPlayerState, iEndRow); if (bIsBeingHeld) { top_beat = column_args.song_beat; } @@ -1425,15 +1418,16 @@ NoteDisplay::DrawHold(const TapNote& tn, // bDrawGlowOnly is a little hacky. We need to draw the diffuse part and // the glow part one pass at a time to minimize state changes - bool bReverse = + const auto bReverse = m_pPlayerState->m_PlayerOptions.GetCurrent().GetReversePercentForColumn( column_args.column) > 0.5f; - float fStartBeat = NoteRowToBeat(max(tn.HoldResult.iLastHeldRow, iRow)); + const auto fStartBeat = + NoteRowToBeat(max(tn.HoldResult.iLastHeldRow, iRow)); float fThrowAway = 0; // HACK: If life > 0, don't set YOffset to 0 so that it doesn't jiggle // around the receptor. - bool bStartIsPastPeak = true; + auto bStartIsPastPeak = true; float fStartYOffset = 0; if (tn.HoldResult.bActive && tn.HoldResult.fLife > 0) ; // use the default values filled in above @@ -1445,17 +1439,17 @@ NoteDisplay::DrawHold(const TapNote& tn, bStartIsPastPeak); float fEndPeakYOffset = 0; - bool bEndIsPastPeak = false; - float fEndYOffset = ArrowEffects::GetYOffset(m_pPlayerState, - column_args.column, - NoteRowToBeat(iEndRow), - fEndPeakYOffset, - bEndIsPastPeak); - float length; + auto bEndIsPastPeak = false; + auto fEndYOffset = ArrowEffects::GetYOffset(m_pPlayerState, + column_args.column, + NoteRowToBeat(iEndRow), + fEndPeakYOffset, + bEndIsPastPeak); if (!tn.HoldResult.bActive) HoldSize[m_pPlayerState->m_PlayerNumber][iRow][column_args.column] = fEndYOffset - fStartYOffset; - length = HoldSize[m_pPlayerState->m_PlayerNumber][iRow][column_args.column]; + auto length = + HoldSize[m_pPlayerState->m_PlayerNumber][iRow][column_args.column]; if (cache->m_UseShrinkHolds) length = fEndYOffset - fStartYOffset; @@ -1472,19 +1466,20 @@ NoteDisplay::DrawHold(const TapNote& tn, if (bReverse) swap(fStartYOffset, fEndYOffset); - const float fYHead = ArrowEffects::GetYPos( + const auto fYHead = ArrowEffects::GetYPos( column_args.column, fStartYOffset, m_fYReverseOffsetPixels); - const float fYTail = ArrowEffects::GetYPos( + const auto fYTail = ArrowEffects::GetYPos( column_args.column, fEndYOffset, m_fYReverseOffsetPixels); - const float fColorScale = SCALE( + const auto fColorScale = SCALE( tn.HoldResult.fLife, 0.0f, 1.0f, cache->m_fHoldLetGoGrayPercent, 1.0f); - bool bFlipHeadAndTail = bReverse && cache->m_bFlipHeadAndTailWhenReverse; + const auto bFlipHeadAndTail = + bReverse && cache->m_bFlipHeadAndTailWhenReverse; /* The body and caps should have no overlap, so their order doesn't matter. * Draw the head last, so it appears on top. */ - float fBeat = NoteRowToBeat(iRow); + const auto fBeat = NoteRowToBeat(iRow); // Side note: I don't know why these two checks were commented out and I // didn't bother to update them when rewriting the arguments that are // passed to the note drawing functions. -Kyz @@ -1526,11 +1521,11 @@ NoteDisplay::DrawHold(const TapNote& tn, // this part was modified in pumpmania, where it flips the draw order // of the head and tail. Perhaps make this a theme/noteskin metric? -aj if (cache->m_bHoldTailIsAboveWavyParts) { - Actor* pActor = GetHoldActor(m_HoldTail, - NotePart_HoldTail, - NoteRowToBeat(iRow), - tn.subType == TapNoteSubType_Roll, - bIsBeingHeld); + auto* const pActor = GetHoldActor(m_HoldTail, + NotePart_HoldTail, + NoteRowToBeat(iRow), + tn.subType == TapNoteSubType_Roll, + bIsBeingHeld); DrawActor(tn, pActor, NotePart_HoldTail, @@ -1544,11 +1539,11 @@ NoteDisplay::DrawHold(const TapNote& tn, false); } if (cache->m_bHoldHeadIsAboveWavyParts) { - Actor* pActor = GetHoldActor(m_HoldHead, - NotePart_HoldHead, - NoteRowToBeat(iRow), - tn.subType == TapNoteSubType_Roll, - bIsBeingHeld); + auto* const pActor = GetHoldActor(m_HoldHead, + NotePart_HoldHead, + NoteRowToBeat(iRow), + tn.subType == TapNoteSubType_Roll, + bIsBeingHeld); DrawActor(tn, pActor, NotePart_HoldHead, @@ -1574,7 +1569,7 @@ NoteDisplay::DrawActor(const TapNote& tn, bool bIsAddition, float fPercentFadeToFail, float fColorScale, - bool is_being_held) + bool is_being_held) const { if (tn.type == TapNoteType_AutoKeysound) return; @@ -1582,30 +1577,30 @@ NoteDisplay::DrawActor(const TapNote& tn, fYOffset > field_args.draw_pixels_before_targets) { return; } - float spline_beat = fBeat; + auto spline_beat = fBeat; if (is_being_held) { spline_beat = column_args.song_beat; } - const float fAlpha = + const auto fAlpha = ArrowEffects::GetAlpha(column_args.column, fYOffset, fPercentFadeToFail, m_fYReverseOffsetPixels, field_args.draw_pixels_before_targets, field_args.fade_before_targets); - const float fGlow = + const auto fGlow = ArrowEffects::GetGlow(column_args.column, fYOffset, fPercentFadeToFail, m_fYReverseOffsetPixels, field_args.draw_pixels_before_targets, field_args.fade_before_targets); - const RageColor diffuse = RageColor(column_args.diffuse.r * fColorScale, - column_args.diffuse.g * fColorScale, - column_args.diffuse.b * fColorScale, - column_args.diffuse.a * fAlpha); - const RageColor glow = RageColor(1, 1, 1, fGlow); + const auto diffuse = RageColor(column_args.diffuse.r * fColorScale, + column_args.diffuse.g * fColorScale, + column_args.diffuse.b * fColorScale, + column_args.diffuse.a * fAlpha); + const auto glow = RageColor(1, 1, 1, fGlow); // We can't actually use the glow color from the effect on the colum actor // because it's used by the stealth modifier. -Kyz /* @@ -1616,8 +1611,8 @@ NoteDisplay::DrawActor(const TapNote& tn, column_args.glow.a * fGlow); */ - bool bIsHoldHead = tn.type == TapNoteType_HoldHead; - bool bIsHoldCap = bIsHoldHead || tn.type == TapNoteType_HoldTail; + const auto bIsHoldHead = tn.type == TapNoteType_HoldHead; + const auto bIsHoldCap = bIsHoldHead || tn.type == TapNoteType_HoldTail; // So, thie call to GetBrightness does nothing because fColorScale is not // used after this point. If you read GetBrightness, it looks like it's @@ -1678,13 +1673,13 @@ NoteDisplay::DrawActor(const TapNote& tn, pActor->SetDiffuse(diffuse); pActor->SetGlow(glow); - bool bNeedsTranslate = + const auto bNeedsTranslate = (bIsAddition && !IsVectorZero(cache->m_fAdditionTextureCoordOffset[part])) || !IsVectorZero(cache->m_fNoteColorTextureCoordSpacing[part]); if (bNeedsTranslate) { DISPLAY->TexturePushMatrix(); - float color = 0.0f; + auto color = 0.0f; switch (cache->m_NoteColorType[part]) { case NoteColorType_Denominator: color = float(BeatToNoteType(fBeat)); @@ -1722,8 +1717,8 @@ NoteDisplay::DrawTap(const TapNote& tn, bool bIsAddition, float fPercentFadeToFail) { - Actor* pActor = NULL; - NotePart part = NotePart_Tap; + Actor* pActor = nullptr; + auto part = NotePart_Tap; /* if( tn.source == TapNoteSource_Addition ) { @@ -1734,7 +1729,7 @@ NoteDisplay::DrawTap(const TapNote& tn, if (tn.type == TapNoteType_Tap) { pActor = GetTapActor(m_TapNote, NotePart_Tap, fBeat); - const float fYOffset = + const auto fYOffset = ArrowEffects::GetYOffset(m_pPlayerState, column_args.column, fBeat); DrawActor(tn, pActor, @@ -1795,11 +1790,11 @@ NoteDisplay::DrawTap(const TapNote& tn, pActor = GetTapActor(m_TapNote, NotePart_Tap, fBeat); } - const float fYOffset = + const auto fYOffset = ArrowEffects::GetYOffset(m_pPlayerState, column_args.column, fBeat); // this is the line that forces the (1,1,1,x) part of the noteskin diffuse // -aj - if (pActor != NULL) + if (pActor != nullptr) DrawActor(tn, pActor, part, @@ -1816,8 +1811,9 @@ NoteDisplay::DrawTap(const TapNote& tn, void NoteColumnRenderer::UpdateReceptorGhostStuff(Actor* receptor) const { - const PlayerState* player_state = m_field_render_args->player_state; - float song_beat = player_state->GetDisplayedPosition().m_fSongBeatVisible; + const auto* const player_state = m_field_render_args->player_state; + const auto song_beat = + player_state->GetDisplayedPosition().m_fSongBeatVisible; // sp_* will be filled with the settings from the splines. // ae_* will be filled with the settings from ArrowEffects. // The two together will be applied to the actor. @@ -1899,7 +1895,7 @@ NoteColumnRenderer::DrawPrimitives() m_column_render_args.zoom_handler = &NCR_current.m_zoom_handler; m_column_render_args.diffuse = m_pTempState->diffuse[0]; m_column_render_args.glow = m_pTempState->glow; - bool any_upcoming = false; + auto any_upcoming = false; // Build lists of holds and taps for each player number, then pass those // lists to the displays to draw. // The vector in the NUM_PlayerNumber slot should stay empty, not worth @@ -1914,7 +1910,7 @@ NoteColumnRenderer::DrawPrimitives() begin, end); for (; begin != end; ++begin) { - const TapNote& tn = begin->second; + const auto& tn = begin->second; switch (tn.type) { case TapNoteType_Empty: continue; diff --git a/src/Etterna/Actor/Gameplay/NoteDisplay.h b/src/Etterna/Actor/Gameplay/NoteDisplay.h index 5db5844648..74f260ffe1 100644 --- a/src/Etterna/Actor/Gameplay/NoteDisplay.h +++ b/src/Etterna/Actor/Gameplay/NoteDisplay.h @@ -35,7 +35,7 @@ enum NotePart enum NoteColorType { NoteColorType_Denominator, /**< Color by note type. */ - NoteColorType_Progress, /**< Color by progress. */ + NoteColorType_Progress, /**< Color by progress. */ NUM_NoteColorType, NoteColorType_Invalid }; @@ -54,8 +54,8 @@ struct NoteColorActor const std::string& sElement, PlayerNumber, GameController, - std::string); - Actor* Get(std::string); + const std::string&); + Actor* Get(const std::string&); private: map g_p; @@ -69,8 +69,8 @@ struct NoteColorSprite const std::string& sElement, PlayerNumber, GameController, - std::string); - Sprite* Get(std::string); + const std::string&); + Sprite* Get(const std::string&); private: map g_p; @@ -150,7 +150,8 @@ struct NCSplineHandler m_beats_per_t = 1.0f; m_subtract_song_beat_from_curr = true; } - float BeatToTValue(float song_beat, float note_beat) const; + + [[nodiscard]] float BeatToTValue(float song_beat, float note_beat) const; void EvalForBeat(float song_beat, float note_beat, RageVector3& ret) const; void EvalDerivForBeat(float song_beat, float note_beat, @@ -182,13 +183,13 @@ struct NoteColumnRenderArgs float beat, RageVector3& sp_zoom, RageVector3& ae_zoom) const; - void SetPRZForActor(Actor* actor, - const RageVector3& sp_pos, - const RageVector3& ae_pos, - const RageVector3& sp_rot, - const RageVector3& ae_rot, - const RageVector3& sp_zoom, - const RageVector3& ae_zoom) const; + static void SetPRZForActor(Actor* actor, + const RageVector3& sp_pos, + const RageVector3& ae_pos, + const RageVector3& sp_rot, + const RageVector3& ae_rot, + const RageVector3& sp_zoom, + const RageVector3& ae_zoom); const NCSplineHandler* pos_handler; const NCSplineHandler* rot_handler; const NCSplineHandler* zoom_handler; @@ -251,25 +252,27 @@ class NoteDisplay bool bIsAddition, float fPercentFadeToFail); - bool DrawHoldHeadForTapsOnSameRow() const; - bool DrawRollHeadForTapsOnSameRow() const; + [[nodiscard]] bool DrawHoldHeadForTapsOnSameRow() const; + [[nodiscard]] bool DrawRollHeadForTapsOnSameRow() const; private: void SetActiveFrame(float fNoteBeat, Actor& actorToSet, float fAnimationLength, - bool bVivid); - Actor* GetTapActor(NoteColorActor& nca, NotePart part, float fNoteBeat); + bool bVivid) const; + Actor* GetTapActor(NoteColorActor& nca, + NotePart part, + float fNoteBeat) const; Actor* GetHoldActor(NoteColorActor nca[NUM_HoldType][NUM_ActiveType], NotePart part, float fNoteBeat, bool bIsRoll, - bool bIsBeingHeld); + bool bIsBeingHeld) const; Sprite* GetHoldSprite(NoteColorSprite ncs[NUM_HoldType][NUM_ActiveType], NotePart part, float fNoteBeat, bool bIsRoll, - bool bIsBeingHeld); + bool bIsBeingHeld) const; struct draw_hold_part_args { @@ -299,27 +302,27 @@ class NoteDisplay bool bIsAddition, float fPercentFadeToFail, float fColorScale, - bool is_being_held); + bool is_being_held) const; void DrawHoldPart(vector& vpSpr, const NoteFieldRenderArgs& field_args, const NoteColumnRenderArgs& column_args, const draw_hold_part_args& part_args, bool glow, - int part_type); + int part_type) const; void DrawHoldBodyInternal(vector& sprite_top, vector& sprite_body, vector& sprite_bottom, const NoteFieldRenderArgs& field_args, const NoteColumnRenderArgs& column_args, draw_hold_part_args& part_args, - const float head_minus_top, - const float tail_plus_bottom, - const float y_head, - const float y_tail, - const float y_length, - const float top_beat, - const float bottom_beat, - bool glow); + float head_minus_top, + float tail_plus_bottom, + float y_head, + float y_tail, + float y_length, + float top_beat, + float bottom_beat, + bool glow) const; void DrawHoldBody(const TapNote& tn, const NoteFieldRenderArgs& field_args, const NoteColumnRenderArgs& column_args, @@ -393,11 +396,11 @@ struct NoteColumnRenderer : public Actor { if (NCR_Tweens.empty()) { return NCR_current; - } else { - return NCR_Tweens.back(); } + return NCR_Tweens.back(); } - const NCR_TweenState& NCR_DestTweenState() const + + [[nodiscard]] const NCR_TweenState& NCR_DestTweenState() const { return const_cast(this)->NCR_DestTweenState(); } diff --git a/src/Etterna/Actor/Gameplay/NoteField.cpp b/src/Etterna/Actor/Gameplay/NoteField.cpp index dca0bafd29..ea1d67a4cf 100644 --- a/src/Etterna/Actor/Gameplay/NoteField.cpp +++ b/src/Etterna/Actor/Gameplay/NoteField.cpp @@ -154,12 +154,13 @@ NoteField::CacheAllUsedNoteSkins() * lying around. Remove them so they don't accumulate. */ set setNoteSkinsToUnload; for (auto& d : m_NoteDisplays) { - auto unused = find(asSkinsLower.begin(), asSkinsLower.end(), d.first) == - asSkinsLower.end(); + const auto unused = + find(asSkinsLower.begin(), asSkinsLower.end(), d.first) == + asSkinsLower.end(); if (unused) setNoteSkinsToUnload.insert(d.first); } - for (auto& s : setNoteSkinsToUnload) { + for (const auto& s : setNoteSkinsToUnload) { UncacheNoteSkin(s); } @@ -218,7 +219,7 @@ NoteField::Load(const NoteData* pNoteData, int iDrawDistanceAfterTargetsPixels, int iDrawDistanceBeforeTargetsPixels) { - ASSERT(pNoteData != NULL); + ASSERT(pNoteData != nullptr); m_pNoteData = pNoteData; m_iDrawDistanceAfterTargetsPixels = iDrawDistanceAfterTargetsPixels; m_iDrawDistanceBeforeTargetsPixels = iDrawDistanceBeforeTargetsPixels; @@ -251,7 +252,7 @@ NoteField::ensure_note_displays_have_skin() /* XXX: Combination of good idea and bad idea to ensure courses load * regardless of noteskin content. This may take a while to fix. */ - auto badIdea = m_pCurDisplay; + auto* badIdea = m_pCurDisplay; if (sNoteSkinLower.empty()) { sNoteSkinLower = @@ -343,8 +344,9 @@ NoteField::Update(float fDeltaTime) // m_fYPosCurrentBeatLastUpdate const auto fCurrentBeat = m_pPlayerState->GetDisplayedPosition().m_fSongBeat; - auto bTweeningOn = m_sprBoard->GetCurrentDiffuseAlpha() >= 0.98 && - m_sprBoard->GetCurrentDiffuseAlpha() < 1.00; // HACK + const auto bTweeningOn = + m_sprBoard->GetCurrentDiffuseAlpha() >= 0.98 && + m_sprBoard->GetCurrentDiffuseAlpha() < 1.00; // HACK if (!bTweeningOn && m_fCurrentBeatLastUpdate != -1) { const auto fYOffsetLast = ArrowEffects::GetYOffset(m_pPlayerState, 0, m_fCurrentBeatLastUpdate); @@ -367,7 +369,7 @@ NoteField::Update(float fDeltaTime) m_rectMarkerBar.Update(fDeltaTime); - auto cur = m_pCurDisplay; + auto* cur = m_pCurDisplay; cur->m_ReceptorArrowRow.Update(fDeltaTime); cur->m_GhostArrowRow.Update(fDeltaTime); @@ -389,7 +391,7 @@ NoteField::Update(float fDeltaTime) * once per player. */ // TODO: Remove use of PlayerNumber. - auto pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; if (pn == GAMESTATE->GetMasterPlayerNumber()) NoteDisplay::Update(fDeltaTime); } @@ -397,7 +399,8 @@ NoteField::Update(float fDeltaTime) float NoteField::GetWidth() const { - auto pStyle = GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); + const auto* const pStyle = + GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); float fMinX, fMaxX; // TODO: Remove use of PlayerNumber. pStyle->GetMinAndMaxColX(m_pPlayerState->m_PlayerNumber, fMinX, fMaxX); @@ -409,7 +412,7 @@ NoteField::GetWidth() const void NoteField::DrawBeatBar(const float fBeat, BeatBarType type, int iMeasureIndex) { - auto bIsMeasure = type == measure; + const auto bIsMeasure = type == measure; const auto fYOffset = ArrowEffects::GetYOffset(m_pPlayerState, 0, fBeat); const auto fYPos = @@ -449,8 +452,8 @@ NoteField::DrawBeatBar(const float fBeat, BeatBarType type, int iMeasureIndex) CLAMP(fAlpha, 0, 1); } - auto fWidth = GetWidth(); - auto fFrameWidth = m_sprBeatBars.GetUnzoomedWidth(); + const auto fWidth = GetWidth(); + const auto fFrameWidth = m_sprBeatBars.GetUnzoomedWidth(); m_sprBeatBars.SetX(0); m_sprBeatBars.SetY(fYPos); @@ -481,7 +484,8 @@ NoteField::DrawBoard(int iDrawDistanceAfterTargetsPixels, auto rect = *pSprite->GetCurrentTextureCoordRect(); const auto fBoardGraphicHeightPixels = pSprite->GetUnzoomedHeight(); - auto fTexCoordOffset = m_fBoardOffsetPixels / fBoardGraphicHeightPixels; + const auto fTexCoordOffset = + m_fBoardOffsetPixels / fBoardGraphicHeightPixels; // top half const auto fHeight = @@ -499,7 +503,7 @@ NoteField::DrawBoard(int iDrawDistanceAfterTargetsPixels, rect.bottom = -fTexCoordOffset + (-iDrawDistanceAfterTargetsPixels / fBoardGraphicHeightPixels); pSprite->SetCustomTextureRect(rect); - auto fFadeTop = + const auto fFadeTop = FADE_BEFORE_TARGETS_PERCENT * iDrawDistanceBeforeTargetsPixels / (iDrawDistanceBeforeTargetsPixels - iDrawDistanceAfterTargetsPixels); pSprite->SetFadeTop(fFadeTop); @@ -510,7 +514,7 @@ NoteField::DrawBoard(int iDrawDistanceAfterTargetsPixels, void NoteField::DrawMarkerBar(int iBeat) { - auto fBeat = NoteRowToBeat(iBeat); + const auto fBeat = NoteRowToBeat(iBeat); const auto fYOffset = ArrowEffects::GetYOffset(m_pPlayerState, 0, fBeat); const auto fYPos = ArrowEffects::GetYPos(0, fYOffset, m_fYReverseOffsetPixels); @@ -527,15 +531,15 @@ static ThemeMetric AREA_HIGHLIGHT_COLOR("NoteField", void NoteField::DrawAreaHighlight(int iStartBeat, int iEndBeat) { - auto fStartBeat = NoteRowToBeat(iStartBeat); - auto fEndBeat = NoteRowToBeat(iEndBeat); - auto fDrawDistanceAfterTargetsPixels = + const auto fStartBeat = NoteRowToBeat(iStartBeat); + const auto fEndBeat = NoteRowToBeat(iEndBeat); + const auto fDrawDistanceAfterTargetsPixels = ArrowEffects::GetYOffset(m_pPlayerState, 0, fStartBeat); - auto fYStartPos = ArrowEffects::GetYPos( + const auto fYStartPos = ArrowEffects::GetYPos( 0, fDrawDistanceAfterTargetsPixels, m_fYReverseOffsetPixels); - auto fDrawDistanceBeforeTargetsPixels = + const auto fDrawDistanceBeforeTargetsPixels = ArrowEffects::GetYOffset(m_pPlayerState, 0, fEndBeat); - auto fYEndPos = ArrowEffects::GetYPos( + const auto fYEndPos = ArrowEffects::GetYPos( 0, fDrawDistanceBeforeTargetsPixels, m_fYReverseOffsetPixels); // The caller should have clamped these to reasonable values @@ -603,31 +607,24 @@ GetNumNotesFromBeginning(const PlayerState* pPlayerState, float beat) // times already. // how can we abstract this? const auto& data = pPlayerState->m_CacheNoteStat; - int max = data.size() - 1; + const int max = data.size() - 1; auto l = 0, r = max; while (l <= r) { - auto m = (l + r) / 2; + const auto m = (l + r) / 2; if ((m == 0 || data[m].beat <= beat) && (m == max || beat < data[m + 1].beat)) { return data[m]; - } else if (data[m].beat <= beat) { + } + if (data[m].beat <= beat) { l = m + 1; } else { r = m - 1; } } - CacheNoteStat dummy = { 0, 0, 0 }; + const CacheNoteStat dummy = { 0, 0, 0 }; return dummy; } -static int -GetNumNotesRange(const PlayerState* pPlayerState, float fLow, float fHigh) -{ - auto low = GetNumNotesFromBeginning(pPlayerState, fLow); - auto high = GetNumNotesFromBeginning(pPlayerState, fHigh); - return high.notesUpper - low.notesLower; -} - void FindDisplayedBeats(const PlayerState* pPlayerState, float& firstBeat, @@ -638,14 +635,15 @@ FindDisplayedBeats(const PlayerState* pPlayerState, auto fFirstBeatToDraw = pPlayerState->GetDisplayedPosition().m_fSongBeatVisible; auto fLastBeatToDraw = fFirstBeatToDraw; - auto fSpeedMultiplier = + const auto fSpeedMultiplier = pPlayerState->GetDisplayedTiming().GetDisplayedSpeedPercent( pPlayerState->GetDisplayedPosition().m_fSongBeatVisible, pPlayerState->GetDisplayedPosition().m_fMusicSecondsVisible); bool bBoomerang; { - auto fAccels = pPlayerState->m_PlayerOptions.GetCurrent().m_fAccels; + const auto* const fAccels = + pPlayerState->m_PlayerOptions.GetCurrent().m_fAccels; bBoomerang = (fAccels[PlayerOptions::ACCEL_BOOMERANG] != 0); } @@ -656,12 +654,12 @@ FindDisplayedBeats(const PlayerState* pPlayerState, for (auto i = 0; i < NUM_ITERATIONS; i++) { bool bIsPastPeakYOffset; float fPeakYOffset; - auto fYOffset = ArrowEffects::GetYOffset(pPlayerState, - 0, - fLastBeatToDraw, - fPeakYOffset, - bIsPastPeakYOffset, - true); + const auto fYOffset = ArrowEffects::GetYOffset(pPlayerState, + 0, + fLastBeatToDraw, + fPeakYOffset, + bIsPastPeakYOffset, + true); if (bBoomerang && !bIsPastPeakYOffset) fLastBeatToDraw += fSearchDistance; @@ -677,12 +675,12 @@ FindDisplayedBeats(const PlayerState* pPlayerState, for (auto i = 0; i < NUM_ITERATIONS; i++) { bool bIsPastPeakYOffset; float fPeakYOffset; - auto fYOffset = ArrowEffects::GetYOffset(pPlayerState, - 0, - fFirstBeatToDraw, - fPeakYOffset, - bIsPastPeakYOffset, - true); + const auto fYOffset = ArrowEffects::GetYOffset(pPlayerState, + 0, + fFirstBeatToDraw, + fPeakYOffset, + bIsPastPeakYOffset, + true); if (bBoomerang && !bIsPastPeakYOffset) fFirstBeatToDraw -= fSearchDistance; @@ -716,7 +714,7 @@ NoteField::CalcPixelsBeforeAndAfterTargets() static_cast(m_iDrawDistanceAfterTargetsPixels); // HACK: If boomerang and centered are on, then we want to draw much // earlier so that the notes don't pop on screen. - auto centered_times_boomerang = + const auto centered_times_boomerang = curr_options.m_fScrolls[PlayerOptions::SCROLL_CENTERED] * curr_options.m_fAccels[PlayerOptions::ACCEL_BOOMERANG]; m_FieldRenderArgs.draw_pixels_after_targets += static_cast( @@ -739,8 +737,6 @@ NoteField::DrawPrimitives() if (!this->GetVisible() || !GAMESTATE->m_pCurSong) return; - // LOG->Trace( "NoteField::DrawPrimitives()" ); - // This should be filled in on the first update. ASSERT(m_pCurDisplay != NULL); @@ -765,7 +761,7 @@ NoteField::DrawPrimitives() &m_pPlayerState->m_PlayerOptions.GetCurrent()); CalcPixelsBeforeAndAfterTargets(); - auto cur = m_pCurDisplay; + auto* cur = m_pCurDisplay; FindDisplayedBeats( m_pPlayerState, @@ -791,7 +787,7 @@ NoteField::DrawPrimitives() cur->m_ReceptorArrowRow.Draw(); } - auto pTiming = &m_pPlayerState->GetDisplayedTiming(); + const auto* const pTiming = &m_pPlayerState->GetDisplayedTiming(); const vector* segs[NUM_TimingSegmentType]; FOREACH_TimingSegmentType(tst) segs[tst] = @@ -804,21 +800,22 @@ NoteField::DrawPrimitives() auto iMeasureIndex = 0; for (i = 0; i < tSigs.size(); i++) { const TimeSignatureSegment* ts = ToTimeSignature(tSigs[i]); - auto iSegmentEndRow = (i + 1 == tSigs.size()) - ? m_FieldRenderArgs.last_row - : tSigs[i + 1]->GetRow(); + const auto iSegmentEndRow = (i + 1 == tSigs.size()) + ? m_FieldRenderArgs.last_row + : tSigs[i + 1]->GetRow(); // beat bars every 16th note - auto iDrawBeatBarsEveryRows = + const auto iDrawBeatBarsEveryRows = BeatToNoteRow((static_cast(ts->GetDen())) / 4) / 4; // In 4/4, every 16th beat bar is a measure - auto iMeasureBarFrequency = ts->GetNum() * 4; + const auto iMeasureBarFrequency = ts->GetNum() * 4; auto iBeatBarsDrawn = 0; for (auto j = ts->GetRow(); j < iSegmentEndRow; j += iDrawBeatBarsEveryRows) { - auto bMeasureBar = iBeatBarsDrawn % iMeasureBarFrequency == 0; + const auto bMeasureBar = + iBeatBarsDrawn % iMeasureBarFrequency == 0; auto type = quarter_beat; if (bMeasureBar) type = measure; @@ -826,7 +823,7 @@ NoteField::DrawPrimitives() type = beat; else if (iBeatBarsDrawn % 2 == 0) type = half_beat; - auto fBeat = NoteRowToBeat(j); + const auto fBeat = NoteRowToBeat(j); if (IS_ON_SCREEN(fBeat)) { DrawBeatBar(fBeat, type, iMeasureIndex); @@ -843,7 +840,8 @@ NoteField::DrawPrimitives() // draw. Draw the arrows in order of column. This minimizes texture switches // and lets us draw in big batches. - auto pStyle = GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); + const auto* pStyle = + GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); ASSERT_M(m_pNoteData->GetNumTracks() == GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber) ->m_iColsPerPlayer, @@ -915,7 +913,7 @@ get_returned_column(Lua* L, PlayerNumber pn, int index, int& col) { if (lua_isnumber(L, index) != 0) { // 1-indexed columns in lua - auto tmpcol = static_cast(lua_tonumber(L, index)) - 1; + const auto tmpcol = static_cast(lua_tonumber(L, index)) - 1; if (tmpcol < 0 || tmpcol >= GAMESTATE->GetCurrentStyle(pn)->m_iColsPerPlayer) { LuaHelpers::ReportScriptErrorFmt( @@ -948,7 +946,7 @@ get_returned_bright(Lua* L, int index, bool& bright) } void -NoteField::Step(int col, TapNoteScore score, bool from_lua) +NoteField::Step(int col, TapNoteScore score, bool from_lua) const { OPEN_CALLBACK_BLOCK(m_StepCallback); PUSH_COLUMN; @@ -960,7 +958,7 @@ NoteField::Step(int col, TapNoteScore score, bool from_lua) m_pCurDisplay->m_ReceptorArrowRow.Step(col, score); } void -NoteField::SetPressed(int col, bool from_lua) +NoteField::SetPressed(int col, bool from_lua) const { OPEN_CALLBACK_BLOCK(m_SetPressedCallback); PUSH_COLUMN; @@ -970,7 +968,10 @@ NoteField::SetPressed(int col, bool from_lua) m_pCurDisplay->m_ReceptorArrowRow.SetPressed(col); } void -NoteField::DidTapNote(int col, TapNoteScore score, bool bright, bool from_lua) +NoteField::DidTapNote(int col, + TapNoteScore score, + bool bright, + bool from_lua) const { OPEN_CALLBACK_BLOCK(m_DidTapNoteCallback); PUSH_COLUMN; @@ -984,7 +985,10 @@ NoteField::DidTapNote(int col, TapNoteScore score, bool bright, bool from_lua) m_pCurDisplay->m_GhostArrowRow.DidTapNote(col, score, bright); } void -NoteField::DidHoldNote(int col, HoldNoteScore score, bool bright, bool from_lua) +NoteField::DidHoldNote(int col, + HoldNoteScore score, + bool bright, + bool from_lua) const { OPEN_CALLBACK_BLOCK(m_DidHoldNoteCallback); PUSH_COLUMN; @@ -1045,7 +1049,7 @@ class LunaNoteField : public Luna static int check_column(lua_State* L, int index, PlayerNumber pn) { // 1-indexed columns in lua - auto col = IArg(1) - 1; + const auto col = IArg(1) - 1; if (col < 0 || col >= GAMESTATE->GetCurrentStyle(pn)->m_iColsPerPlayer) { luaL_error(L, @@ -1058,33 +1062,37 @@ class LunaNoteField : public Luna static int step(T* p, lua_State* L) { - auto col = check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); - auto tns = Enum::Check(L, 2); + const auto col = + check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); + const auto tns = Enum::Check(L, 2); p->Step(col, tns, true); return 0; } static int set_pressed(T* p, lua_State* L) { - auto col = check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); + const auto col = + check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); p->SetPressed(col, true); return 0; } static int did_tap_note(T* p, lua_State* L) { - auto col = check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); - auto tns = Enum::Check(L, 2); - auto bright = BArg(3); + const auto col = + check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); + const auto tns = Enum::Check(L, 2); + const auto bright = BArg(3); p->DidTapNote(col, tns, bright, true); return 0; } static int did_hold_note(T* p, lua_State* L) { - auto col = check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); - auto hns = Enum::Check(L, 2); - auto bright = BArg(3); + const auto col = + check_column(L, 1, p->GetPlayerState()->m_PlayerNumber); + const auto hns = Enum::Check(L, 2); + const auto bright = BArg(3); p->DidHoldNote(col, hns, bright, true); return 0; } diff --git a/src/Etterna/Actor/Gameplay/NoteField.h b/src/Etterna/Actor/Gameplay/NoteField.h index 35bb8d2cd1..64aab33a28 100644 --- a/src/Etterna/Actor/Gameplay/NoteField.h +++ b/src/Etterna/Actor/Gameplay/NoteField.h @@ -11,7 +11,7 @@ class NoteData; /** @brief An Actor that renders NoteData. */ -class NoteField : public ActorFrame +class NoteField final : public ActorFrame { public: NoteField(); @@ -21,13 +21,13 @@ class NoteField : public ActorFrame void CalcPixelsBeforeAndAfterTargets(); void DrawBoardPrimitive(); - virtual void Init(const PlayerState* pPlayerState, - float fYReverseOffsetPixels, - bool use_states_zoom = true); - virtual void Load(const NoteData* pNoteData, - int iDrawDistanceAfterTargetsPixels, - int iDrawDistanceBeforeTargetsPixels); - virtual void Unload(); + void Init(const PlayerState* pPlayerState, + float fYReverseOffsetPixels, + bool use_states_zoom = true); + void Load(const NoteData* pNoteData, + int iDrawDistanceAfterTargetsPixels, + int iDrawDistanceBeforeTargetsPixels); + void Unload(); void ensure_note_displays_have_skin(); void InitColumnRenderers(); @@ -39,16 +39,16 @@ class NoteField : public ActorFrame void CacheAllUsedNoteSkins(); void FadeToFail(); - void Step(int col, TapNoteScore score, bool from_lua = false); - void SetPressed(int col, bool from_lua = false); + void Step(int col, TapNoteScore score, bool from_lua = false) const; + void SetPressed(int col, bool from_lua = false) const; void DidTapNote(int col, TapNoteScore score, bool bright, - bool from_lua = false); + bool from_lua = false) const; void DidHoldNote(int col, HoldNoteScore score, bool bright, - bool from_lua = false); + bool from_lua = false) const; void PushSelf(lua_State* L) override; @@ -60,13 +60,16 @@ class NoteField : public ActorFrame LuaReference m_DidTapNoteCallback; LuaReference m_DidHoldNoteCallback; - const PlayerState* GetPlayerState() const { return m_pPlayerState; } + [[nodiscard]] const PlayerState* GetPlayerState() const + { + return m_pPlayerState; + } int m_iBeginMarker, m_iEndMarker; // only used with MODE_EDIT // m_ColumnRenderers belongs in the protected section, but it's here in // public so that the Lua API can access it. -Kyz - vector m_ColumnRenderers; + std::vector m_ColumnRenderers; protected: void CacheNoteSkin(const std::string& sNoteSkin, PlayerNumber pn); @@ -101,7 +104,7 @@ class NoteField : public ActorFrame void DrawBGChangeText(float beat, const std::string& new_bg_name, const RageColor& glow); - float GetWidth() const; + [[nodiscard]] float GetWidth() const; const NoteData* m_pNoteData; @@ -119,7 +122,12 @@ class NoteField : public ActorFrame NoteDisplay* display; ReceptorArrowRow m_ReceptorArrowRow; GhostArrowRow m_GhostArrowRow; - NoteDisplayCols(int iNumCols) { display = new NoteDisplay[iNumCols]; } + explicit NoteDisplayCols(int iNumCols) + : m_GhostArrowRow() + { + display = new NoteDisplay[iNumCols]; + } + ~NoteDisplayCols() { delete[] display; } }; diff --git a/src/Etterna/Actor/Gameplay/Player.cpp b/src/Etterna/Actor/Gameplay/Player.cpp index edfd6c3d2b..dabe705f68 100644 --- a/src/Etterna/Actor/Gameplay/Player.cpp +++ b/src/Etterna/Actor/Gameplay/Player.cpp @@ -209,22 +209,22 @@ Player::Player(NoteData& nd, bool bVisibleParts) m_bLoaded = false; m_inside_lua_set_life = false; - m_pPlayerState = NULL; - m_pPlayerStageStats = NULL; + m_pPlayerState = nullptr; + m_pPlayerStageStats = nullptr; m_fNoteFieldHeight = 0; - m_pLifeMeter = NULL; - m_pPrimaryScoreKeeper = NULL; - m_pIterNeedsTapJudging = NULL; - m_pIterNeedsHoldJudging = NULL; - m_pIterUncrossedRows = NULL; - m_pIterUnjudgedRows = NULL; - m_pIterUnjudgedMineRows = NULL; + m_pLifeMeter = nullptr; + m_pPrimaryScoreKeeper = nullptr; + m_pIterNeedsTapJudging = nullptr; + m_pIterNeedsHoldJudging = nullptr; + m_pIterUncrossedRows = nullptr; + m_pIterUnjudgedRows = nullptr; + m_pIterUnjudgedMineRows = nullptr; totalwifescore = 0; - m_Timing = NULL; - m_pActorWithJudgmentPosition = NULL; - m_pActorWithComboPosition = NULL; + m_Timing = nullptr; + m_pActorWithJudgmentPosition = nullptr; + m_pActorWithComboPosition = nullptr; m_LastTapNoteScore = TNS_None; m_iFirstUncrossedRow = -1; m_iLastSeenCombo = 0; @@ -234,7 +234,7 @@ Player::Player(NoteData& nd, bool bVisibleParts) m_bPaused = false; m_bDelay = false; - m_pNoteField = NULL; + m_pNoteField = nullptr; if (bVisibleParts) { m_pNoteField = new NoteField; m_pNoteField->SetName("NoteField"); @@ -286,7 +286,7 @@ Player::Init(const std::string& sType, { // Init judgment positions - bool bPlayerUsingBothSides = + const auto bPlayerUsingBothSides = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber) ->GetUsesCenteredArrows(); Actor TempJudgment; @@ -297,11 +297,11 @@ Player::Init(const std::string& sType, TempCombo.SetName("Combo"); ActorUtil::LoadCommand(TempCombo, sType, "Transform"); - int iEnabledPlayerIndex = 0; - int iNumEnabledPlayers = 1; + const auto iEnabledPlayerIndex = 0; + const auto iNumEnabledPlayers = 1; - for (int i = 0; i < NUM_REVERSE; i++) { - for (int j = 0; j < NUM_CENTERED; j++) { + for (auto i = 0; i < NUM_REVERSE; i++) { + for (auto j = 0; j < NUM_CENTERED; j++) { Message msg("Transform"); msg.SetParam("Player", pPlayerState->m_PlayerNumber); msg.SetParam("MultiPlayer", pPlayerState->m_mp); @@ -332,7 +332,7 @@ Player::Init(const std::string& sType, // set initial life if ((m_pLifeMeter != nullptr) && (m_pPlayerStageStats != nullptr)) { - float fLife = m_pLifeMeter->GetLife(); + const auto fLife = m_pLifeMeter->GetLife(); m_pPlayerStageStats->SetLifeRecordAt( fLife, STATSMAN->m_CurStageStats.m_fStepsSeconds); // m_pPlayerStageStats->SetWifeRecordAt( 1.f, @@ -340,7 +340,7 @@ Player::Init(const std::string& sType, } // TODO: Remove use of PlayerNumber. - PlayerNumber pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; m_pPlayerState->SetNumCols( GAMESTATE->GetCurrentStyle(pn)->m_iColsPerPlayer); @@ -393,7 +393,7 @@ Player::Init(const std::string& sType, m_pPlayerState->m_fReadBPM = fMaxBPM; } - float fBalance = GameSoundManager::GetPlayerBalance(pn); + const auto fBalance = GameSoundManager::GetPlayerBalance(pn); m_soundMine.SetProperty("Pan", fBalance); if (HasVisibleParts()) { @@ -415,8 +415,8 @@ Player::Init(const std::string& sType, m_pActorWithJudgmentPosition = &*m_sprJudgment; this->AddChild(m_sprJudgment); } else { - m_pActorWithComboPosition = NULL; - m_pActorWithJudgmentPosition = NULL; + m_pActorWithComboPosition = nullptr; + m_pActorWithJudgmentPosition = nullptr; } // Load HoldJudgments @@ -426,11 +426,11 @@ Player::Init(const std::string& sType, lastHoldHeadsSeconds.resize( GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer); - for (int i = 0; + for (auto i = 0; i < GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer; ++i) { - m_vpHoldJudgment[i] = NULL; + m_vpHoldJudgment[i] = nullptr; // set this reasonably negative because if we don't, the first row of // the song doesn't get judged // and also it gets changed back to a realistic number after a hold is @@ -439,7 +439,7 @@ Player::Init(const std::string& sType, } if (HasVisibleParts()) { - for (int i = 0; + for (auto i = 0; i < GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer; ++i) { @@ -508,14 +508,14 @@ GenerateCacheDataStructure(PlayerState* pPlayerState, const NoteData& notes) pPlayerState->m_CacheDisplayedBeat.clear(); - const vector vScrolls = + const auto vScrolls = pPlayerState->GetDisplayedTiming().GetTimingSegments(SEGMENT_SCROLL); - float displayedBeat = 0.0f; - float lastRealBeat = 0.0f; - float lastRatio = 1.0f; - for (unsigned i = 0; i < vScrolls.size(); i++) { - ScrollSegment* seg = ToScroll(vScrolls[i]); + auto displayedBeat = 0.0f; + auto lastRealBeat = 0.0f; + auto lastRatio = 1.0f; + for (auto vScroll : vScrolls) { + auto* const seg = ToScroll(vScroll); displayedBeat += (seg->GetBeat() - lastRealBeat) * lastRatio; lastRealBeat = seg->GetBeat(); lastRatio = seg->GetRatio(); @@ -527,11 +527,10 @@ GenerateCacheDataStructure(PlayerState* pPlayerState, const NoteData& notes) pPlayerState->m_CacheNoteStat.clear(); - NoteData::all_tracks_const_iterator it = - notes.GetTapNoteRangeAllTracks(0, MAX_NOTE_ROW, true); - int count = 0, lastCount = 0; + auto it = notes.GetTapNoteRangeAllTracks(0, MAX_NOTE_ROW, true); + auto count = 0, lastCount = 0; for (; !it.IsAtEnd(); ++it) { - for (int t = 0; t < notes.GetNumTracks(); t++) { + for (auto t = 0; t < notes.GetNumTracks(); t++) { if (notes.GetTapNote(t, it.Row()) != TAP_EMPTY) count++; } @@ -551,7 +550,7 @@ Player::Load() m_LastTapNoteScore = TNS_None; // The editor can start playing in the middle of the song. - const int iNoteRow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); + const auto iNoteRow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); m_iFirstUncrossedRow = iNoteRow - 1; m_pJudgedRows->Reset(iNoteRow); @@ -568,7 +567,7 @@ Player::Load() // Mina garbage - Mina m_Timing = GAMESTATE->m_pCurSteps->GetTimingData(); m_Timing->NegStopAndBPMCheck(); - int lastRow = m_NoteData.GetLastRow(); + const auto lastRow = m_NoteData.GetLastRow(); m_Timing->BuildAndGetEtar(lastRow); totalwifescore = m_NoteData.WifeTotalScoreCalc(m_Timing, 0, 1073741824); @@ -577,7 +576,7 @@ Player::Load() m_NoteData.LogNonEmptyRows(m_Timing); nerv = m_NoteData.GetNonEmptyRowVector(); - const vector& etaner = m_Timing->BuildAndGetEtaner(nerv); + const auto& etaner = m_Timing->BuildAndGetEtaner(nerv); if (m_pPlayerStageStats != nullptr) m_pPlayerStageStats->serializednd = m_NoteData.SerializeNoteData(etaner); @@ -627,10 +626,12 @@ Player::Load() // Generate some cache data structure. GenerateCacheDataStructure(m_pPlayerState, m_NoteData); - int iDrawDistanceAfterTargetsPixels = DRAW_DISTANCE_AFTER_TARGET_PIXELS; - int iDrawDistanceBeforeTargetsPixels = DRAW_DISTANCE_BEFORE_TARGET_PIXELS; + const int iDrawDistanceAfterTargetsPixels = + DRAW_DISTANCE_AFTER_TARGET_PIXELS; + const int iDrawDistanceBeforeTargetsPixels = + DRAW_DISTANCE_BEFORE_TARGET_PIXELS; - float fNoteFieldMiddle = + const auto fNoteFieldMiddle = (GRAY_ARROWS_Y_STANDARD + GRAY_ARROWS_Y_REVERSE) / 2; if (m_pNoteField != nullptr) { @@ -649,17 +650,17 @@ Player::Load() // have to load separate copies to set player fade: always make a copy, and // set the fade on the copy. const Song* pSong = GAMESTATE->m_pCurSong; - std::string sSongDir = pSong->GetSongDir(); + const auto sSongDir = pSong->GetSongDir(); m_vKeysounds.resize(pSong->m_vsKeysoundFile.size()); // parameters are invalid somehow... -aj RageSoundLoadParams SoundParams; SoundParams.m_bSupportPan = true; - float fBalance = GameSoundManager::GetPlayerBalance(PLAYER_1); + const auto fBalance = GameSoundManager::GetPlayerBalance(PLAYER_1); for (unsigned i = 0; i < m_vKeysounds.size(); i++) { - std::string sKeysoundFilePath = sSongDir + pSong->m_vsKeysoundFile[i]; - RageSound& sound = m_vKeysounds[i]; + auto sKeysoundFilePath = sSongDir + pSong->m_vsKeysoundFile[i]; + auto& sound = m_vKeysounds[i]; if (sound.GetLoadedFilePath() != sKeysoundFilePath) sound.Load(sKeysoundFilePath, true, &SoundParams); sound.SetProperty("Pan", fBalance); @@ -699,7 +700,7 @@ Player::Reload() m_LastTapNoteScore = TNS_None; - const int iNoteRow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); + const auto iNoteRow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); m_iFirstUncrossedRow = iNoteRow - 1; m_pJudgedRows->Reset(iNoteRow); @@ -750,9 +751,10 @@ Player::Reload() } void -Player::SendComboMessages(unsigned int iOldCombo, unsigned int iOldMissCombo) +Player::SendComboMessages(unsigned int iOldCombo, + unsigned int iOldMissCombo) const { - const unsigned int iCurCombo = + const auto iCurCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; if (iOldCombo > static_cast(COMBO_STOPPED_AT) && iCurCombo < static_cast(COMBO_STOPPED_AT)) { @@ -783,30 +785,32 @@ Player::UpdateVisibleParts() if (!HasVisibleParts()) return; - float fMiniPercent = m_pPlayerState->m_PlayerOptions.GetCurrent() - .m_fEffects[PlayerOptions::EFFECT_MINI]; - float fTinyPercent = m_pPlayerState->m_PlayerOptions.GetCurrent() - .m_fEffects[PlayerOptions::EFFECT_TINY]; - float fJudgmentZoom = min(powf(0.5f, fMiniPercent + fTinyPercent), 1.0f); + const auto fMiniPercent = m_pPlayerState->m_PlayerOptions.GetCurrent() + .m_fEffects[PlayerOptions::EFFECT_MINI]; + const auto fTinyPercent = m_pPlayerState->m_PlayerOptions.GetCurrent() + .m_fEffects[PlayerOptions::EFFECT_TINY]; + const auto fJudgmentZoom = + min(powf(0.5f, fMiniPercent + fTinyPercent), 1.0f); // Update Y positions { - for (int c = 0; + for (auto c = 0; c < GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer; c++) { - float fPercentReverse = m_pPlayerState->m_PlayerOptions.GetCurrent() - .GetReversePercentForColumn(c); - float fHoldJudgeYPos = SCALE(fPercentReverse, - 0.f, - 1.f, - HOLD_JUDGMENT_Y_STANDARD, - HOLD_JUDGMENT_Y_REVERSE); + const auto fPercentReverse = + m_pPlayerState->m_PlayerOptions.GetCurrent() + .GetReversePercentForColumn(c); + const auto fHoldJudgeYPos = SCALE(fPercentReverse, + 0.f, + 1.f, + HOLD_JUDGMENT_Y_STANDARD, + HOLD_JUDGMENT_Y_REVERSE); // float fGrayYPos = SCALE( fPercentReverse, 0.f, 1.f, // GRAY_ARROWS_Y_STANDARD, GRAY_ARROWS_Y_REVERSE ); - float fX = ArrowEffects::GetXPos(m_pPlayerState, c, 0); - const float fZ = ArrowEffects::GetZPos(c, 0); + auto fX = ArrowEffects::GetXPos(m_pPlayerState, c, 0); + const auto fZ = ArrowEffects::GetZPos(c, 0); fX *= (1 - fMiniPercent * 0.5f); m_vpHoldJudgment[c]->SetX(fX); @@ -820,39 +824,39 @@ Player::UpdateVisibleParts() // if( m_pNoteField ) // m_pNoteField->SetY( fGrayYPos ); - const bool bReverse = + const auto bReverse = m_pPlayerState->m_PlayerOptions.GetCurrent().GetReversePercentForColumn( 0) == 1; - float fPercentCentered = m_pPlayerState->m_PlayerOptions.GetCurrent() - .m_fScrolls[PlayerOptions::SCROLL_CENTERED]; + const auto fPercentCentered = m_pPlayerState->m_PlayerOptions.GetCurrent() + .m_fScrolls[PlayerOptions::SCROLL_CENTERED]; - if (m_pActorWithJudgmentPosition != NULL) { - const Actor::TweenState& ts1 = m_tsJudgment[bReverse ? 1 : 0][0]; - const Actor::TweenState& ts2 = m_tsJudgment[bReverse ? 1 : 0][1]; - Actor::TweenState::MakeWeightedAverage( + if (m_pActorWithJudgmentPosition != nullptr) { + const auto& ts1 = m_tsJudgment[bReverse ? 1 : 0][0]; + const auto& ts2 = m_tsJudgment[bReverse ? 1 : 0][1]; + TweenState::MakeWeightedAverage( m_pActorWithJudgmentPosition->DestTweenState(), ts1, ts2, fPercentCentered); } - if (m_pActorWithComboPosition != NULL) { - const Actor::TweenState& ts1 = m_tsCombo[bReverse ? 1 : 0][0]; - const Actor::TweenState& ts2 = m_tsCombo[bReverse ? 1 : 0][1]; - Actor::TweenState::MakeWeightedAverage( + if (m_pActorWithComboPosition != nullptr) { + const auto& ts1 = m_tsCombo[bReverse ? 1 : 0][0]; + const auto& ts2 = m_tsCombo[bReverse ? 1 : 0][1]; + TweenState::MakeWeightedAverage( m_pActorWithComboPosition->DestTweenState(), ts1, ts2, fPercentCentered); } - float fNoteFieldZoom = 1 - fMiniPercent * 0.5f; + const auto fNoteFieldZoom = 1 - fMiniPercent * 0.5f; if (m_pNoteField) m_pNoteField->SetZoom(fNoteFieldZoom); - if (m_pActorWithJudgmentPosition != NULL) + if (m_pActorWithJudgmentPosition != nullptr) m_pActorWithJudgmentPosition->SetZoom( m_pActorWithJudgmentPosition->GetZoom() * fJudgmentZoom); - if (m_pActorWithComboPosition != NULL) + if (m_pActorWithComboPosition != nullptr) m_pActorWithComboPosition->SetZoom( m_pActorWithComboPosition->GetZoom() * fJudgmentZoom); } @@ -860,12 +864,12 @@ Player::UpdateVisibleParts() void Player::UpdatePressedFlags() { - const int iNumCols = + const auto iNumCols = GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer; ASSERT_M(iNumCols <= MAX_COLS_PER_PLAYER, ssprintf("%i > %i", iNumCols, MAX_COLS_PER_PLAYER)); - for (int col = 0; col < iNumCols; ++col) { + for (auto col = 0; col < iNumCols; ++col) { ASSERT(m_pPlayerState != NULL); // TODO: Remove use of PlayerNumber. @@ -873,7 +877,7 @@ Player::UpdatePressedFlags() GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->StyleInputToGameInput(col, m_pPlayerState->m_PlayerNumber, GameI); - bool bIsHoldingButton = INPUTMAPPER->IsBeingPressed(GameI); + const auto bIsHoldingButton = INPUTMAPPER->IsBeingPressed(GameI); // TODO: Make this work for non-human-controlled players if (bIsHoldingButton && m_pPlayerState->m_PlayerController == PC_HUMAN) @@ -886,17 +890,17 @@ void Player::UpdateHoldsAndRolls(float fDeltaTime, const std::chrono::steady_clock::time_point& now) { - const float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; - const int iSongRow = BeatToNoteRow(fSongBeat); + const auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + const auto iSongRow = BeatToNoteRow(fSongBeat); // handle Autoplay for rolls if (m_pPlayerState->m_PlayerController != PC_HUMAN) { - for (int iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { + for (auto iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { // TODO: Make the CPU miss sometimes. int iHeadRow; if (!m_NoteData.IsHoldNoteAtRow(iTrack, iSongRow, &iHeadRow)) iHeadRow = iSongRow; - const TapNote& tn = m_NoteData.GetTapNote(iTrack, iHeadRow); + const auto& tn = m_NoteData.GetTapNote(iTrack, iHeadRow); if (tn.type != TapNoteType_HoldHead || tn.subType != TapNoteSubType_Roll) continue; @@ -923,22 +927,22 @@ Player::UpdateHoldsAndRolls(float fDeltaTime, // Fast forward to the first that needs hold judging. { - NoteData::all_tracks_iterator& iter = *m_pIterNeedsHoldJudging; + auto& iter = *m_pIterNeedsHoldJudging; while (!iter.IsAtEnd() && iter.Row() <= iSongRow && !NeedsHoldJudging(*iter)) ++iter; } vector vHoldNotesToGradeTogether; - int iRowOfLastHoldNote = -1; - NoteData::all_tracks_iterator iter = *m_pIterNeedsHoldJudging; // copy + auto iRowOfLastHoldNote = -1; + auto iter = *m_pIterNeedsHoldJudging; // copy for (; !iter.IsAtEnd() && iter.Row() <= iSongRow; ++iter) { - TapNote& tn = *iter; + auto& tn = *iter; if (tn.type != TapNoteType_HoldHead) continue; - int iTrack = iter.Track(); - int iRow = iter.Row(); + const auto iTrack = iter.Track(); + const auto iRow = iter.Row(); TrackRowTapNote trtn = { iTrack, iRow, &tn }; // Set last hold head seconds stuff @@ -964,8 +968,6 @@ Player::UpdateHoldsAndRolls(float fDeltaTime, } if (!vHoldNotesToGradeTogether.empty()) { - // LOG->Trace( ssprintf("UpdateHoldNotes; %i != %i || !judge - // holds on same row together",iRow,iRowOfLastHoldNote) ); UpdateHoldNotes( iSongRow, fDeltaTime, vHoldNotesToGradeTogether); vHoldNotesToGradeTogether.clear(); @@ -975,8 +977,6 @@ Player::UpdateHoldsAndRolls(float fDeltaTime, } if (!vHoldNotesToGradeTogether.empty()) { - // LOG->Trace("UpdateHoldNotes since - // !vHoldNotesToGradeTogether.empty()"); UpdateHoldNotes(iSongRow, fDeltaTime, vHoldNotesToGradeTogether); vHoldNotesToGradeTogether.clear(); } @@ -986,7 +986,7 @@ Player::UpdateHoldsAndRolls(float fDeltaTime, void Player::UpdateCrossedRows(const std::chrono::steady_clock::time_point& now) { - const int iRowNow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); + const auto iRowNow = BeatToNoteRow(m_pPlayerState->m_Position.m_fSongBeat); if (iRowNow >= 0) { if (GAMESTATE->IsPlayerEnabled(m_pPlayerState)) { if (m_pPlayerState->m_Position.m_bDelay) { @@ -1016,7 +1016,7 @@ Player::Update(float fDeltaTime) // LOG->Trace( "Player::Update(%f)", fDeltaTime ); - if (GAMESTATE->m_pCurSong == NULL) + if (GAMESTATE->m_pCurSong == nullptr) return; ActorFrame::Update(fDeltaTime); @@ -1029,7 +1029,7 @@ Player::Update(float fDeltaTime) * to user actions in this mode, this doesn't degrade gameplay. Run 4 * players per update, which means 12 Players in 3-difficulty mode. */ - static int iCycle = 0; + static auto iCycle = 0; iCycle = (iCycle + 1) % 8; if ((m_pPlayerState->m_mp % 8) != iCycle) @@ -1077,15 +1077,15 @@ Player::UpdateHoldNotes(int iSongRow, LOG->Trace( ssprintf("song row %i, deltaTime = %f",iSongRow,fDeltaTime) ); */ - int iStartRow = vTN[0].iRow; - int iMaxEndRow = INT_MIN; - int iFirstTrackWithMaxEndRow = -1; + const auto iStartRow = vTN[0].iRow; + auto iMaxEndRow = INT_MIN; + auto iFirstTrackWithMaxEndRow = -1; - TapNoteSubType subType = TapNoteSubType_Invalid; + auto subType = TapNoteSubType_Invalid; for (auto& trtn : vTN) { - int iTrack = trtn.iTrack; + const auto iTrack = trtn.iTrack; ASSERT(iStartRow == trtn.iRow); - int iEndRow = iStartRow + trtn.pTN->iDuration; + const auto iEndRow = iStartRow + trtn.pTN->iDuration; if (subType == TapNoteSubType_Invalid) subType = trtn.pTN->subType; @@ -1102,7 +1102,7 @@ Player::UpdateHoldNotes(int iSongRow, trtn.pTN->HoldResult.bHeld = false; trtn.pTN->HoldResult.bActive = false; - int iRow = trtn.iRow; + const auto iRow = trtn.iRow; // If the song beat is in the range of this hold: if (iRow <= iSongRow && iRow <= iMaxEndRow) { @@ -1112,16 +1112,16 @@ Player::UpdateHoldNotes(int iSongRow, } } - HoldNoteScore hns = vTN[0].pTN->HoldResult.hns; - float fLife = vTN[0].pTN->HoldResult.fLife; + auto hns = vTN[0].pTN->HoldResult.hns; + auto fLife = vTN[0].pTN->HoldResult.fLife; if (hns != HNS_None) // if this HoldNote already has a result { return; // we don't need to update the logic for this group } - bool bSteppedOnHead = true; - bool bHeadJudged = true; + auto bSteppedOnHead = true; + auto bHeadJudged = true; for (auto& trtn : vTN) { const auto& tns = trtn.pTN->result.tns; @@ -1154,7 +1154,7 @@ Player::UpdateHoldNotes(int iSongRow, bHeadJudged = true; } - bool bIsHoldingButton = true; + auto bIsHoldingButton = true; for (auto& trtn : vTN) { /*if this hold is already done, pretend it's always being pressed. fixes/masks the phantom hold issue. -FSX*/ @@ -1162,7 +1162,7 @@ Player::UpdateHoldNotes(int iSongRow, // causing ALL holds to be judged HNS_Held whether they were or not. if (!IMMEDIATE_HOLD_LET_GO || (iStartRow + trtn.pTN->iDuration) > iSongRow) { - int iTrack = trtn.iTrack; + const auto iTrack = trtn.iTrack; if (m_pPlayerState->m_PlayerController != PC_HUMAN) { // TODO: Make the CPU miss sometimes. @@ -1210,7 +1210,7 @@ Player::UpdateHoldNotes(int iSongRow, if (bInitiatedNote && bIsHoldingButton) { fLife = 1; } else { - auto window = m_bTickHolds ? TW_Checkpoint : TW_Hold; + const auto window = m_bTickHolds ? TW_Checkpoint : TW_Hold; fLife -= fDeltaTime / GetWindowSeconds(window); fLife = max(0, fLife); } @@ -1240,7 +1240,7 @@ Player::UpdateHoldNotes(int iSongRow, // TODO: Cap the active time passed to the score keeper to the actual // start time and end time of the hold. if (vTN[0].pTN->HoldResult.bActive) { - float fSecondsActiveSinceLastUpdate = + const auto fSecondsActiveSinceLastUpdate = fDeltaTime * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; if (m_pPrimaryScoreKeeper != nullptr) m_pPrimaryScoreKeeper->HandleHoldActiveSeconds( @@ -1262,7 +1262,7 @@ Player::UpdateHoldNotes(int iSongRow, // score hold notes that have passed if (iSongRow >= iMaxEndRow && bHeadJudged) { - bool bLetGoOfHoldNote = false; + auto bLetGoOfHoldNote = false; /* Score rolls that end with fLife == 0 as LetGo, even if * m_bTickHolds is on. Rolls don't have iCheckpointsMissed set, so, @@ -1281,8 +1281,8 @@ Player::UpdateHoldNotes(int iSongRow, if (m_bTickHolds && bAllowHoldCheckpoints) { // LOG->Trace("(hold checkpoints are allowed and enabled.)"); - int iCheckpointsHit = 0; - int iCheckpointsMissed = 0; + auto iCheckpointsHit = 0; + auto iCheckpointsMissed = 0; for (auto& v : vTN) { iCheckpointsHit += v.pTN->HoldResult.iCheckpointsHit; iCheckpointsMissed += v.pTN->HoldResult.iCheckpointsMissed; @@ -1301,13 +1301,13 @@ Player::UpdateHoldNotes(int iSongRow, if (!bLetGoOfHoldNote) { fLife = 1; hns = HNS_Held; - bool bBright = + const auto bBright = m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast(BRIGHT_GHOST_COMBO_THRESHOLD); if (m_pNoteField != nullptr) { for (auto& trtn : vTN) { - int iTrack = trtn.iTrack; + const auto iTrack = trtn.iTrack; m_pNoteField->DidHoldNote( iTrack, HNS_Held, bBright); // bright ghost flash } @@ -1324,7 +1324,7 @@ Player::UpdateHoldNotes(int iSongRow, } } - float fLifeFraction = fLife / 1; // haha im just gonna leave this here + const auto fLifeFraction = fLife / 1; // haha im just gonna leave this here // aren't keysounds broken anyway? for (auto& trtn : vTN) { @@ -1336,17 +1336,17 @@ Player::UpdateHoldNotes(int iSongRow, // before the preference works: otherwise, it causes problems on // holds. At least, that hapened on my Mac. -wolfman2000 - static Preference* pVolume = + static auto* pVolume = Preference::GetPreferenceByName("SoundVolume"); - if (pVolume != NULL) { - static float fVol = pVolume->Get(); + if (pVolume != nullptr) { + static auto fVol = pVolume->Get(); if (trtn.pTN->iKeysoundIndex >= 0 && trtn.pTN->iKeysoundIndex < static_cast(m_vKeysounds.size())) { - float factor = (trtn.pTN->subType == TapNoteSubType_Roll - ? 2.0f * fLifeFraction - : 10.0f * fLifeFraction - 8.5f); + auto factor = (trtn.pTN->subType == TapNoteSubType_Roll + ? 2.0f * fLifeFraction + : 10.0f * fLifeFraction - 8.5f); m_vKeysounds[trtn.pTN->iKeysoundIndex].SetProperty( "Volume", max(0.0f, min(1.0f, factor)) * fVol); } @@ -1357,7 +1357,7 @@ Player::UpdateHoldNotes(int iSongRow, IncrementMissCombo(); if (hns != HNS_None) { - TapNote& tn = *vTN[0].pTN; + auto& tn = *vTN[0].pTN; SetHoldJudgment(tn, iFirstTrackWithMaxEndRow, iSongRow); HandleHoldScore(tn); } @@ -1367,21 +1367,20 @@ void Player::DrawPrimitives() { // TODO: Remove use of PlayerNumber. - PlayerNumber pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; if (pn != PLAYER_1) return; - bool draw_notefield = (m_pNoteField != nullptr); + const auto draw_notefield = (m_pNoteField != nullptr); - const PlayerOptions& curr_options = - m_pPlayerState->m_PlayerOptions.GetCurrent(); - float tilt = curr_options.m_fPerspectiveTilt; - float skew = curr_options.m_fSkew; - float mini = curr_options.m_fEffects[PlayerOptions::EFFECT_MINI]; - float center_y = + const auto& curr_options = m_pPlayerState->m_PlayerOptions.GetCurrent(); + const auto tilt = curr_options.m_fPerspectiveTilt; + const auto skew = curr_options.m_fSkew; + const auto mini = curr_options.m_fEffects[PlayerOptions::EFFECT_MINI]; + const auto center_y = GetY() + (GRAY_ARROWS_Y_STANDARD + GRAY_ARROWS_Y_REVERSE) / 2; - bool reverse = curr_options.GetReversePercentForColumn(0) > .5; + const auto reverse = curr_options.GetReversePercentForColumn(0) > .5; if (m_drawing_notefield_board) { // Ask the Notefield to draw its board primitive before everything @@ -1462,10 +1461,10 @@ Player::PlayerNoteFieldPositioner::PlayerNoteFieldPositioner(Player* p, : player(p) { player->PushPlayerMatrix(x, skew, center_y); - int reverse_mult = (reverse ? -1 : 1); + const auto reverse_mult = (reverse ? -1 : 1); original_y = player->m_pNoteField->GetY(); - float tilt_degrees = SCALE(tilt, -1.f, +1.f, +30, -30) * reverse_mult; - float zoom = SCALE(mini, 0.f, 1.f, 1.f, .5f); + const auto tilt_degrees = SCALE(tilt, -1.f, +1.f, +30, -30) * reverse_mult; + auto zoom = SCALE(mini, 0.f, 1.f, 1.f, .5f); // Something strange going on here. Notice that the range for tilt's // effect on y_offset goes to -45 when positive, but -20 when negative. // I don't know why it's done this why, simply preserving old behavior. @@ -1504,13 +1503,13 @@ Player::DrawHoldJudgments() if (m_pPlayerState->m_PlayerOptions.GetCurrent().m_fBlind > 0) return; - for (int c = 0; c < m_NoteData.GetNumTracks(); c++) + for (auto c = 0; c < m_NoteData.GetNumTracks(); c++) if (m_vpHoldJudgment[c]) m_vpHoldJudgment[c]->Draw(); } void -Player::ChangeLife(TapNoteScore tns) +Player::ChangeLife(TapNoteScore tns) const { if (m_pLifeMeter != nullptr) m_pLifeMeter->ChangeLife(tns); @@ -1519,7 +1518,7 @@ Player::ChangeLife(TapNoteScore tns) } void -Player::ChangeLife(HoldNoteScore hns, TapNoteScore tns) +Player::ChangeLife(HoldNoteScore hns, TapNoteScore tns) const { if (m_pLifeMeter != nullptr) m_pLifeMeter->ChangeLife(hns, tns); @@ -1528,7 +1527,7 @@ Player::ChangeLife(HoldNoteScore hns, TapNoteScore tns) } void -Player::ChangeLife(float delta) +Player::ChangeLife(float delta) const { // If ChangeLifeRecord is not called before the change, then the life // graph will show a gradual change from the time of the previous step @@ -1542,7 +1541,7 @@ Player::ChangeLife(float delta) } void -Player::SetLife(float value) +Player::SetLife(float value) const { // If ChangeLifeRecord is not called before the change, then the life // graph will show a gradual change from the time of the previous step @@ -1556,7 +1555,7 @@ Player::SetLife(float value) } void -Player::ChangeLifeRecord() +Player::ChangeLifeRecord() const { float fLife = -1; if (m_pLifeMeter != nullptr) { @@ -1569,7 +1568,7 @@ Player::ChangeLifeRecord() } void -Player::ChangeWifeRecord() +Player::ChangeWifeRecord() const { // Sets the life ... to the wife.... // That's not right. @@ -1598,7 +1597,7 @@ Player::GetClosestNoteDirectional(int col, // Is this the row we want? do { - const TapNote& tn = begin->second; + const auto& tn = begin->second; if (!m_Timing->IsJudgableAtRow(begin->first)) break; // unsure if autoKeysounds should be excluded. -Wolfman2000 @@ -1628,9 +1627,9 @@ Player::GetClosestNote(int col, bool bAllowOldMines) const { // Start at iIndexStartLookingAt and search outward. - int iNextIndex = GetClosestNoteDirectional( + const auto iNextIndex = GetClosestNoteDirectional( col, iNoteRow, iNoteRow + iMaxRowsAhead, bAllowGraded, true); - int iPrevIndex = GetClosestNoteDirectional( + const auto iPrevIndex = GetClosestNoteDirectional( col, iNoteRow - iMaxRowsBehind, iNoteRow, bAllowGraded, false); if (iNextIndex == -1 && iPrevIndex == -1) @@ -1641,15 +1640,15 @@ Player::GetClosestNote(int col, return iNextIndex; // Get the current time, previous time, and next time. - float fNoteTime = m_pPlayerState->m_Position.m_fMusicSeconds; - float fNextTime = m_Timing->WhereUAtBro(iNextIndex); - float fPrevTime = m_Timing->WhereUAtBro(iPrevIndex); + const auto fNoteTime = m_pPlayerState->m_Position.m_fMusicSeconds; + const auto fNextTime = m_Timing->WhereUAtBro(iNextIndex); + const auto fPrevTime = m_Timing->WhereUAtBro(iPrevIndex); // If we passed a mine, we can't hit it anymore. Literally. // So forget about them. // RIP Minebug 20xx - 2019 if (!bAllowOldMines) { - NoteData::iterator iter = m_NoteData.FindTapNote(col, iPrevIndex); + auto iter = m_NoteData.FindTapNote(col, iPrevIndex); if (iter != m_NoteData.end(col)) if ((&iter->second)->type == TapNoteType_Mine) return iNextIndex; @@ -1669,8 +1668,7 @@ Player::GetClosestNonEmptyRowDirectional(int iStartRow, bool bForward) const { if (bForward) { - NoteData::all_tracks_iterator iter = - m_NoteData.GetTapNoteRangeAllTracks(iStartRow, iEndRow); + auto iter = m_NoteData.GetTapNoteRangeAllTracks(iStartRow, iEndRow); while (!iter.IsAtEnd()) { if (NoteDataWithScoring::IsRowCompletelyJudged(m_NoteData, @@ -1685,7 +1683,7 @@ Player::GetClosestNonEmptyRowDirectional(int iStartRow, return iter.Row(); } } else { - NoteData::all_tracks_reverse_iterator iter = + auto iter = m_NoteData.GetTapNoteRangeAllTracksReverse(iStartRow, iEndRow); while (!iter.IsAtEnd()) { @@ -1709,9 +1707,9 @@ Player::GetClosestNonEmptyRow(int iNoteRow, bool bAllowGraded) const { // Start at iIndexStartLookingAt and search outward. - int iNextRow = GetClosestNonEmptyRowDirectional( + const auto iNextRow = GetClosestNonEmptyRowDirectional( iNoteRow, iNoteRow + iMaxRowsAhead, bAllowGraded, true); - int iPrevRow = GetClosestNonEmptyRowDirectional( + const auto iPrevRow = GetClosestNonEmptyRowDirectional( iNoteRow - iMaxRowsBehind, iNoteRow, bAllowGraded, false); if (iNextRow == -1 && iPrevRow == -1) @@ -1722,9 +1720,9 @@ Player::GetClosestNonEmptyRow(int iNoteRow, return iNextRow; // Get the current time, previous time, and next time. - float fNoteTime = m_pPlayerState->m_Position.m_fMusicSeconds; - float fNextTime = m_Timing->WhereUAtBro(iNextRow); - float fPrevTime = m_Timing->WhereUAtBro(iPrevRow); + const auto fNoteTime = m_pPlayerState->m_Position.m_fMusicSeconds; + const auto fNextTime = m_Timing->WhereUAtBro(iNextRow); + const auto fPrevTime = m_Timing->WhereUAtBro(iPrevRow); /* Figure out which row is closer. */ if (fabsf(fNoteTime - fNextTime) > fabsf(fNoteTime - fPrevTime)) @@ -1739,9 +1737,9 @@ Player::DoTapScoreNone() Message msg("ScoreNone"); MESSAGEMAN->Broadcast(msg); - const unsigned int iOldCombo = + const auto iOldCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iOldMissCombo = + const auto iOldMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; /* The only real way to tell if a mine has been scored is if it has @@ -1769,20 +1767,20 @@ void Player::ScoreAllActiveHoldsLetGo() { if (PENALIZE_TAP_SCORE_NONE) { - const float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; - const int iSongRow = BeatToNoteRow(fSongBeat); + const auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + const auto iSongRow = BeatToNoteRow(fSongBeat); // Score all active holds to NotHeld - for (int iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { + for (auto iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { // Since this is being called every frame, let's not check the // whole array every time. Instead, only check 1 beat back. Even // 1 is overkill. - const int iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); + const auto iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); NoteData::TrackMap::iterator begin, end; m_NoteData.GetTapNoteRangeInclusive( iTrack, iStartCheckingAt, iSongRow + 1, begin, end); for (; begin != end; ++begin) { - TapNote& tn = begin->second; + auto& tn = begin->second; if (tn.HoldResult.bActive) { tn.HoldResult.hns = HNS_LetGo; tn.HoldResult.fLife = 0; @@ -1806,7 +1804,7 @@ Player::PlayKeysound(const TapNote& tn, TapNoteScore score) // if the hold is not already held if (tn.HoldResult.hns == HNS_None) { // if the hold is already activated - TapNoteScore tns = tn.result.tns; + const auto tns = tn.result.tns; if (tns != TNS_None && tns != TNS_Miss && score == TNS_None) { // the sound must also be already playing if (m_vKeysounds[tn.iKeysoundIndex].IsPlaying()) { @@ -1818,9 +1816,9 @@ Player::PlayKeysound(const TapNote& tn, TapNoteScore score) } } m_vKeysounds[tn.iKeysoundIndex].Play(false); - static Preference* pVolume = + static auto* pVolume = Preference::GetPreferenceByName("SoundVolume"); - static float fVol = pVolume->Get(); + static auto fVol = pVolume->Get(); m_vKeysounds[tn.iKeysoundIndex].SetProperty("Volume", fVol); } } @@ -1828,7 +1826,7 @@ Player::PlayKeysound(const TapNote& tn, TapNoteScore score) void Player::AddNoteToReplayData(int col, const TapNote* pTN, - int RowOfOverlappingNoteOrRow) + int RowOfOverlappingNoteOrRow) const { m_pPlayerStageStats->m_vOffsetVector.emplace_back( pTN->result.fTapNoteOffset); @@ -1841,7 +1839,7 @@ Player::AddNoteToReplayData(int col, void Player::AddHoldToReplayData(int col, const TapNote* pTN, - int RowOfOverlappingNoteOrRow) + int RowOfOverlappingNoteOrRow) const { if (pTN->HoldResult.hns == HNS_Held) return; @@ -1864,36 +1862,36 @@ Player::Step(int col, // set your breakpoints somewhere after this block. std::chrono::duration stepDelta = std::chrono::steady_clock::now() - tm; - float stepAgo = stepDelta.count() - padStickSeconds; + auto stepAgo = stepDelta.count() - padStickSeconds; - const float fLastBeatUpdate = + const auto fLastBeatUpdate = m_pPlayerState->m_Position.m_LastBeatUpdate.Ago(); - const float fPositionSeconds = + const auto fPositionSeconds = m_pPlayerState->m_Position.m_fMusicSeconds - stepAgo; - const float fTimeSinceStep = stepAgo; + const auto fTimeSinceStep = stepAgo; // idk if this is the correct value for input logs but we'll use them to // test -mina ok this is 100% not the place to do this // m_pPlayerStageStats->InputData.emplace_back(fPositionSeconds); - float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; if (GAMESTATE->m_pCurSteps) fSongBeat = m_Timing->GetBeatFromElapsedTime(fPositionSeconds); - const int iSongRow = row == -1 ? BeatToNoteRow(fSongBeat) : row; + const auto iSongRow = row == -1 ? BeatToNoteRow(fSongBeat) : row; if (col != -1 && !bRelease) { // Update roll life // Let's not check the whole array every time. // Instead, only check 1 beat back. Even 1 is overkill. // Just update the life here and let Update judge the roll. - const int iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); + const auto iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); NoteData::TrackMap::iterator begin, end; m_NoteData.GetTapNoteRangeInclusive( col, iStartCheckingAt, iSongRow + 1, begin, end); for (; begin != end; ++begin) { - TapNote& tn = begin->second; + auto& tn = begin->second; if (tn.type != TapNoteType_HoldHead) continue; @@ -1905,20 +1903,20 @@ Player::Step(int col, break; } - const int iRow = begin->first; + const auto iRow = begin->first; - HoldNoteScore hns = tn.HoldResult.hns; + auto hns = tn.HoldResult.hns; if (hns != HNS_None) // if this HoldNote already has a result continue; // we don't need to update the logic for this one // if they got a bad score or haven't stepped on the // corresponding tap yet - const TapNoteScore tns = tn.result.tns; - bool bInitiatedNote = true; + const auto tns = tn.result.tns; + auto bInitiatedNote = true; if (REQUIRE_STEP_ON_HOLD_HEADS) bInitiatedNote = tns != TNS_None && tns != TNS_Miss; // did they step on the start? - const int iEndRow = iRow + tn.iDuration; + const auto iEndRow = iRow + tn.iDuration; if (bInitiatedNote && tn.HoldResult.fLife != 0) { /* This hold note is not judged and we stepped on its head. @@ -1941,7 +1939,7 @@ Player::Step(int col, m_pPlayerState->m_PlayerController != PC_AUTOPLAY) { IncrementCombo(); - bool bBright = m_pPlayerStageStats && + auto bBright = m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast( BRIGHT_GHOST_COMBO_THRESHOLD); @@ -1968,9 +1966,9 @@ Player::Step(int col, */ int iStepSearchRows; - static const float StepSearchDistance = GetMaxStepDistanceSeconds(); - int skipstart = nerv[10]; // this is not robust need to come up with - // something better later - Mina + static const auto StepSearchDistance = GetMaxStepDistanceSeconds(); + auto skipstart = nerv[10]; // this is not robust need to come up with + // something better later - Mina if (iSongRow < skipstart || iSongRow > static_cast(nerv.size()) - 10) { iStepSearchRows = @@ -1992,9 +1990,9 @@ Player::Step(int col, if (nerv[nervpos] < iSongRow && nervpos < nerv.size()) nervpos += 1; - size_t SearchIndexBehind = nervpos; - size_t SearchIndexAhead = nervpos; - float SearchBeginTime = m_Timing->WhereUAtBro(nerv[nervpos]); + auto SearchIndexBehind = nervpos; + auto SearchIndexAhead = nervpos; + auto SearchBeginTime = m_Timing->WhereUAtBro(nerv[nervpos]); while (SearchIndexBehind > 1 && SearchBeginTime - @@ -2008,8 +2006,8 @@ Player::Step(int col, StepSearchDistance) SearchIndexAhead += 1; - int MaxLookBehind = nerv[nervpos] - nerv[SearchIndexBehind]; - int MaxLookAhead = nerv[SearchIndexAhead] - nerv[nervpos]; + auto MaxLookBehind = nerv[nervpos] - nerv[SearchIndexBehind]; + auto MaxLookAhead = nerv[SearchIndexAhead] - nerv[nervpos]; if (nervpos > 0) iStepSearchRows = @@ -2017,21 +2015,21 @@ Player::Step(int col, } // calculate TapNoteScore - TapNoteScore score = TNS_None; + auto score = TNS_None; - int iRowOfOverlappingNoteOrRow = row; + auto iRowOfOverlappingNoteOrRow = row; if (row == -1 && col != -1) iRowOfOverlappingNoteOrRow = GetClosestNote( col, iSongRow, iStepSearchRows, iStepSearchRows, false, false); if (iRowOfOverlappingNoteOrRow != -1 && col != -1) { // compute the score for this hit - float fNoteOffset = 0.f; + auto fNoteOffset = 0.f; // only valid if - float fMusicSeconds = 0.f; + auto fMusicSeconds = 0.f; // we need this later if we are autosyncing - const float fStepBeat = NoteRowToBeat(iRowOfOverlappingNoteOrRow); - const float fStepSeconds = m_Timing->WhereUAtBro(fStepBeat); + const auto fStepBeat = NoteRowToBeat(iRowOfOverlappingNoteOrRow); + const auto fStepSeconds = m_Timing->WhereUAtBro(fStepBeat); if (row == -1) { // We actually stepped on the note this long ago: @@ -2040,7 +2038,7 @@ Player::Step(int col, /* GAMESTATE->m_fMusicSeconds is the music time as of * GAMESTATE->m_LastBeatUpdate. Figure out what the music time * is as of now. */ - const float fCurrentMusicSeconds = + const auto fCurrentMusicSeconds = m_pPlayerState->m_Position.m_fMusicSeconds + (fLastBeatUpdate * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate); @@ -2067,11 +2065,10 @@ Player::Step(int col, NOTESKIN->SetLastSeenColor( NoteTypeToString(GetNoteType(iRowOfOverlappingNoteOrRow))); - const float fSecondsFromExact = fabsf(fNoteOffset); + const auto fSecondsFromExact = fabsf(fNoteOffset); - TapNote* pTN = NULL; - NoteData::iterator iter = - m_NoteData.FindTapNote(col, iRowOfOverlappingNoteOrRow); + TapNote* pTN = nullptr; + auto iter = m_NoteData.FindTapNote(col, iRowOfOverlappingNoteOrRow); DEBUG_ASSERT(iter != m_NoteData.end(col)); pTN = &iter->second; @@ -2156,7 +2153,7 @@ Player::Step(int col, // The CPU hits a lot of mines. Only consider hitting // the first mine for a row. We know we're the first // mine if there are are no mines to the left of us. - for (int t = 0; t < col; t++) { + for (auto t = 0; t < col; t++) { if (m_NoteData.GetTapNote(t, iRowOfOverlappingNoteOrRow) .type == TapNoteType_Mine) // there's a mine to // the left of us @@ -2165,9 +2162,9 @@ Player::Step(int col, // The CPU hits a lot of mines. Make it less likely to // hit mines that don't have a tap note on the same row. - bool bTapsOnRow = m_NoteData.IsThereATapOrHoldHeadAtRow( + auto bTapsOnRow = m_NoteData.IsThereATapOrHoldHeadAtRow( iRowOfOverlappingNoteOrRow); - TapNoteScore get_to_avoid = bTapsOnRow ? TNS_W3 : TNS_W4; + auto get_to_avoid = bTapsOnRow ? TNS_W3 : TNS_W4; if (score >= get_to_avoid) return; // avoided @@ -2196,16 +2193,16 @@ Player::Step(int col, // TapNoteScore, so that they can logically match up with // the current timing windows. -aj { - float fWindowW1 = GetWindowSeconds(TW_W1); - float fWindowW2 = GetWindowSeconds(TW_W2); - float fWindowW3 = GetWindowSeconds(TW_W3); - float fWindowW4 = GetWindowSeconds(TW_W4); - float fWindowW5 = GetWindowSeconds(TW_W5); + auto fWindowW1 = GetWindowSeconds(TW_W1); + auto fWindowW2 = GetWindowSeconds(TW_W2); + auto fWindowW3 = GetWindowSeconds(TW_W3); + auto fWindowW4 = GetWindowSeconds(TW_W4); + auto fWindowW5 = GetWindowSeconds(TW_W5); // figure out overlap. - float fLowerBound = 0.0f; // negative upper limit - float fUpperBound = 0.0f; // positive lower limit - float fCompareWindow = 0.0f; // filled in here: + auto fLowerBound = 0.0f; // negative upper limit + auto fUpperBound = 0.0f; // positive lower limit + auto fCompareWindow = 0.0f; // filled in here: if (score == TNS_W4) { fLowerBound = -fWindowW3; fUpperBound = fWindowW3; @@ -2215,8 +2212,8 @@ Player::Step(int col, fUpperBound = fWindowW4; fCompareWindow = fWindowW5; } - float f1 = randomf(-fCompareWindow, fLowerBound); - float f2 = randomf(fUpperBound, fCompareWindow); + auto f1 = randomf(-fCompareWindow, fLowerBound); + auto f2 = randomf(fUpperBound, fCompareWindow); if (randomf() * 100 >= 50) fNoteOffset = f1; @@ -2250,9 +2247,9 @@ Player::Step(int col, iRowOfOverlappingNoteOrRow); if (GAMESTATE->CountNotesSeparately()) { if (pTN->type != TapNoteType_Mine) { - const bool bBlind = + const auto bBlind = (m_pPlayerState->m_PlayerOptions.GetCurrent().m_fBlind != 0); - const bool bBright = + const auto bBright = (m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast(BRIGHT_GHOST_COMBO_THRESHOLD)); @@ -2302,7 +2299,7 @@ Player::Step(int col, GetClosestNote(col, iSongRow, MAX_NOTE_ROW, MAX_NOTE_ROW, true); } if (iRowOfOverlappingNoteOrRow != -1) { - const TapNote& tn = + const auto& tn = m_NoteData.GetTapNote(col, iRowOfOverlappingNoteOrRow); PlayKeysound(tn, score); } @@ -2327,17 +2324,17 @@ Player::Step(int col, void Player::FlashGhostRow(int iRow) { - TapNoteScore lastTNS = + const auto lastTNS = NoteDataWithScoring::LastTapNoteWithResult(m_NoteData, iRow).result.tns; - const bool bBlind = + const auto bBlind = (m_pPlayerState->m_PlayerOptions.GetCurrent().m_fBlind != 0); - const bool bBright = + const auto bBright = (m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast(BRIGHT_GHOST_COMBO_THRESHOLD)); - for (int iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { - const TapNote& tn = m_NoteData.GetTapNote(iTrack, iRow); + for (auto iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { + const auto& tn = m_NoteData.GetTapNote(iTrack, iRow); if (tn.type == TapNoteType_Empty || tn.type == TapNoteType_Mine || tn.type == TapNoteType_Fake || tn.result.bHidden) { @@ -2360,25 +2357,25 @@ Player::CrossedRows(int iLastRowCrossed, // LOG->Trace( "Player::CrossedRows %d %d", iFirstRowCrossed, // iLastRowCrossed ); - NoteData::all_tracks_iterator& iter = *m_pIterUncrossedRows; - int iLastSeenRow = -1; + auto& iter = *m_pIterUncrossedRows; + auto iLastSeenRow = -1; for (; !iter.IsAtEnd() && iter.Row() <= iLastRowCrossed; ++iter) { // Apply InitialHoldLife. - TapNote& tn = *iter; - int iRow = iter.Row(); - int iTrack = iter.Track(); + auto& tn = *iter; + auto iRow = iter.Row(); + const auto iTrack = iter.Track(); switch (tn.type) { case TapNoteType_HoldHead: { tn.HoldResult.fLife = INITIAL_HOLD_LIFE; if (!REQUIRE_STEP_ON_HOLD_HEADS) { - PlayerNumber pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; vector GameI; GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->StyleInputToGameInput(iTrack, pn, GameI); if (PREFSMAN->m_fPadStickSeconds > 0.f) { - for (size_t i = 0; i < GameI.size(); ++i) { - float fSecsHeld = INPUTMAPPER->GetSecsHeld( - GameI[i], m_pPlayerState->m_mp); + for (auto& i : GameI) { + const auto fSecsHeld = + INPUTMAPPER->GetSecsHeld(i, m_pPlayerState->m_mp); if (fSecsHeld >= PREFSMAN->m_fPadStickSeconds) { Step(iTrack, -1, @@ -2401,14 +2398,14 @@ Player::CrossedRows(int iLastRowCrossed, // Hold the panel while crossing a mine will cause the mine // to explode // TODO: Remove use of PlayerNumber. - PlayerNumber pn = m_pPlayerState->m_PlayerNumber; + const auto pn = m_pPlayerState->m_PlayerNumber; vector GameI; GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->StyleInputToGameInput(iTrack, pn, GameI); if (PREFSMAN->m_fPadStickSeconds > 0.0f) { - for (size_t i = 0; i < GameI.size(); ++i) { - float fSecsHeld = INPUTMAPPER->GetSecsHeld( - GameI[i], m_pPlayerState->m_mp); + for (auto& i : GameI) { + const auto fSecsHeld = + INPUTMAPPER->GetSecsHeld(i, m_pPlayerState->m_mp); if (fSecsHeld >= PREFSMAN->m_fPadStickSeconds) { Step(iTrack, -1, @@ -2453,8 +2450,8 @@ Player::CrossedRows(int iLastRowCrossed, // crossed a new not-empty row iLastSeenRow = iRow; - for (int t = 0; t < m_NoteData.GetNumTracks(); ++t) { - const TapNote& tap = m_NoteData.GetTapNote(t, iRow); + for (auto t = 0; t < m_NoteData.GetNumTracks(); ++t) { + const auto& tap = m_NoteData.GetTapNote(t, iRow); if (tap.type == TapNoteType_AutoKeysound) { PlayKeysound(tap, TNS_None); } @@ -2468,26 +2465,26 @@ Player::CrossedRows(int iLastRowCrossed, if (m_bTickHolds && m_pPlayerState->m_PlayerController == PC_HUMAN) { // Few rows typically cross per update. Easier to check all crossed // rows than to calculate from timing segments. - for (int r = m_iFirstUncrossedRow; r <= iLastRowCrossed; ++r) { - int tickCurrent = m_Timing->GetTickcountAtRow(r); + for (auto r = m_iFirstUncrossedRow; r <= iLastRowCrossed; ++r) { + const auto tickCurrent = m_Timing->GetTickcountAtRow(r); // There is a tick count at this row if (tickCurrent > 0 && r % (ROWS_PER_BEAT / tickCurrent) == 0) { vector viColsWithHold; - int iNumHoldsHeldThisRow = 0; - int iNumHoldsMissedThisRow = 0; + auto iNumHoldsHeldThisRow = 0; + auto iNumHoldsMissedThisRow = 0; // start at r-1 so that we consider holds whose end rows are // equal to the checkpoint row - NoteData::all_tracks_iterator nIter = + auto nIter = m_NoteData.GetTapNoteRangeAllTracks(r - 1, r, true); for (; !nIter.IsAtEnd(); ++nIter) { - TapNote& tn = *nIter; + auto& tn = *nIter; if (tn.type != TapNoteType_HoldHead) continue; - int iTrack = nIter.Track(); + auto iTrack = nIter.Track(); viColsWithHold.push_back(iTrack); if (tn.HoldResult.fLife > 0) { @@ -2523,7 +2520,7 @@ Player::UpdateTapNotesMissedOlderThan(float fMissIfOlderThanSeconds) // LOG->Trace( "Steps::UpdateTapNotesMissedOlderThan(%f)", // fMissIfOlderThanThisBeat ); int iMissIfOlderThanThisRow; - const float fEarliestTime = + const auto fEarliestTime = m_pPlayerState->m_Position.m_fMusicSeconds - fMissIfOlderThanSeconds; { TimingData::GetBeatArgs beat_info; @@ -2540,10 +2537,10 @@ Player::UpdateTapNotesMissedOlderThan(float fMissIfOlderThanSeconds) } } - NoteData::all_tracks_iterator& iter = *m_pIterNeedsTapJudging; + auto& iter = *m_pIterNeedsTapJudging; for (; !iter.IsAtEnd() && iter.Row() < iMissIfOlderThanThisRow; ++iter) { - TapNote& tn = *iter; + auto& tn = *iter; if (!NeedsTapJudging(tn)) continue; @@ -2580,16 +2577,16 @@ void Player::UpdateJudgedRows(float fDeltaTime) { // Look into the future only as far as we need to - const int iEndRow = BeatToNoteRow(m_Timing->GetBeatFromElapsedTime( + const auto iEndRow = BeatToNoteRow(m_Timing->GetBeatFromElapsedTime( m_pPlayerState->m_Position.m_fMusicSeconds + GetMaxStepDistanceSeconds())); - bool bAllJudged = true; + auto bAllJudged = true; if (!GAMESTATE->CountNotesSeparately()) { - NoteData::all_tracks_iterator iter = *m_pIterUnjudgedRows; - int iLastSeenRow = -1; + auto iter = *m_pIterUnjudgedRows; + auto iLastSeenRow = -1; for (; !iter.IsAtEnd() && iter.Row() <= iEndRow; ++iter) { - int iRow = iter.Row(); + const auto iRow = iter.Row(); // Do not judge arrows in WarpSegments or FakeSegments if (!m_Timing->IsJudgableAtRow(iRow)) @@ -2609,7 +2606,7 @@ Player::UpdateJudgedRows(float fDeltaTime) if (m_pJudgedRows->JudgeRow(iRow)) continue; - const TapNote& lastTN = + const auto& lastTN = NoteDataWithScoring::LastTapNoteWithResult(m_NoteData, iRow); if (lastTN.result.tns < TNS_Miss) @@ -2628,16 +2625,16 @@ Player::UpdateJudgedRows(float fDeltaTime) { bAllJudged = true; set setSounds; - NoteData::all_tracks_iterator iter = *m_pIterUnjudgedMineRows; // copy - int iLastSeenRow = -1; + auto iter = *m_pIterUnjudgedMineRows; // copy + auto iLastSeenRow = -1; for (; !iter.IsAtEnd() && iter.Row() <= iEndRow; ++iter) { - int iRow = iter.Row(); + const auto iRow = iter.Row(); // Do not worry about mines in WarpSegments or FakeSegments if (!m_Timing->IsJudgableAtRow(iRow)) continue; - TapNote& tn = *iter; + auto& tn = *iter; if (iRow != iLastSeenRow) { iLastSeenRow = iRow; @@ -2645,7 +2642,7 @@ Player::UpdateJudgedRows(float fDeltaTime) *m_pIterUnjudgedMineRows = iter; } - bool bMineNotHidden = + const auto bMineNotHidden = tn.type == TapNoteType_Mine && !tn.result.bHidden; if (!bMineNotHidden) continue; @@ -2684,7 +2681,7 @@ Player::UpdateJudgedRows(float fDeltaTime) *m_pIterUnjudgedMineRows = iter; } - for (auto& s : setSounds) { + for (const auto& s : setSounds) { // Only play one copy of each mine sound at a time per player. s->Stop(); s->Play(false); @@ -2695,7 +2692,7 @@ Player::UpdateJudgedRows(float fDeltaTime) void Player::HandleTapRowScore(unsigned row) { - bool bNoCheating = true; + const auto bNoCheating = true; #ifdef DEBUG bNoCheating = false; #endif @@ -2704,18 +2701,18 @@ Player::HandleTapRowScore(unsigned row) if (bNoCheating && m_pPlayerState->m_PlayerController == PC_AUTOPLAY) return; - TapNoteScore scoreOfLastTap = + const auto scoreOfLastTap = NoteDataWithScoring::LastTapNoteWithResult(m_NoteData, row).result.tns; - const unsigned int iOldCombo = + const auto iOldCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iOldMissCombo = + const auto iOldMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; if (scoreOfLastTap == TNS_Miss) m_LastTapNoteScore = TNS_Miss; - for (int track = 0; track < m_NoteData.GetNumTracks(); ++track) { - const TapNote& tn = m_NoteData.GetTapNote(track, row); + for (auto track = 0; track < m_NoteData.GetNumTracks(); ++track) { + const auto& tn = m_NoteData.GetTapNote(track, row); // Mines cannot be handled here. if (tn.type == TapNoteType_Empty || tn.type == TapNoteType_Fake || tn.type == TapNoteType_Mine || tn.type == TapNoteType_AutoKeysound) @@ -2724,12 +2721,12 @@ Player::HandleTapRowScore(unsigned row) m_pPrimaryScoreKeeper->HandleTapScore(tn); } - if (m_pPrimaryScoreKeeper != NULL) + if (m_pPrimaryScoreKeeper != nullptr) m_pPrimaryScoreKeeper->HandleTapRowScore(m_NoteData, row); - const unsigned int iCurCombo = + const auto iCurCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iCurMissCombo = + const auto iCurMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; SendComboMessages(iOldCombo, iOldMissCombo); @@ -2787,7 +2784,7 @@ Player::HandleHoldCheckpoint(int iRow, int iNumHoldsMissedThisRow, const vector& viColsWithHold) { - bool bNoCheating = true; + const auto bNoCheating = true; #ifdef DEBUG bNoCheating = false; #endif @@ -2800,9 +2797,9 @@ Player::HandleHoldCheckpoint(int iRow, if (bNoCheating && m_pPlayerState->m_PlayerController == PC_AUTOPLAY) return; - const unsigned int iOldCombo = + const auto iOldCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iOldMissCombo = + const auto iOldMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; if (m_pPrimaryScoreKeeper != nullptr) @@ -2813,8 +2810,8 @@ Player::HandleHoldCheckpoint(int iRow, // added for http://ssc.ajworld.net/sm-ssc/bugtracker/view.php?id=16 // -aj if (CHECKPOINTS_FLASH_ON_HOLD) { - for (auto& i : viColsWithHold) { - bool bBright = + for (const auto& i : viColsWithHold) { + const auto bBright = m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast(BRIGHT_GHOST_COMBO_THRESHOLD); @@ -2845,11 +2842,11 @@ Player::HandleHoldCheckpoint(int iRow, } void -Player::HandleHoldScore(const TapNote& tn) +Player::HandleHoldScore(const TapNote& tn) const { - HoldNoteScore holdScore = tn.HoldResult.hns; - TapNoteScore tapScore = tn.result.tns; - bool bNoCheating = true; + const auto holdScore = tn.HoldResult.hns; + const auto tapScore = tn.result.tns; + const auto bNoCheating = true; #ifdef DEBUG bNoCheating = false; #endif @@ -2872,7 +2869,7 @@ Player::GetMaxStepDistanceSeconds() fMax = max(fMax, GetWindowSeconds(TW_W3)); fMax = max(fMax, GetWindowSeconds(TW_W2)); fMax = max(fMax, GetWindowSeconds(TW_W1)); - float f = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate * fMax; + const auto f = GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate * fMax; return f + m_fMaxInputLatencySeconds; } @@ -2887,7 +2884,7 @@ Player::FadeToFail() } void -Player::CacheAllUsedNoteSkins() +Player::CacheAllUsedNoteSkins() const { if (m_pNoteField != nullptr) m_pNoteField->CacheAllUsedNoteSkins(); @@ -3041,39 +3038,39 @@ Player::SetJudgment(int iRow, #endif } - Lua* L = LUA->Get(); + auto* L = LUA->Get(); lua_createtable(L, 0, m_NoteData.GetNumTracks()); // TapNotes this row lua_createtable( L, 0, m_NoteData.GetNumTracks()); // HoldHeads of tracks held at this row. if (GAMESTATE->CountNotesSeparately()) { - for (int jTrack = 0; jTrack < m_NoteData.GetNumTracks(); ++jTrack) { - NoteData::iterator tn = m_NoteData.FindTapNote(jTrack, iRow); + for (auto jTrack = 0; jTrack < m_NoteData.GetNumTracks(); + ++jTrack) { + auto tn = m_NoteData.FindTapNote(jTrack, iRow); if (tn != m_NoteData.end(jTrack) && jTrack == iTrack) { tn->second.PushSelf(L); lua_rawseti(L, -3, jTrack + 1); } else { int iHeadRow; if (m_NoteData.IsHoldNoteAtRow(jTrack, iRow, &iHeadRow)) { - NoteData::iterator hold = - m_NoteData.FindTapNote(jTrack, iHeadRow); + auto hold = m_NoteData.FindTapNote(jTrack, iHeadRow); hold->second.PushSelf(L); lua_rawseti(L, -2, jTrack + 1); } } } } else { - for (int jTrack = 0; jTrack < m_NoteData.GetNumTracks(); ++jTrack) { - NoteData::iterator tn = m_NoteData.FindTapNote(jTrack, iRow); + for (auto jTrack = 0; jTrack < m_NoteData.GetNumTracks(); + ++jTrack) { + auto tn = m_NoteData.FindTapNote(jTrack, iRow); if (tn != m_NoteData.end(jTrack)) { tn->second.PushSelf(L); lua_rawseti(L, -3, jTrack + 1); } else { int iHeadRow; if (m_NoteData.IsHoldNoteAtRow(jTrack, iRow, &iHeadRow)) { - NoteData::iterator hold = - m_NoteData.FindTapNote(jTrack, iHeadRow); + auto hold = m_NoteData.FindTapNote(jTrack, iHeadRow); hold->second.PushSelf(L); lua_rawseti(L, -2, jTrack + 1); } @@ -3145,7 +3142,7 @@ Player::SetHoldJudgment(TapNote& tn, int iTrack, int iRow) #endif } - Lua* L = LUA->Get(); + auto* L = LUA->Get(); tn.PushSelf(L); msg.SetParamFromStack(L, "TapNote"); LUA->Release(L); @@ -3163,11 +3160,11 @@ Player::SetCombo(unsigned int iCombo, unsigned int iMisses) m_iLastSeenCombo = iCombo; } - bool b25Milestone = false; - bool b50Milestone = false; - bool b100Milestone = false; - bool b250Milestone = false; - bool b1000Milestone = false; + auto b25Milestone = false; + auto b50Milestone = false; + auto b100Milestone = false; + auto b250Milestone = false; + auto b1000Milestone = false; #define MILESTONE_CHECK(amount) \ ((iCombo / (amount)) > (m_iLastSeenCombo / (amount))) @@ -3207,7 +3204,7 @@ Player::SetCombo(unsigned int iCombo, unsigned int iMisses) * * TODO: Add a metric that determines Course combo colors logic? * Or possibly move the logic to a Lua function? -aj */ - bool bPastBeginning = false; + auto bPastBeginning = false; bPastBeginning = m_pPlayerState->m_Position.m_fMusicSeconds > @@ -3232,11 +3229,11 @@ Player::SetCombo(unsigned int iCombo, unsigned int iMisses) } void -Player::IncrementComboOrMissCombo(bool bComboOrMissCombo) +Player::IncrementComboOrMissCombo(const bool bComboOrMissCombo) { - const unsigned int iOldCombo = + const auto iOldCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iOldMissCombo = + const auto iOldMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; if (m_pPlayerStageStats != nullptr) { @@ -3257,19 +3254,19 @@ Player::IncrementComboOrMissCombo(bool bComboOrMissCombo) void Player::RenderAllNotesIgnoreScores() { - int firstRow = 0; - int lastRow = m_NoteData.GetLastRow() + 1; + auto firstRow = 0; + auto lastRow = m_NoteData.GetLastRow() + 1; // Go over every single non empty row and their tracks FOREACH_NONEMPTY_ROW_ALL_TRACKS(m_NoteData, row) { - for (int track = 0; track < m_NoteData.GetNumTracks(); track++) { + for (auto track = 0; track < m_NoteData.GetNumTracks(); track++) { // Find the tapnote we are on - NoteData::iterator iter = m_NoteData.FindTapNote(track, row); + auto iter = m_NoteData.FindTapNote(track, row); // Reset the score so it can be visible if (iter != m_NoteData.end(track)) { - TapNote* pTN = &iter->second; + auto* pTN = &iter->second; if (pTN->type == TapNoteType_Empty) continue; if (pTN->HoldResult.hns != HNS_None) { @@ -3295,7 +3292,7 @@ Player::RenderAllNotesIgnoreScores() m_iFirstUncrossedRow = -1; m_pJudgedRows->Reset(-1); - for (int i = 0; + for (auto i = 0; i < GAMESTATE->GetCurrentStyle(GetPlayerState()->m_PlayerNumber) ->m_iColsPerPlayer; ++i) { @@ -3360,13 +3357,13 @@ class LunaPlayer : public Luna } static int SetActorWithJudgmentPosition(T* p, lua_State* L) { - Actor* pActor = Luna::check(L, 1); + auto* const pActor = Luna::check(L, 1); p->SetActorWithJudgmentPosition(pActor); COMMON_RETURN_SELF; } static int SetActorWithComboPosition(T* p, lua_State* L) { - Actor* pActor = Luna::check(L, 1); + auto* const pActor = Luna::check(L, 1); p->SetActorWithComboPosition(pActor); COMMON_RETURN_SELF; } diff --git a/src/Etterna/Actor/Gameplay/Player.h b/src/Etterna/Actor/Gameplay/Player.h index ac39f6a600..d553843eea 100644 --- a/src/Etterna/Actor/Gameplay/Player.h +++ b/src/Etterna/Actor/Gameplay/Player.h @@ -6,6 +6,7 @@ #include "Etterna/Screen/Others/ScreenMessage.h" #include "RageUtil/Sound/RageSound.h" #include "Etterna/Models/NoteData/NoteData.h" + #include class LifeMeter; @@ -102,10 +103,10 @@ class Player : public ActorFrame void DoTapScoreNone(); void AddHoldToReplayData(int col, const TapNote* pTN, - int RowOfOverlappingNoteOrRow); + int RowOfOverlappingNoteOrRow) const; void AddNoteToReplayData(int col, const TapNote* pTN, - int RowOfOverlappingNoteOrRow); + int RowOfOverlappingNoteOrRow) const; virtual void Step(int col, int row, @@ -115,7 +116,7 @@ class Player : public ActorFrame float padStickSeconds = 0.0f); void FadeToFail(); - void CacheAllUsedNoteSkins(); + void CacheAllUsedNoteSkins() const; TapNoteScore GetLastTapNoteScore() const { return m_LastTapNoteScore; } void SetPaused(bool bPaused) { m_bPaused = bPaused; } @@ -125,7 +126,7 @@ class Player : public ActorFrame float timingScale = 1.f); static float GetTimingWindowScale(); const NoteData& GetNoteData() const { return m_NoteData; } - bool HasVisibleParts() const { return m_pNoteField != NULL; } + bool HasVisibleParts() const { return m_pNoteField != nullptr; } void SetActorWithJudgmentPosition(Actor* pActor) { @@ -145,9 +146,9 @@ class Player : public ActorFrame // Lua void PushSelf(lua_State* L) override; - PlayerState* GetPlayerState() { return this->m_pPlayerState; } - void ChangeLife(float delta); - void SetLife(float value); + PlayerState* GetPlayerState() const { return this->m_pPlayerState; } + void ChangeLife(float delta) const; + void SetLife(float value) const; bool m_inside_lua_set_life; // Mina perma-temp stuff @@ -161,7 +162,7 @@ class Player : public ActorFrame protected: static bool NeedsTapJudging(const TapNote& tn); static bool NeedsHoldJudging(const TapNote& tn); - void UpdateTapNotesMissedOlderThan(float fMissIfOlderThanThisBeat); + virtual void UpdateTapNotesMissedOlderThan(float fMissIfOlderThanThisBeat); void UpdateJudgedRows(float fDeltaTime); // Updates visible parts: Hold Judgments, NoteField Zoom, Combo based Actors void UpdateVisibleParts(); @@ -172,8 +173,9 @@ class Player : public ActorFrame // For Rolls, just tells Autoplay to restep them // For Holds, tells their life to decay // ... oh man this is redundant - void UpdateHoldsAndRolls(float fDeltaTime, - const std::chrono::steady_clock::time_point& now); + virtual void UpdateHoldsAndRolls( + float fDeltaTime, + const std::chrono::steady_clock::time_point& now); // Updates Crossed Rows for NoteData // What this involves is: // Hold Life/Tapping Heads/Checkpoints @@ -182,15 +184,16 @@ class Player : public ActorFrame // Keysounds void UpdateCrossedRows(const std::chrono::steady_clock::time_point& now); void FlashGhostRow(int iRow); - void HandleTapRowScore(unsigned row); - void HandleHoldScore(const TapNote& tn); + virtual void HandleTapRowScore(unsigned row); + void HandleHoldScore(const TapNote& tn) const; void HandleHoldCheckpoint(int iRow, int iNumHoldsHeldThisRow, int iNumHoldsMissedThisRow, const vector& viColsWithHold); void DrawTapJudgments(); void DrawHoldJudgments(); - void SendComboMessages(unsigned int iOldCombo, unsigned int iOldMissCombo); + void SendComboMessages(unsigned int iOldCombo, + unsigned int iOldMissCombo) const; void PlayKeysound(const TapNote& tn, TapNoteScore score); void SetMineJudgment(TapNoteScore tns, int iTrack); @@ -210,11 +213,11 @@ class Player : public ActorFrame void IncrementCombo() { IncrementComboOrMissCombo(true); }; void IncrementMissCombo() { IncrementComboOrMissCombo(false); }; - void ChangeLife(TapNoteScore tns); - void ChangeLife(HoldNoteScore hns, TapNoteScore tns); - void ChangeLifeRecord(); + void ChangeLife(TapNoteScore tns) const; + void ChangeLife(HoldNoteScore hns, TapNoteScore tns) const; + void ChangeLifeRecord() const; - void ChangeWifeRecord(); + void ChangeWifeRecord() const; int GetClosestNoteDirectional(int col, int iStartRow, @@ -236,9 +239,9 @@ class Player : public ActorFrame int iMaxRowsBehind, bool bAllowGraded) const; - inline void HideNote(int col, int row) + void HideNote(int col, int row) const { - NoteData::iterator iter = m_NoteData.FindTapNote(col, row); + const auto iter = m_NoteData.FindTapNote(col, row); if (iter != m_NoteData.end(col)) iter->second.result.bHidden = true; } @@ -308,7 +311,7 @@ class JudgedRows void Resize(size_t iMin) { - size_t iNewSize = max(2 * m_vRows.size(), iMin); + const auto iNewSize = max(2 * m_vRows.size(), iMin); vector vNewRows(m_vRows.begin() + m_iOffset, m_vRows.end()); vNewRows.reserve(iNewSize); vNewRows.insert( diff --git a/src/Etterna/Actor/Gameplay/PlayerPractice.cpp b/src/Etterna/Actor/Gameplay/PlayerPractice.cpp index 8cde8b3286..fa8ece0366 100644 --- a/src/Etterna/Actor/Gameplay/PlayerPractice.cpp +++ b/src/Etterna/Actor/Gameplay/PlayerPractice.cpp @@ -1,21 +1,16 @@ #include "Etterna/Globals/global.h" -#include "Etterna/Models/Misc/PlayerAI.h" #include "Etterna/Models/Misc/PlayerState.h" #include "ArrowEffects.h" #include "NoteField.h" -#include "Etterna/Models/Misc/AdjustSync.h" #include "Etterna/Models/Misc/Game.h" #include "Etterna/Models/StepsAndStyles/Style.h" -#include "Etterna/Models/NoteData/NoteDataWithScoring.h" #include "Etterna/Models/ScoreKeepers/ScoreKeeperNormal.h" #include "Etterna/Models/StepsAndStyles/Steps.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/NoteSkinManager.h" #include "Etterna/Singletons/StatsManager.h" #include "Etterna/Singletons/ScreenManager.h" -#include "Etterna/Singletons/ThemeManager.h" #include "Etterna/Models/Misc/GamePreferences.h" -#include "Etterna/Models/Misc/ThemeMetric.h" #include "RageUtil/Utils/RageUtil.h" #include "PlayerPractice.h" @@ -47,14 +42,11 @@ void PlayerPractice::Update(float fDeltaTime) { const auto now = std::chrono::steady_clock::now(); - if (!m_bLoaded || GAMESTATE->m_pCurSong == NULL) + if (!m_bLoaded || GAMESTATE->m_pCurSong == nullptr) return; ActorFrame::Update(fDeltaTime); - const float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; - const int iSongRow = BeatToNoteRow(fSongBeat); - ArrowEffects::SetCurrentOptions( &m_pPlayerState->m_PlayerOptions.GetCurrent()); diff --git a/src/Etterna/Actor/Gameplay/PlayerReplay.cpp b/src/Etterna/Actor/Gameplay/PlayerReplay.cpp index a8e65bbbaa..dd9fd5f831 100644 --- a/src/Etterna/Actor/Gameplay/PlayerReplay.cpp +++ b/src/Etterna/Actor/Gameplay/PlayerReplay.cpp @@ -13,7 +13,6 @@ #include "Etterna/Models/Misc/ThemeMetric.h" #include "RageUtil/Utils/RageUtil.h" #include "PlayerReplay.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Models/Songs/SongOptions.h" static ThemeMetric GRAY_ARROWS_Y_STANDARD; @@ -86,23 +85,17 @@ PlayerReplay::UpdateHoldNotes(int iSongRow, Player::UpdateHoldNotes(iSongRow, fDeltaTime, vTN); ASSERT(!vTN.empty()); - int iStartRow = vTN[0].iRow; - int iMaxEndRow = INT_MIN; - int iFirstTrackWithMaxEndRow = -1; + const auto iStartRow = vTN[0].iRow; + auto iMaxEndRow = INT_MIN; + auto iFirstTrackWithMaxEndRow = -1; - TapNoteSubType subType = TapNoteSubType_Invalid; - FOREACH(TrackRowTapNote, vTN, trtn) - { - int iTrack = trtn->iTrack; - ASSERT(iStartRow == trtn->iRow); - TapNote& tn = *trtn->pTN; - int iEndRow = iStartRow + tn.iDuration; + auto subType = TapNoteSubType_Invalid; + for (auto& trtn : vTN) { + const auto iTrack = trtn.iTrack; + ASSERT(iStartRow == trtn.iRow); + const auto iEndRow = iStartRow + trtn.pTN->iDuration; if (subType == TapNoteSubType_Invalid) - subType = tn.subType; - - /* All holds must be of the same subType because fLife is handled - * in different ways depending on the SubType. */ - ASSERT(tn.subType == subType); + subType = trtn.pTN->subType; if (iEndRow > iMaxEndRow) { iMaxEndRow = iEndRow; @@ -112,32 +105,30 @@ PlayerReplay::UpdateHoldNotes(int iSongRow, ASSERT(iFirstTrackWithMaxEndRow != -1); - FOREACH(TrackRowTapNote, vTN, trtn) - { - TapNote& tn = *trtn->pTN; - + for (auto& trtn : vTN) { // check from now until the head of the hold to see if it should die // possibly really bad, but we dont REALLY care that much about fps // in replays, right? - bool holdDropped = false; - for (int yeet = vTN[0].iRow; yeet <= iSongRow && !holdDropped; yeet++) { - if (PlayerAI::DetermineIfHoldDropped(yeet, trtn->iTrack)) { + auto holdDropped = false; + for (auto yeet = vTN[0].iRow; yeet <= iSongRow && !holdDropped; + yeet++) { + if (PlayerAI::DetermineIfHoldDropped(yeet, trtn.iTrack)) { holdDropped = true; } } if (holdDropped) // it should be dead { - tn.HoldResult.bHeld = false; - tn.HoldResult.bActive = false; - tn.HoldResult.fLife = 0.f; - tn.HoldResult.hns = HNS_LetGo; + trtn.pTN->HoldResult.bHeld = false; + trtn.pTN->HoldResult.bActive = false; + trtn.pTN->HoldResult.fLife = 0.f; + trtn.pTN->HoldResult.hns = HNS_LetGo; // score the dead hold if (COMBO_BREAK_ON_IMMEDIATE_HOLD_LET_GO) IncrementMissCombo(); - SetHoldJudgment(tn, iFirstTrackWithMaxEndRow, iSongRow); - HandleHoldScore(tn); + SetHoldJudgment(*trtn.pTN, iFirstTrackWithMaxEndRow, iSongRow); + HandleHoldScore(*trtn.pTN); return; } } @@ -148,16 +139,16 @@ PlayerReplay::UpdateHoldsAndRolls( float fDeltaTime, const std::chrono::steady_clock::time_point& now) { - const float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; - const int iSongRow = BeatToNoteRow(fSongBeat); + const auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + const auto iSongRow = BeatToNoteRow(fSongBeat); // Auto tap rolls - for (int iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { + for (auto iTrack = 0; iTrack < m_NoteData.GetNumTracks(); ++iTrack) { int iHeadRow; if (!m_NoteData.IsHoldNoteAtRow(iTrack, iSongRow, &iHeadRow)) iHeadRow = iSongRow; - const TapNote& tn = m_NoteData.GetTapNote(iTrack, iHeadRow); + const auto& tn = m_NoteData.GetTapNote(iTrack, iHeadRow); if (tn.type != TapNoteType_HoldHead || tn.subType != TapNoteSubType_Roll) continue; @@ -174,22 +165,22 @@ PlayerReplay::UpdateHoldsAndRolls( // Fast forward to the first that needs hold judging. { - NoteData::all_tracks_iterator& iter = *m_pIterNeedsHoldJudging; + auto& iter = *m_pIterNeedsHoldJudging; while (!iter.IsAtEnd() && iter.Row() <= iSongRow && !NeedsHoldJudging(*iter)) ++iter; } vector vHoldNotesToGradeTogether; - int iRowOfLastHoldNote = -1; - NoteData::all_tracks_iterator iter = *m_pIterNeedsHoldJudging; // copy + auto iRowOfLastHoldNote = -1; + auto iter = *m_pIterNeedsHoldJudging; // copy for (; !iter.IsAtEnd() && iter.Row() <= iSongRow; ++iter) { - TapNote& tn = *iter; + auto& tn = *iter; if (tn.type != TapNoteType_HoldHead) continue; - int iTrack = iter.Track(); - int iRow = iter.Row(); + const auto iTrack = iter.Track(); + const auto iRow = iter.Row(); TrackRowTapNote trtn = { iTrack, iRow, &tn }; /* All holds must be of the same subType because fLife is handled @@ -231,13 +222,13 @@ void PlayerReplay::Update(float fDeltaTime) { const auto now = std::chrono::steady_clock::now(); - if (!m_bLoaded || GAMESTATE->m_pCurSong == NULL) + if (!m_bLoaded || GAMESTATE->m_pCurSong == nullptr) return; ActorFrame::Update(fDeltaTime); - const float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; - const int iSongRow = BeatToNoteRow(fSongBeat); + const auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + const auto iSongRow = BeatToNoteRow(fSongBeat); ArrowEffects::SetCurrentOptions( &m_pPlayerState->m_PlayerOptions.GetCurrent()); @@ -251,9 +242,8 @@ PlayerReplay::Update(float fDeltaTime) // Step with offsets if we have column data. if (PlayerAI::pScoreData->GetReplayType() == 2) { if (PlayerAI::TapExistsAtOrBeforeThisRow(iSongRow)) { - vector trrVector = - PlayerAI::GetTapsAtOrBeforeRow(iSongRow); - for (TapReplayResult& trr : trrVector) { + auto trrVector = PlayerAI::GetTapsAtOrBeforeRow(iSongRow); + for (auto& trr : trrVector) { // LOG->Trace("\tPassing row %d pressed on %d", iSongRow, // trr.row); Step(trr.track, trr.row, now, false, false, 0.f, trr.row); @@ -280,13 +270,13 @@ void PlayerReplay::CrossedRows(int iLastRowCrossed, const std::chrono::steady_clock::time_point& now) { - NoteData::all_tracks_iterator& iter = *m_pIterUncrossedRows; - int iLastSeenRow = -1; + auto& iter = *m_pIterUncrossedRows; + auto iLastSeenRow = -1; for (; !iter.IsAtEnd() && iter.Row() <= iLastRowCrossed; ++iter) { // Apply InitialHoldLife. - TapNote& tn = *iter; - int iRow = iter.Row(); - int iTrack = iter.Track(); + auto& tn = *iter; + auto iRow = iter.Row(); + const auto iTrack = iter.Track(); switch (tn.type) { case TapNoteType_HoldHead: { tn.HoldResult.fLife = 1; @@ -312,8 +302,8 @@ PlayerReplay::CrossedRows(int iLastRowCrossed, // crossed a new not-empty row iLastSeenRow = iRow; - for (int t = 0; t < m_NoteData.GetNumTracks(); ++t) { - const TapNote& tap = m_NoteData.GetTapNote(t, iRow); + for (auto t = 0; t < m_NoteData.GetNumTracks(); ++t) { + const auto& tap = m_NoteData.GetTapNote(t, iRow); if (tap.type == TapNoteType_AutoKeysound) { PlayKeysound(tap, TNS_None); } @@ -327,19 +317,18 @@ PlayerReplay::CrossedRows(int iLastRowCrossed, void PlayerReplay::HandleTapRowScore(unsigned row) { - - TapNoteScore scoreOfLastTap = + const auto scoreOfLastTap = NoteDataWithScoring::LastTapNoteWithResult(m_NoteData, row).result.tns; - const unsigned int iOldCombo = + const auto iOldCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iOldMissCombo = + const auto iOldMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; if (scoreOfLastTap == TNS_Miss) m_LastTapNoteScore = TNS_Miss; - for (int track = 0; track < m_NoteData.GetNumTracks(); ++track) { - const TapNote& tn = m_NoteData.GetTapNote(track, row); + for (auto track = 0; track < m_NoteData.GetNumTracks(); ++track) { + const auto& tn = m_NoteData.GetTapNote(track, row); // Mines cannot be handled here. if (tn.type == TapNoteType_Empty || tn.type == TapNoteType_Fake || tn.type == TapNoteType_Mine || tn.type == TapNoteType_AutoKeysound) @@ -348,12 +337,12 @@ PlayerReplay::HandleTapRowScore(unsigned row) m_pPrimaryScoreKeeper->HandleTapScore(tn); } - if (m_pPrimaryScoreKeeper != NULL) + if (m_pPrimaryScoreKeeper != nullptr) m_pPrimaryScoreKeeper->HandleTapRowScore(m_NoteData, row); - const unsigned int iCurCombo = + const auto iCurCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurCombo : 0; - const unsigned int iCurMissCombo = + const auto iCurMissCombo = m_pPlayerStageStats != nullptr ? m_pPlayerStageStats->m_iCurMissCombo : 0; SendComboMessages(iOldCombo, iOldMissCombo); @@ -409,7 +398,7 @@ void PlayerReplay::UpdateTapNotesMissedOlderThan(float fMissIfOlderThanSeconds) { int iMissIfOlderThanThisRow; - const float fEarliestTime = + const auto fEarliestTime = m_pPlayerState->m_Position.m_fMusicSeconds - fMissIfOlderThanSeconds; { TimingData::GetBeatArgs beat_info; @@ -426,10 +415,10 @@ PlayerReplay::UpdateTapNotesMissedOlderThan(float fMissIfOlderThanSeconds) } } - NoteData::all_tracks_iterator& iter = *m_pIterNeedsTapJudging; + auto& iter = *m_pIterNeedsTapJudging; for (; !iter.IsAtEnd() && iter.Row() < iMissIfOlderThanThisRow; ++iter) { - TapNote& tn = *iter; + auto& tn = *iter; if (!NeedsTapJudging(tn)) continue; @@ -470,15 +459,15 @@ PlayerReplay::Step(int col, { // Do everything that depends on a timer here; // set your breakpoints somewhere after this block. - std::chrono::duration stepDelta = + const std::chrono::duration stepDelta = std::chrono::steady_clock::now() - tm; - float stepAgo = stepDelta.count() - padStickSeconds; + const auto stepAgo = stepDelta.count() - padStickSeconds; - const float fLastBeatUpdate = + const auto fLastBeatUpdate = m_pPlayerState->m_Position.m_LastBeatUpdate.Ago(); - const float fPositionSeconds = + const auto fPositionSeconds = m_pPlayerState->m_Position.m_fMusicSeconds - stepAgo; - const float fTimeSinceStep = stepAgo; + const auto fTimeSinceStep = stepAgo; // LOG->Trace(ssprintf("col %d\n\trow %d", col, row)); @@ -486,24 +475,24 @@ PlayerReplay::Step(int col, // test -mina ok this is 100% not the place to do this // m_pPlayerStageStats->InputData.emplace_back(fPositionSeconds); - float fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; + auto fSongBeat = m_pPlayerState->m_Position.m_fSongBeat; if (GAMESTATE->m_pCurSteps) fSongBeat = m_Timing->GetBeatFromElapsedTime(fPositionSeconds); - const int iSongRow = row == -1 ? BeatToNoteRow(fSongBeat) : row; + const auto iSongRow = row == -1 ? BeatToNoteRow(fSongBeat) : row; if (col != -1 && !bRelease) { // Update roll life // Let's not check the whole array every time. // Instead, only check 1 beat back. Even 1 is overkill. // Just update the life here and let Update judge the roll. - const int iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); + const auto iStartCheckingAt = max(0, iSongRow - BeatToNoteRow(1)); NoteData::TrackMap::iterator begin, end; m_NoteData.GetTapNoteRangeInclusive( col, iStartCheckingAt, iSongRow + 1, begin, end); for (; begin != end; ++begin) { - TapNote& tn = begin->second; + auto& tn = begin->second; if (tn.type != TapNoteType_HoldHead) continue; @@ -515,19 +504,19 @@ PlayerReplay::Step(int col, break; } - const int iRow = begin->first; + const auto iRow = begin->first; - HoldNoteScore hns = tn.HoldResult.hns; + const auto hns = tn.HoldResult.hns; if (hns != HNS_None) // if this HoldNote already has a result continue; // we don't need to update the logic for this one // if they got a bad score or haven't stepped on the corresponding // tap yet - const TapNoteScore tns = tn.result.tns; - bool bInitiatedNote = true; + const auto tns = tn.result.tns; + auto bInitiatedNote = true; bInitiatedNote = tns != TNS_None && tns != TNS_Miss; // did they step on the start? - const int iEndRow = iRow + tn.iDuration; + const auto iEndRow = iRow + tn.iDuration; if (bInitiatedNote && tn.HoldResult.fLife != 0) { /* This hold note is not judged and we stepped on its head. @@ -548,10 +537,10 @@ PlayerReplay::Step(int col, if (ROLL_BODY_INCREMENTS_COMBO) { IncrementCombo(); - bool bBright = m_pPlayerStageStats && - m_pPlayerStageStats->m_iCurCombo > - static_cast( - BRIGHT_GHOST_COMBO_THRESHOLD); + const auto bBright = m_pPlayerStageStats && + m_pPlayerStageStats->m_iCurCombo > + static_cast( + BRIGHT_GHOST_COMBO_THRESHOLD); if (m_pNoteField) m_pNoteField->DidHoldNote(col, HNS_Held, bBright); } @@ -563,9 +552,9 @@ PlayerReplay::Step(int col, // Check for tap int iStepSearchRows; - static const float StepSearchDistance = GetMaxStepDistanceSeconds(); - int skipstart = nerv[10]; // this is not robust need to come up with - // something better later - Mina + static const auto StepSearchDistance = GetMaxStepDistanceSeconds(); + const auto skipstart = nerv[10]; // this is not robust need to come up with + // something better later - Mina if (iSongRow < skipstart || iSongRow > static_cast(nerv.size()) - 10) { iStepSearchRows = @@ -587,9 +576,9 @@ PlayerReplay::Step(int col, if (nerv[nervpos] < iSongRow && nervpos < nerv.size()) nervpos += 1; - size_t SearchIndexBehind = nervpos; - size_t SearchIndexAhead = nervpos; - float SearchBeginTime = m_Timing->WhereUAtBro(nerv[nervpos]); + auto SearchIndexBehind = nervpos; + auto SearchIndexAhead = nervpos; + const auto SearchBeginTime = m_Timing->WhereUAtBro(nerv[nervpos]); while (SearchIndexBehind > 1 && SearchBeginTime - @@ -603,8 +592,8 @@ PlayerReplay::Step(int col, StepSearchDistance) SearchIndexAhead += 1; - int MaxLookBehind = nerv[nervpos] - nerv[SearchIndexBehind]; - int MaxLookAhead = nerv[SearchIndexAhead] - nerv[nervpos]; + const auto MaxLookBehind = nerv[nervpos] - nerv[SearchIndexBehind]; + const auto MaxLookAhead = nerv[SearchIndexAhead] - nerv[nervpos]; if (nervpos > 0) iStepSearchRows = @@ -612,19 +601,19 @@ PlayerReplay::Step(int col, } // calculate TapNoteScore - TapNoteScore score = TNS_None; + auto score = TNS_None; - int iRowOfOverlappingNoteOrRow = row; + auto iRowOfOverlappingNoteOrRow = row; if (row == -1 && col != -1) iRowOfOverlappingNoteOrRow = GetClosestNote( col, iSongRow, iStepSearchRows, iStepSearchRows, false, false); if (iRowOfOverlappingNoteOrRow != -1 && col != -1) { // compute the score for this hit - float fNoteOffset = 0.f; + auto fNoteOffset = 0.f; // we need this later if we are autosyncing - const float fStepBeat = NoteRowToBeat(iRowOfOverlappingNoteOrRow); - const float fStepSeconds = m_Timing->WhereUAtBro(fStepBeat); + const auto fStepBeat = NoteRowToBeat(iRowOfOverlappingNoteOrRow); + const auto fStepSeconds = m_Timing->WhereUAtBro(fStepBeat); if (row == -1) { // We actually stepped on the note this long ago: @@ -633,13 +622,13 @@ PlayerReplay::Step(int col, /* GAMESTATE->m_fMusicSeconds is the music time as of * GAMESTATE->m_LastBeatUpdate. Figure out what the music time is as * of now. */ - const float fCurrentMusicSeconds = + const auto fCurrentMusicSeconds = m_pPlayerState->m_Position.m_fMusicSeconds + (fLastBeatUpdate * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate); // ... which means it happened at this point in the music: - const float fMusicSeconds = + const auto fMusicSeconds = fCurrentMusicSeconds - fTimeSinceStep * GAMESTATE->m_SongOptions.GetCurrent().m_fMusicRate; @@ -653,10 +642,10 @@ PlayerReplay::Step(int col, NOTESKIN->SetLastSeenColor( NoteTypeToString(GetNoteType(iRowOfOverlappingNoteOrRow))); - const float fSecondsFromExact = fabsf(fNoteOffset); + const auto fSecondsFromExact = fabsf(fNoteOffset); TapNote* pTN = nullptr; - NoteData::iterator iter = m_NoteData.FindTapNote( + auto iter = m_NoteData.FindTapNote( col, GetClosestNote(col, iSongRow, MAX_NOTE_ROW, MAX_NOTE_ROW, false)); @@ -720,9 +709,9 @@ PlayerReplay::Step(int col, iRowOfOverlappingNoteOrRow); if (GAMESTATE->CountNotesSeparately()) { if (pTN->type != TapNoteType_Mine) { - const bool bBlind = + const auto bBlind = (m_pPlayerState->m_PlayerOptions.GetCurrent().m_fBlind != 0); - const bool bBright = + const auto bBright = (m_pPlayerStageStats && m_pPlayerStageStats->m_iCurCombo > static_cast(BRIGHT_GHOST_COMBO_THRESHOLD)); @@ -777,7 +766,7 @@ PlayerReplay::Step(int col, GetClosestNote(col, iSongRow, MAX_NOTE_ROW, MAX_NOTE_ROW, true); } if (iRowOfOverlappingNoteOrRow != -1) { - const TapNote& tn = + const auto& tn = m_NoteData.GetTapNote(col, iRowOfOverlappingNoteOrRow); PlayKeysound(tn, score); } diff --git a/src/Etterna/Actor/Gameplay/ReceptorArrow.cpp b/src/Etterna/Actor/Gameplay/ReceptorArrow.cpp index 3ea977b6a8..7b40165fa4 100644 --- a/src/Etterna/Actor/Gameplay/ReceptorArrow.cpp +++ b/src/Etterna/Actor/Gameplay/ReceptorArrow.cpp @@ -1,4 +1,3 @@ -#include "Etterna/Globals/global.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/NoteSkinManager.h" #include "Etterna/Models/Misc/PlayerState.h" @@ -11,7 +10,7 @@ ReceptorArrow::ReceptorArrow() m_bIsPressed = false; m_bWasPressed = false; m_bWasReverse = false; - m_pPlayerState = NULL; + m_pPlayerState = nullptr; m_iColNo = 0; } @@ -23,8 +22,8 @@ ReceptorArrow::Load(const PlayerState* pPlayerState, m_pPlayerState = pPlayerState; m_iColNo = iColNo; - const PlayerNumber pn = m_pPlayerState->m_PlayerNumber; - vector GameI; + const auto pn = m_pPlayerState->m_PlayerNumber; + std::vector GameI; GAMESTATE->GetCurrentStyle(pn)->StyleInputToGameInput(iColNo, pn, GameI); NOTESKIN->SetPlayerNumber(pn); // FIXME? Does this cause a problem when game inputs on different @@ -33,12 +32,12 @@ ReceptorArrow::Load(const PlayerState* pPlayerState, // requirements. -Kyz NOTESKIN->SetGameController(GameI[0].controller); - std::string sButton = + const auto sButton = GAMESTATE->GetCurrentStyle(pn)->ColToButtonName(iColNo); m_pReceptor.Load(NOTESKIN->LoadActor(sButton, Type)); this->AddChild(m_pReceptor); - bool bReverse = + const auto bReverse = m_pPlayerState->m_PlayerOptions.GetCurrent().GetReversePercentForColumn( m_iColNo) > 0.5f; m_pReceptor->PlayCommand(bReverse ? "ReverseOn" : "ReverseOff"); @@ -50,7 +49,7 @@ ReceptorArrow::Update(float fDeltaTime) { ActorFrame::Update(fDeltaTime); - bool bReverse = + const auto bReverse = m_pPlayerState->m_PlayerOptions.GetCurrent().GetReversePercentForColumn( m_iColNo) > 0.5f; if (bReverse != m_bWasReverse) { diff --git a/src/Etterna/Actor/Gameplay/ReceptorArrowRow.cpp b/src/Etterna/Actor/Gameplay/ReceptorArrowRow.cpp index 8890cc5a54..391c9181a3 100644 --- a/src/Etterna/Actor/Gameplay/ReceptorArrowRow.cpp +++ b/src/Etterna/Actor/Gameplay/ReceptorArrowRow.cpp @@ -12,10 +12,10 @@ map> NoteUpcoming; ReceptorArrowRow::ReceptorArrowRow() { NoteUpcoming.clear(); - m_pPlayerState = NULL; + m_pPlayerState = nullptr; m_fYReverseOffsetPixels = 0; m_fFadeToFailPercent = 0; - m_renderers = NULL; + m_renderers = nullptr; } void @@ -24,10 +24,10 @@ ReceptorArrowRow::Load(const PlayerState* pPlayerState, float fYReverseOffset) m_pPlayerState = pPlayerState; m_fYReverseOffsetPixels = fYReverseOffset; - const Style* pStyle = + const auto* const pStyle = GAMESTATE->GetCurrentStyle(pPlayerState->m_PlayerNumber); - for (int c = 0; c < pStyle->m_iColsPerPlayer; c++) { + for (auto c = 0; c < pStyle->m_iColsPerPlayer; c++) { m_ReceptorArrow.push_back(new ReceptorArrow); m_OverlayReceptorArrow.push_back(new ReceptorArrow); m_ReceptorArrow[c]->SetName("ReceptorArrow"); @@ -52,8 +52,8 @@ ReceptorArrowRow::SetColumnRenderers(vector& renderers) ReceptorArrowRow::~ReceptorArrowRow() { - for (unsigned i = 0; i < m_ReceptorArrow.size(); ++i) - delete m_ReceptorArrow[i]; + for (auto& i : m_ReceptorArrow) + delete i; } void @@ -64,13 +64,13 @@ ReceptorArrowRow::Update(float fDeltaTime) // ArrowEffects. But if we're on ScreenNameEntry, there is no notefield, // Checking whether m_renderers is null is a proxy for checking whether // there is a notefield. -Kyz - if (m_renderers == NULL) { + if (m_renderers == nullptr) { ArrowEffects::Update(); } for (unsigned c = 0; c < m_ReceptorArrow.size(); c++) { // m_fDark==1 or m_fFadeToFailPercent==1 should make fBaseAlpha==0 - float fBaseAlpha = + auto fBaseAlpha = (1 - m_pPlayerState->m_PlayerOptions.GetCurrent().m_fDark); if (m_fFadeToFailPercent != -1) { fBaseAlpha *= (1 - m_fFadeToFailPercent); @@ -79,7 +79,7 @@ ReceptorArrowRow::Update(float fDeltaTime) m_ReceptorArrow[c]->SetBaseAlpha(fBaseAlpha); m_OverlayReceptorArrow[c]->SetBaseAlpha(fBaseAlpha); - if (m_renderers != NULL) { + if (m_renderers != nullptr) { // set arrow XYZ (*m_renderers)[c].UpdateReceptorGhostStuff(m_ReceptorArrow[c]); (*m_renderers)[c].UpdateReceptorGhostStuff( @@ -87,7 +87,7 @@ ReceptorArrowRow::Update(float fDeltaTime) } else { // ScreenNameEntry uses ReceptorArrowRow but doesn't have or need // column renderers. Just do the lazy thing and offset x. -Kyz - const Style* style = + const auto* style = GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); m_ReceptorArrow[c]->SetX(style->m_ColumnInfo[c].fXOffset); m_OverlayReceptorArrow[c]->SetX(style->m_ColumnInfo[c].fXOffset); @@ -98,10 +98,10 @@ ReceptorArrowRow::Update(float fDeltaTime) void ReceptorArrowRow::DrawPrimitives() { - const Style* pStyle = + const auto* pStyle = GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); for (unsigned i = 0; i < m_ReceptorArrow.size(); i++) { - const int c = pStyle->m_iColumnDrawOrder[i]; + const auto c = pStyle->m_iColumnDrawOrder[i]; m_ReceptorArrow[c]->Draw(); } } @@ -109,10 +109,10 @@ ReceptorArrowRow::DrawPrimitives() void ReceptorArrowRow::DrawOverlay() { - const Style* pStyle = + const auto* pStyle = GAMESTATE->GetCurrentStyle(m_pPlayerState->m_PlayerNumber); for (unsigned i = 0; i < m_ReceptorArrow.size(); i++) { - const int c = pStyle->m_iColumnDrawOrder[i]; + const auto c = pStyle->m_iColumnDrawOrder[i]; m_OverlayReceptorArrow[c]->Draw(); } } diff --git a/src/Etterna/Actor/Menus/BPMDisplay.cpp b/src/Etterna/Actor/Menus/BPMDisplay.cpp index 7c52c54794..c42c7715dc 100644 --- a/src/Etterna/Actor/Menus/BPMDisplay.cpp +++ b/src/Etterna/Actor/Menus/BPMDisplay.cpp @@ -60,9 +60,9 @@ BPMDisplay::Update(float fDeltaTime) { BitmapText::Update(fDeltaTime); - if (!(bool)CYCLE) + if (!static_cast(CYCLE)) return; - if (m_BPMS.size() == 0) + if (m_BPMS.empty()) return; // no bpm m_fPercentInState -= fDeltaTime / m_fCycleTime; @@ -76,13 +76,14 @@ BPMDisplay::Update(float fDeltaTime) if (m_fBPMTo == -1) { m_fBPMFrom = -1; - if ((bool)SHOW_QMARKS) - SetText((RandomFloat(0, 1) > 0.90f) - ? (std::string)QUESTIONMARKS_TEXT - : ssprintf((std::string)BPM_FORMAT_STRING, - RandomFloat(0, 999))); + if (static_cast(SHOW_QMARKS)) + SetText( + (RandomFloat(0, 1) > 0.90f) + ? static_cast(QUESTIONMARKS_TEXT) + : ssprintf(static_cast(BPM_FORMAT_STRING), + RandomFloat(0, 999))); else - SetText(ssprintf((std::string)BPM_FORMAT_STRING, + SetText(ssprintf(static_cast(BPM_FORMAT_STRING), RandomFloat(0, 999))); } else if (m_fBPMFrom == -1) { m_fBPMFrom = m_fBPMTo; @@ -91,7 +92,8 @@ BPMDisplay::Update(float fDeltaTime) if (m_fBPMTo != -1) { const float fActualBPM = GetActiveBPM(); - SetText(ssprintf((std::string)BPM_FORMAT_STRING, fActualBPM)); + SetText( + ssprintf(static_cast(BPM_FORMAT_STRING), fActualBPM)); } } @@ -110,7 +112,7 @@ BPMDisplay::SetBPMRange(const DisplayBpms& bpms) AllIdentical = false; } - if (!(bool)CYCLE) { + if (!static_cast(CYCLE)) { int MinBPM = INT_MAX; int MaxBPM = INT_MIN; for (unsigned i = 0; i < BPMS.size(); ++i) { @@ -248,7 +250,7 @@ SongBPMDisplay::SongBPMDisplay() void SongBPMDisplay::Update(float fDeltaTime) { - float fGameStateBPM = GAMESTATE->m_Position.m_fCurBPS * 60.0f; + const float fGameStateBPM = GAMESTATE->m_Position.m_fCurBPS * 60.0f; if (m_fLastGameStateBPM != fGameStateBPM) { m_fLastGameStateBPM = fGameStateBPM; SetConstantBpm(fGameStateBPM); diff --git a/src/Etterna/Actor/Menus/ComboGraph.cpp b/src/Etterna/Actor/Menus/ComboGraph.cpp index e6fcce626c..67381961a4 100644 --- a/src/Etterna/Actor/Menus/ComboGraph.cpp +++ b/src/Etterna/Actor/Menus/ComboGraph.cpp @@ -14,10 +14,10 @@ ComboGraph::ComboGraph() { DeleteChildrenWhenDone(true); - m_pNormalCombo = NULL; - m_pMaxCombo = NULL; - m_pComboNumber = NULL; - m_pBacking = NULL; + m_pNormalCombo = nullptr; + m_pMaxCombo = nullptr; + m_pComboNumber = nullptr; + m_pBacking = nullptr; } void @@ -31,11 +31,11 @@ ComboGraph::Load(const std::string& sMetricsGroup) this->SetWidth(BODY_WIDTH); this->SetHeight(BODY_HEIGHT); - Actor* pActor = NULL; + Actor* pActor = nullptr; m_pBacking = ActorUtil::MakeActor(THEME->GetPathG(sMetricsGroup, "Backing")); - if (m_pBacking != NULL) { + if (m_pBacking != nullptr) { m_pBacking->ZoomToWidth(BODY_WIDTH); m_pBacking->ZoomToHeight(BODY_HEIGHT); this->AddChild(m_pBacking); @@ -43,7 +43,7 @@ ComboGraph::Load(const std::string& sMetricsGroup) m_pNormalCombo = ActorUtil::MakeActor(THEME->GetPathG(sMetricsGroup, "NormalCombo")); - if (m_pNormalCombo != NULL) { + if (m_pNormalCombo != nullptr) { m_pNormalCombo->ZoomToWidth(BODY_WIDTH); m_pNormalCombo->ZoomToHeight(BODY_HEIGHT); this->AddChild(m_pNormalCombo); @@ -51,7 +51,7 @@ ComboGraph::Load(const std::string& sMetricsGroup) m_pMaxCombo = ActorUtil::MakeActor(THEME->GetPathG(sMetricsGroup, "MaxCombo")); - if (m_pMaxCombo != NULL) { + if (m_pMaxCombo != nullptr) { m_pMaxCombo->ZoomToWidth(BODY_WIDTH); m_pMaxCombo->ZoomToHeight(BODY_HEIGHT); this->AddChild(m_pMaxCombo); @@ -59,9 +59,9 @@ ComboGraph::Load(const std::string& sMetricsGroup) pActor = ActorUtil::MakeActor(THEME->GetPathG(sMetricsGroup, "ComboNumber")); - if (pActor != NULL) { + if (pActor != nullptr) { m_pComboNumber = dynamic_cast(pActor); - if (m_pComboNumber != NULL) + if (m_pComboNumber != nullptr) this->AddChild(m_pComboNumber); else LuaHelpers::ReportScriptErrorFmt("ComboGraph: \"sMetricsGroup\" " diff --git a/src/Etterna/Actor/Menus/DifficultyList.cpp b/src/Etterna/Actor/Menus/DifficultyList.cpp index 4ae76646fb..2278011fe5 100644 --- a/src/Etterna/Actor/Menus/DifficultyList.cpp +++ b/src/Etterna/Actor/Menus/DifficultyList.cpp @@ -95,7 +95,8 @@ StepsDisplayList::LoadFromNode(const XNode* pNode) int StepsDisplayList::GetCurrentRowIndex(PlayerNumber pn) const { - Difficulty ClosestDifficulty = GAMESTATE->GetClosestShownDifficulty(pn); + const Difficulty ClosestDifficulty = + GAMESTATE->GetClosestShownDifficulty(pn); for (unsigned i = 0; i < m_Rows.size(); i++) { const Row& row = m_Rows[i]; @@ -116,7 +117,7 @@ StepsDisplayList::GetCurrentRowIndex(PlayerNumber pn) const void StepsDisplayList::UpdatePositions() { - int iCurrentRow = GetCurrentRowIndex(PLAYER_1); + const int iCurrentRow = GetCurrentRowIndex(PLAYER_1); const int total = NUM_SHOWN_ITEMS; const int halfsize = total / 2; @@ -125,7 +126,7 @@ StepsDisplayList::UpdatePositions() // Choices for each player. If only one player is active, it's the same for // both. - int P1Choice = iCurrentRow; + const int P1Choice = iCurrentRow; vector& Rows = m_Rows; @@ -192,7 +193,7 @@ StepsDisplayList::UpdatePositions() Row& row = Rows[i]; - float fY = ITEMS_SPACING_Y * ItemPosition; + const float fY = ITEMS_SPACING_Y * ItemPosition; row.m_fY = fY; row.m_bHidden = i < first_start || (i >= first_end && i < second_start) || i >= second_end; @@ -203,7 +204,7 @@ void StepsDisplayList::PositionItems() { for (int i = 0; i < MAX_METERS; ++i) { - bool bUnused = (i >= static_cast(m_Rows.size())); + const bool bUnused = (i >= static_cast(m_Rows.size())); m_Lines[i].m_Meter.SetVisible(!bUnused); } @@ -229,12 +230,12 @@ StepsDisplayList::PositionItems() if (m_bShown && m < static_cast(m_Rows.size())) bHidden = m_Rows[m].m_bHidden; - float fDiffuseAlpha = bHidden ? 0.0f : 1.0f; + const float fDiffuseAlpha = bHidden ? 0.0f : 1.0f; m_Lines[m].m_Meter.SetDiffuseAlpha(fDiffuseAlpha); } - int iCurrentRow = GetCurrentRowIndex(PLAYER_1); + const int iCurrentRow = GetCurrentRowIndex(PLAYER_1); float fY = 0; if (iCurrentRow < static_cast(m_Rows.size())) diff --git a/src/Etterna/Actor/Menus/DifficultyList.h b/src/Etterna/Actor/Menus/DifficultyList.h index 0a492e6347..9ba8490a0c 100644 --- a/src/Etterna/Actor/Menus/DifficultyList.h +++ b/src/Etterna/Actor/Menus/DifficultyList.h @@ -10,7 +10,7 @@ class Song; class Steps; -class StepsDisplayList : public ActorFrame +class StepsDisplayList final : public ActorFrame { public: StepsDisplayList(); @@ -47,7 +47,7 @@ class StepsDisplayList : public ActorFrame { StepsDisplay m_Meter; }; - vector m_Lines; + std::vector m_Lines; const Song* m_CurSong; bool m_bShown; @@ -56,7 +56,7 @@ class StepsDisplayList : public ActorFrame { Row() { - m_Steps = NULL; + m_Steps = nullptr; m_dc = Difficulty_Invalid; m_fY = 0; m_bHidden = false; @@ -68,7 +68,7 @@ class StepsDisplayList : public ActorFrame bool m_bHidden; // currently off screen }; - vector m_Rows; + std::vector m_Rows; }; #endif diff --git a/src/Etterna/Actor/Menus/GraphDisplay.cpp b/src/Etterna/Actor/Menus/GraphDisplay.cpp index db14e5d1ab..45c45247c8 100644 --- a/src/Etterna/Actor/Menus/GraphDisplay.cpp +++ b/src/Etterna/Actor/Menus/GraphDisplay.cpp @@ -45,7 +45,7 @@ class GraphLine : public Actor DISPLAY->DrawQuads(&m_Quads[0], m_Quads.size()); - int iFans = m_pCircles.size() / iCircleVertices; + const int iFans = m_pCircles.size() / iCircleVertices; for (int i = 0; i < iFans; ++i) DISPLAY->DrawFan(&m_pCircles[0] + iCircleVertices * i, iCircleVertices); @@ -80,26 +80,26 @@ class GraphLine : public Actor 1); } - int iNumLines = iSize - 1; + const int iNumLines = iSize - 1; m_Quads.resize(iNumLines * 4); for (int i = 0; i < iNumLines; ++i) { const RageSpriteVertex& p1 = m_LineStrip[i]; const RageSpriteVertex& p2 = m_LineStrip[i + 1]; - float opp = p2.p.x - p1.p.x; - float adj = p2.p.y - p1.p.y; - float hyp = powf(opp * opp + adj * adj, 0.5f); + const float opp = p2.p.x - p1.p.x; + const float adj = p2.p.y - p1.p.y; + const float hyp = powf(opp * opp + adj * adj, 0.5f); - float lsin = opp / hyp; - float lcos = adj / hyp; + const float lsin = opp / hyp; + const float lcos = adj / hyp; RageSpriteVertex* v = &m_Quads[i * 4]; v[0] = v[1] = p1; v[2] = v[3] = p2; - int iLineWidth = 2; - float ydist = lsin * iLineWidth / 2; - float xdist = lcos * iLineWidth / 2; + const int iLineWidth = 2; + const float ydist = lsin * iLineWidth / 2; + const float xdist = lcos * iLineWidth / 2; v[0].p.x += xdist; v[0].p.y -= ydist; @@ -135,7 +135,7 @@ class GraphBody : public Actor ~GraphBody() override { TEXTUREMAN->UnloadTexture(m_pTexture); - m_pTexture = NULL; + m_pTexture = nullptr; } void DrawPrimitives() override @@ -158,8 +158,8 @@ class GraphBody : public Actor GraphDisplay::GraphDisplay() { - m_pGraphLine = NULL; - m_pGraphBody = NULL; + m_pGraphLine = nullptr; + m_pGraphBody = nullptr; } GraphDisplay::~GraphDisplay() @@ -174,7 +174,7 @@ GraphDisplay::~GraphDisplay() void GraphDisplay::Set(const StageStats& ss, const PlayerStageStats& pss) { - float fTotalStepSeconds = ss.GetTotalPossibleStepsSeconds(); + const float fTotalStepSeconds = ss.GetTotalPossibleStepsSeconds(); m_Values.resize(VALUE_RESOLUTION); pss.GetWifeRecord( @@ -194,11 +194,11 @@ GraphDisplay::Set(const StageStats& ss, const PlayerStageStats& pss) Actor* p = m_sprSongBoundary->Copy(); m_vpSongBoundaries.push_back(p); - float fX = SCALE(fSec, - 0, - fTotalStepSeconds, - m_quadVertices.left, - m_quadVertices.right); + const float fX = SCALE(fSec, + 0, + fTotalStepSeconds, + m_quadVertices.left, + m_quadVertices.right); p->SetX(fX); this->AddChild(p); } @@ -209,7 +209,7 @@ GraphDisplay::Set(const StageStats& ss, const PlayerStageStats& pss) int iMinLifeSoFarAt = 0; for (int i = 0; i < VALUE_RESOLUTION; ++i) { - float fLife = m_Values[i]; + const float fLife = m_Values[i]; if (fLife < fMinLifeSoFar) { fMinLifeSoFar = fLife; iMinLifeSoFarAt = i; @@ -217,11 +217,11 @@ GraphDisplay::Set(const StageStats& ss, const PlayerStageStats& pss) } if (fMinLifeSoFar > 0.0f && fMinLifeSoFar < 0.1f) { - float fX = SCALE(static_cast(iMinLifeSoFarAt), - 0.0f, - static_cast(VALUE_RESOLUTION - 1), - m_quadVertices.left, - m_quadVertices.right); + const float fX = SCALE(static_cast(iMinLifeSoFarAt), + 0.0f, + static_cast(VALUE_RESOLUTION - 1), + m_quadVertices.left, + m_quadVertices.right); m_sprBarely->SetX(fX); } else { m_sprBarely->SetVisible(false); @@ -318,10 +318,10 @@ class LunaGraphDisplay : public Luna StageStats* pStageStats = Luna::check(L, 1); PlayerStageStats* pPlayerStageStats = Luna::check(L, 2); - if (pStageStats == NULL) { + if (pStageStats == nullptr) { luaL_error(L, "The StageStats passed to GraphDisplay:Set are nil."); } - if (pPlayerStageStats == NULL) { + if (pPlayerStageStats == nullptr) { luaL_error( L, "The PlayerStageStats passed to GraphDisplay:Set are nil."); } diff --git a/src/Etterna/Actor/Menus/MenuTimer.cpp b/src/Etterna/Actor/Menus/MenuTimer.cpp index 6f33258dce..318ced2179 100644 --- a/src/Etterna/Actor/Menus/MenuTimer.cpp +++ b/src/Etterna/Actor/Menus/MenuTimer.cpp @@ -107,7 +107,7 @@ MenuTimer::Update(float fDeltaTime) fNewSecondsLeft < HURRY_UP_TRANSITION) SOUND->PlayOnceFromAnnouncer("hurry up"); - int iCrossed = (int)floorf(fOldSecondsLeft); + const int iCrossed = static_cast(floorf(fOldSecondsLeft)); if (fOldSecondsLeft > iCrossed && fNewSecondsLeft < iCrossed) // crossed { if (iCrossed <= WARNING_START) { diff --git a/src/Etterna/Actor/Menus/ModIcon.cpp b/src/Etterna/Actor/Menus/ModIcon.cpp index 57fc1ced29..da1daadc57 100644 --- a/src/Etterna/Actor/Menus/ModIcon.cpp +++ b/src/Etterna/Actor/Menus/ModIcon.cpp @@ -59,7 +59,7 @@ ModIcon::Set(const std::string& _sText) s_replace(sText, (" "), "\n"); - auto bVacant = (sText == ""); + const auto bVacant = (sText.empty()); m_sprFilled->SetVisible(!bVacant); m_sprEmpty->SetVisible(bVacant); diff --git a/src/Etterna/Actor/Menus/ModIconRow.cpp b/src/Etterna/Actor/Menus/ModIconRow.cpp index 3004a67dc8..c90b0bc14b 100644 --- a/src/Etterna/Actor/Menus/ModIconRow.cpp +++ b/src/Etterna/Actor/Menus/ModIconRow.cpp @@ -1,6 +1,5 @@ #include "Etterna/Globals/global.h" #include "Etterna/Actor/Base/ActorUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/LuaManager.h" #include "ModIconRow.h" @@ -21,7 +20,9 @@ ModIconRow::ModIconRow() ModIconRow::~ModIconRow() { - FOREACH(ModIcon*, m_vpModIcon, p) { SAFE_DELETE(*p); } + for (auto& p : m_vpModIcon) { + SAFE_DELETE(p); + } this->RemoveAllChildren(); } @@ -128,9 +129,6 @@ OptionToPreferredColumn(std::string sOptionText) for (auto g_OptionColumnEntry : g_OptionColumnEntries) if (g_OptionColumnEntry.szString == sOptionText) return g_OptionColumnEntry.iSlotIndex; - - // This warns about C1234 and noteskins. - // LOG->Warn("Unknown option: '%s'", sOptionText.c_str() ); return 0; } @@ -149,17 +147,16 @@ ModIconRow::SetFromGameState() vsText.resize(m_vpModIcon.size()); // for each option, look for the best column to place it in - for (unsigned i = 0; i < vsOptions.size(); i++) { - std::string sOption = vsOptions[i]; + for (auto sOption : vsOptions) { int iPerferredCol = OptionToPreferredColumn(sOption); - clamp(iPerferredCol, 0, (int)m_vpModIcon.size() - 1); + CLAMP(iPerferredCol, 0, static_cast(m_vpModIcon.size()) - 1); if (iPerferredCol == -1) continue; // skip // search for a vacant spot for (int j = iPerferredCol; j < NUM_OPTION_ICONS; j++) { - if (vsText[j] != "") { + if (!vsText[j].empty()) { continue; } else { vsText[j] = sOption; diff --git a/src/Etterna/Actor/Menus/MusicWheel.cpp b/src/Etterna/Actor/Menus/MusicWheel.cpp index 5e9afea92d..af472fc68e 100644 --- a/src/Etterna/Actor/Menus/MusicWheel.cpp +++ b/src/Etterna/Actor/Menus/MusicWheel.cpp @@ -129,7 +129,7 @@ MusicWheel::BeginScreen() { const auto& from = getWheelItemsData(SORT_MODE_MENU); for (auto* i : from) { - ASSERT(&*i->m_pAction != NULL); + ASSERT(&*i->m_pAction != nullptr); if (i->m_pAction->DescribesCurrentModeForAllPlayers()) { m_sLastModeMenuItem = i->m_pAction->m_sName; break; diff --git a/src/Etterna/Actor/Menus/MusicWheelItem.cpp b/src/Etterna/Actor/Menus/MusicWheelItem.cpp index 40df5de6bf..3114360548 100644 --- a/src/Etterna/Actor/Menus/MusicWheelItem.cpp +++ b/src/Etterna/Actor/Menus/MusicWheelItem.cpp @@ -65,7 +65,7 @@ MusicWheelItem::MusicWheelItem(const std::string& sType) FOREACH_ENUM(MusicWheelItemType, i) { - m_pText[i] = NULL; + m_pText[i] = nullptr; // Don't init text for Type_Song. It uses a TextBanner. if (i == MusicWheelItemType_Song) @@ -124,8 +124,8 @@ MusicWheelItem::MusicWheelItem(const MusicWheelItem& cpy) FOREACH_ENUM(MusicWheelItemType, i) { - if (cpy.m_pText[i] == NULL) { - m_pText[i] = NULL; + if (cpy.m_pText[i] == nullptr) { + m_pText[i] = nullptr; } else { m_pText[i] = new BitmapText(*cpy.m_pText[i]); this->AddChild(m_pText[i]); @@ -265,11 +265,11 @@ MusicWheelItem::RefreshGrades() { const auto* pWID = dynamic_cast(m_pData); - if (pWID == NULL) + if (pWID == nullptr) return; // LoadFromWheelItemData() hasn't been called yet. m_pGradeDisplay->SetVisible(false); - if (pWID->m_pSong == NULL) + if (pWID->m_pSong == nullptr) return; Difficulty dc; diff --git a/src/Etterna/Actor/Menus/MusicWheelItem.h b/src/Etterna/Actor/Menus/MusicWheelItem.h index dacb78dc66..708cfc4ec2 100644 --- a/src/Etterna/Actor/Menus/MusicWheelItem.h +++ b/src/Etterna/Actor/Menus/MusicWheelItem.h @@ -29,7 +29,7 @@ enum MusicWheelItemType const std::string& MusicWheelItemTypeToString(MusicWheelItemType i); /** @brief An item on the MusicWheel. */ -class MusicWheelItem : public WheelItemBase +class MusicWheelItem final : public WheelItemBase { public: MusicWheelItem(const std::string& sType = "MusicWheelItem"); @@ -55,12 +55,11 @@ class MusicWheelItem : public WheelItemBase AutoActor m_pGradeDisplay; }; -struct MusicWheelItemData : public WheelItemBaseData +struct MusicWheelItemData : WheelItemBaseData { MusicWheelItemData() - : m_pSong(NULL) + : m_pSong(nullptr) , m_sLabel("") - , m_pAction() { } MusicWheelItemData(WheelItemDataType type, diff --git a/src/Etterna/Actor/Menus/OptionRow.cpp b/src/Etterna/Actor/Menus/OptionRow.cpp index 468b7d569e..77ff9c7fb2 100644 --- a/src/Etterna/Actor/Menus/OptionRow.cpp +++ b/src/Etterna/Actor/Menus/OptionRow.cpp @@ -40,13 +40,13 @@ MOD_ICON_X_NAME(size_t p) OptionRow::OptionRow(const OptionRowType* pSource) { m_pParentType = pSource; - m_pHand = NULL; + m_pHand = nullptr; - m_textTitle = NULL; - m_ModIcons = NULL; + m_textTitle = nullptr; + m_ModIcons = nullptr; m_RowType = OptionRow::RowType_Normal; - m_sprFrame = NULL; + m_sprFrame = nullptr; Clear(); this->AddChild(&m_Frame); @@ -70,7 +70,7 @@ OptionRow::Clear() m_textItems.clear(); m_Underline.clear(); - if (m_pHand != NULL) { + if (m_pHand != nullptr) { for (auto& m : m_pHand->m_vsReloadRowMessages) { MESSAGEMAN->Unsubscribe(this, m); } @@ -118,7 +118,7 @@ OptionRowType::Load(const std::string& sMetricsGroup, Actor* pParent) Actor* pActor = ActorUtil::MakeActor(THEME->GetPathG(sMetricsGroup, "Frame"), pParent); - if (pActor == NULL) + if (pActor == nullptr) pActor = new Actor; m_sprFrame.Load(pActor); m_sprFrame->SetName("Frame"); @@ -177,7 +177,7 @@ OptionRow::ChoicesChanged(RowType type, bool reset_focus) vbSelected.resize(m_pHand->m_Def.m_vsChoices.size(), false); // set select the first item if a SELECT_ONE row - if (vbSelected.size() && m_pHand->m_Def.m_selectType == SELECT_ONE) + if (!vbSelected.empty() && m_pHand->m_Def.m_selectType == SELECT_ONE) vbSelected[0] = true; // TRICKY: Insert a down arrow as the first choice in the row. @@ -206,7 +206,8 @@ OptionRow::GetRowTitle() const // HACK: tack the BPM onto the name of the speed line if (CompareNoCase(m_pHand->m_Def.m_sName, "speed") == 0) { - bool bShowBpmInSpeedTitle = m_pParentType->SHOW_BPM_IN_SPEED_TITLE; + const bool bShowBpmInSpeedTitle = + m_pParentType->SHOW_BPM_IN_SPEED_TITLE; if (bShowBpmInSpeedTitle) { DisplayBpms bpms; @@ -286,10 +287,10 @@ OptionRow::InitText(RowType type) } // Try to fit everything on one line. - float fTotalWidth = + const float fTotalWidth = m_pParentType->ITEMS_END_X - m_pParentType->ITEMS_START_X; if (fWidth > fTotalWidth) { - float fPossibleBaseZoom = fTotalWidth / fWidth; + const float fPossibleBaseZoom = fTotalWidth / fWidth; if (fPossibleBaseZoom >= m_pParentType->ITEMS_MIN_BASE_ZOOM) fBaseZoom = fPossibleBaseZoom; else @@ -324,7 +325,7 @@ OptionRow::InitText(RowType type) int iWidth, iX, iY; GetWidthXY(PLAYER_1, 0, iWidth, iX, iY); - pCursor->SetX(float(iX)); + pCursor->SetX(static_cast(iX)); pCursor->SetBarWidth(iWidth); } break; @@ -343,7 +344,7 @@ OptionRow::InitText(RowType type) bt->SetText(sText); // set the X position of each item in the line - float fItemWidth = bt->GetZoomedWidth(); + const float fItemWidth = bt->GetZoomedWidth(); fX += fItemWidth / 2; bt->SetX(fX); @@ -410,7 +411,7 @@ OptionRow::AfterImportOptions(PlayerNumber pn) switch (m_pHand->m_Def.m_selectType) { case SELECT_ONE: { // Make sure the row actually has a selection. - int iSelection = GetOneSelection(pn, true); + const int iSelection = GetOneSelection(pn, true); if (iSelection == -1) { ASSERT(!m_vbSelected.empty()); m_vbSelected[0] = true; @@ -435,10 +436,10 @@ OptionRow::PositionUnderlines(PlayerNumber pn) PlayerNumber pnTakeSelectedFrom = m_pHand->m_Def.m_bOneChoiceForAllPlayers ? PLAYER_1 : pn; - for (int i = 0; i < (int)vpUnderlines.size(); i++) { + for (int i = 0; i < static_cast(vpUnderlines.size()); i++) { OptionsCursor& ul = *vpUnderlines[i]; - int iChoiceWithFocus = + const int iChoiceWithFocus = (m_pHand->m_Def.m_layoutType == LAYOUT_SHOW_ONE_IN_ROW) ? GetChoiceInRowWithFocus() : i; @@ -448,8 +449,9 @@ OptionRow::PositionUnderlines(PlayerNumber pn) float fAlpha = 1.0f; if (m_pHand->m_Def.m_layoutType == LAYOUT_SHOW_ONE_IN_ROW) { - bool bRowEnabled = m_pHand->m_Def.m_vEnabledForPlayers.find(pn) != - m_pHand->m_Def.m_vEnabledForPlayers.end(); + const bool bRowEnabled = + m_pHand->m_Def.m_vEnabledForPlayers.find(pn) != + m_pHand->m_Def.m_vEnabledForPlayers.end(); if (!m_pHand->m_Def.m_bOneChoiceForAllPlayers) { if (m_bRowHasFocus) @@ -472,8 +474,8 @@ OptionRow::PositionUnderlines(PlayerNumber pn) ASSERT(m_vbSelected.size() == m_pHand->m_Def.m_vsChoices.size()); - bool bSelected = m_vbSelected[iChoiceWithFocus]; - bool bVisible = bSelected && GAMESTATE->IsHumanPlayer(pn); + const bool bSelected = m_vbSelected[iChoiceWithFocus]; + const bool bVisible = bSelected && GAMESTATE->IsHumanPlayer(pn); ul.BeginTweening(m_pParentType->TWEEN_SECONDS); ul.SetVisible(bVisible); @@ -485,7 +487,7 @@ void OptionRow::PositionIcons(PlayerNumber pn) { ModIcon* pIcon = m_ModIcons; - if (pIcon == NULL) + if (pIcon == nullptr) return; pIcon->SetX(m_pParentType->MOD_ICON_X.GetValue(pn)); @@ -497,15 +499,16 @@ OptionRow::UpdateText(PlayerNumber p) { switch (m_pHand->m_Def.m_layoutType) { case LAYOUT_SHOW_ONE_IN_ROW: { - unsigned pn = m_pHand->m_Def.m_bOneChoiceForAllPlayers ? 0 : p; - int iChoiceWithFocus = m_iChoiceInRowWithFocus; + const unsigned pn = + m_pHand->m_Def.m_bOneChoiceForAllPlayers ? 0 : p; + const int iChoiceWithFocus = m_iChoiceInRowWithFocus; if (iChoiceWithFocus == -1) break; - std::string sText = GetThemedItemText(iChoiceWithFocus); + const std::string sText = GetThemedItemText(iChoiceWithFocus); // If player_no is 2 and there is no player 1: - int index = min(pn, m_textItems.size() - 1); + const int index = min(pn, m_textItems.size() - 1); // TODO: Always have one textItem for each player @@ -567,7 +570,7 @@ OptionRow::UpdateEnabledDisabled() for (unsigned j = 0; j < m_textItems.size(); j++) { bool bThisItemHasFocusByAny = false; if (m_bRowHasFocus) { - if ((int)j == GetChoiceInRowWithFocus()) { + if (static_cast(j) == GetChoiceInRowWithFocus()) { bThisItemHasFocusByAny = true; break; } @@ -635,14 +638,14 @@ OptionRow::SetModIcon(PlayerNumber pn, msg.SetParam("GameCommand", &gc); msg.SetParam("Text", sText); m_sprFrame->HandleMessage(msg); - if (m_ModIcons != NULL) + if (m_ModIcons != nullptr) m_ModIcons->Set(sText); } const BitmapText& OptionRow::GetTextItemForRow(PlayerNumber pn, int iChoiceOnRow) const { - bool bOneChoice = m_pHand->m_Def.m_bOneChoiceForAllPlayers; + const bool bOneChoice = m_pHand->m_Def.m_bOneChoiceForAllPlayers; int index = -1; switch (m_pHand->m_Def.m_layoutType) { case LAYOUT_SHOW_ONE_IN_ROW: @@ -659,7 +662,7 @@ OptionRow::GetTextItemForRow(PlayerNumber pn, int iChoiceOnRow) const m_pHand->m_Def.m_layoutType)); } - ASSERT_M(index < (int)m_textItems.size(), + ASSERT_M(index < static_cast(m_textItems.size()), ssprintf("%i < %i", index, (int)m_textItems.size())); return *m_textItems[index]; } @@ -730,7 +733,7 @@ OptionRow::GetChoiceInRowWithFocus() const { if (m_pHand->m_Def.m_vsChoices.empty()) return -1; - int iChoice = m_iChoiceInRowWithFocus; + const int iChoice = m_iChoiceInRowWithFocus; return iChoice; } @@ -745,7 +748,8 @@ OptionRow::SetChoiceInRowWithFocus(PlayerNumber pn, int iChoice) { if (m_pHand->m_Def.m_bOneChoiceForAllPlayers) pn = PLAYER_1; - ASSERT(iChoice >= 0 && iChoice < (int)m_pHand->m_Def.m_vsChoices.size()); + ASSERT(iChoice >= 0 && + iChoice < static_cast(m_pHand->m_Def.m_vsChoices.size())); m_iChoiceInRowWithFocus = iChoice; UpdateText(pn); @@ -802,7 +806,7 @@ OptionRow::SetSelected(PlayerNumber pn, int iChoice, bool b) bool OptionRow::NotifyHandlerOfSelection(PlayerNumber pn, int choice) { - bool changed = m_pHand->NotifyOfSelection( + const bool changed = m_pHand->NotifyOfSelection( pn, choice - static_cast(m_bFirstItemGoesDown)); if (changed) { ChoicesChanged(m_RowType, false); @@ -895,7 +899,7 @@ OptionRow::HandleMessage(const Message& msg) void OptionRow::ImportOptions(const PlayerNumber& vpns) { - ASSERT(m_pHand->m_Def.m_vsChoices.size() > 0); + ASSERT(!m_pHand->m_Def.m_vsChoices.empty()); PlayerNumber p = PLAYER_1; @@ -915,12 +919,12 @@ OptionRow::ImportOptions(const PlayerNumber& vpns) int OptionRow::ExportOptions(const PlayerNumber& vpns, bool bRowHasFocus) { - ASSERT(m_pHand->m_Def.m_vsChoices.size() > 0); + ASSERT(!m_pHand->m_Def.m_vsChoices.empty()); int iChangeMask = 0; PlayerNumber p = PLAYER_1; - bool bFocus = bRowHasFocus; + const bool bFocus = bRowHasFocus; VerifySelected( m_pHand->m_Def.m_selectType, m_vbSelected, m_pHand->m_Def.m_sName); @@ -929,7 +933,7 @@ OptionRow::ExportOptions(const PlayerNumber& vpns, bool bRowHasFocus) // SELECT_NONE rows get exported if they have focus when the user // presses Start. - int iChoice = GetChoiceInRowWithFocus(); + const int iChoice = GetChoiceInRowWithFocus(); if (m_pHand->m_Def.m_selectType == SELECT_NONE && bFocus && iChoice != -1) m_vbSelected[iChoice] = true; diff --git a/src/Etterna/Actor/Menus/OptionsList.cpp b/src/Etterna/Actor/Menus/OptionsList.cpp index 3c854f69ef..3843bb24eb 100644 --- a/src/Etterna/Actor/Menus/OptionsList.cpp +++ b/src/Etterna/Actor/Menus/OptionsList.cpp @@ -5,7 +5,6 @@ #include "OptionsList.h" #include "Etterna/Models/Misc/PlayerState.h" #include "Etterna/Models/Songs/SongUtil.h" -#include "Etterna/Models/Misc/Foreach.h" #define LINE(sLineName) \ THEME->GetMetric(m_sName, ssprintf("Line%s", (sLineName).c_str())) @@ -46,10 +45,10 @@ OptionListRow::SetFromHandler(const OptionRowHandler* pHandler) this->FinishTweening(); this->RemoveAllChildren(); - if (pHandler == NULL) + if (pHandler == nullptr) return; - int iNum = max(pHandler->m_Def.m_vsChoices.size(), m_Text.size()) + 1; + const int iNum = max(pHandler->m_Def.m_vsChoices.size(), m_Text.size()) + 1; m_Text.resize(iNum, m_Text[0]); m_Underlines.resize(iNum, m_Underlines[0]); @@ -64,7 +63,7 @@ OptionListRow::SetFromHandler(const OptionRowHandler* pHandler) SetTextFromHandler(pHandler); const unsigned iCnt = pHandler->m_Def.m_vsChoices.size(); - m_bItemsInTwoRows = (int)iCnt > MAX_ITEMS_BEFORE_SPLIT; + m_bItemsInTwoRows = static_cast(iCnt) > MAX_ITEMS_BEFORE_SPLIT; const float fWidth = ITEMS_SPLIT_WIDTH; float fY = 0; for (unsigned i = 0; i < iCnt; ++i) { @@ -89,7 +88,7 @@ OptionListRow::SetFromHandler(const OptionRowHandler* pHandler) fY += ITEMS_SPACING_Y; } - int iExit = pHandler->m_Def.m_vsChoices.size(); + const int iExit = pHandler->m_Def.m_vsChoices.size(); m_Text[iExit].SetText("Exit"); // XXX localize m_Text[iExit].SetXY(0, fY); this->AddChild(&m_Text[iExit]); @@ -106,10 +105,10 @@ OptionListRow::SetTextFromHandler(const OptionRowHandler* pHandler) std::string sDest = pHandler->GetScreen(i); if (m_pOptions->m_setDirectRows.find(sDest) != m_pOptions->m_setDirectRows.end() && - sDest.size()) { + !sDest.empty()) { const OptionRowHandler* pTarget = m_pOptions->m_Rows[sDest]; if (pTarget->m_Def.m_selectType == SELECT_ONE) { - int iSelection = m_pOptions->GetOneSelection(sDest); + const int iSelection = m_pOptions->GetOneSelection(sDest); sText += ": " + pTarget->GetThemedItemText(iSelection); } } @@ -127,15 +126,15 @@ OptionListRow::SetUnderlines(const vector& aSelections, bool bSelected = aSelections[i]; std::string sDest = pHandler->GetScreen(i); - if (sDest.size()) { + if (!sDest.empty()) { /* This is a submenu. Underline the row if its options have been * changed from the default. */ const OptionRowHandler* pTarget = m_pOptions->m_Rows[sDest]; if (pTarget->m_Def.m_selectType == SELECT_ONE) { - int iSelection = m_pOptions->GetOneSelection(sDest); + const int iSelection = m_pOptions->GetOneSelection(sDest); const OptionRowHandler* lHandler = m_pOptions->m_Rows.find(sDest)->second; - int iDefault = lHandler->GetDefaultOption(); + const int iDefault = lHandler->GetDefaultOption(); if (iDefault != -1 && iSelection != iDefault) bSelected = true; } else if (pTarget->m_Def.m_selectType == SELECT_MULTIPLE) { @@ -155,8 +154,8 @@ OptionListRow::SetUnderlines(const vector& aSelections, void OptionListRow::PositionCursor(Actor* pCursor, int iSelection) { - float fX = m_Text[iSelection].GetDestX(); - float fY = m_Text[iSelection].GetDestY(); + const float fX = m_Text[iSelection].GetDestX(); + const float fY = m_Text[iSelection].GetDestY(); if (m_bItemsInTwoRows) pCursor->PlayCommand("PositionTwoRows"); else @@ -167,7 +166,7 @@ OptionListRow::PositionCursor(Actor* pCursor, int iSelection) OptionsList::OptionsList() { m_iCurrentRow = 0; - m_pLinked = NULL; + m_pLinked = nullptr; m_bStartIsDown = false; m_bAcceptStartRelease = false; m_pn = PLAYER_1; @@ -176,8 +175,8 @@ OptionsList::OptionsList() OptionsList::~OptionsList() { - FOREACHM(std::string, OptionRowHandler*, m_Rows, hand) - delete hand->second; + for (auto& hand : m_Rows) + delete hand.second; } void @@ -197,8 +196,8 @@ OptionsList::Load(const std::string& sType, PlayerNumber pn) vector asDirectLines; split(DIRECT_LINES, ",", asDirectLines, true); - FOREACH(std::string, asDirectLines, s) - m_setDirectRows.insert(*s); + for (auto& s : asDirectLines) + m_setDirectRows.insert(s); vector setToLoad; split(TOP_MENUS, ",", setToLoad); @@ -216,7 +215,7 @@ OptionsList::Load(const std::string& sType, PlayerNumber pn) ParseCommands(sRowCommands, cmds, false); OptionRowHandler* pHand = OptionRowHandlerUtil::Make(cmds); - if (pHand == NULL) { + if (pHand == nullptr) { LuaHelpers::ReportScriptErrorFmt( "Invalid OptionRowHandler '%s' in %s::Line%s", cmds.GetOriginalCommandString().c_str(), @@ -250,9 +249,8 @@ void OptionsList::Reset() { /* Import options. */ - FOREACHM(std::string, OptionRowHandler*, m_Rows, hand) - { - std::string sLineName = hand->first; + for (auto& hand : m_Rows) { + std::string sLineName = hand.first; ImportRow(sLineName); } } @@ -267,11 +265,11 @@ OptionsList::Open() MESSAGEMAN->Broadcast(msg); /* Push the initial menu. */ - ASSERT(m_asMenuStack.size() == 0); + ASSERT(m_asMenuStack.empty()); Push(TOP_MENU); this->FinishTweening(); - m_Row[!m_iCurrentRow].SetFromHandler(NULL); + m_Row[!m_iCurrentRow].SetFromHandler(nullptr); this->PlayCommand("TweenOn"); } @@ -297,14 +295,15 @@ OptionsList::GetCurrentRow() const const OptionRowHandler* OptionsList::GetCurrentHandler() { - std::string sCurrentRow = GetCurrentRow(); + const std::string sCurrentRow = GetCurrentRow(); return m_Rows[sCurrentRow]; } int OptionsList::GetOneSelection(const std::string& sRow, bool bAllowFail) const { - map>::const_iterator it = m_bSelections.find(sRow); + const map>::const_iterator it = + m_bSelections.find(sRow); ASSERT_M(it != m_bSelections.end(), sRow); const vector& bSelections = it->second; for (unsigned i = 0; i < bSelections.size(); i++) { @@ -335,7 +334,7 @@ OptionsList::SwitchMenu(int iDir) * the submenus follow. This allows consistent navigation; moving right * from the main menu walks through the menus, moving left goes back as far * as the main menu. Don't loop, so it's harder to lose track of menus. */ - std::string sTopRow = m_asMenuStack.front(); + const std::string sTopRow = m_asMenuStack.front(); const OptionRowHandler* pHandler = m_Rows[sTopRow]; int iCurrentRow = 0; if (m_asMenuStack.size() == 1) @@ -345,9 +344,9 @@ OptionsList::SwitchMenu(int iDir) iCurrentRow += iDir; if (iCurrentRow >= 0) { - if (iCurrentRow >= (int)pHandler->m_Def.m_vsChoices.size()) + if (iCurrentRow >= static_cast(pHandler->m_Def.m_vsChoices.size())) return; - std::string sDest = pHandler->GetScreen(iCurrentRow); + const std::string sDest = pHandler->GetScreen(iCurrentRow); if (sDest.empty()) return; @@ -381,7 +380,7 @@ OptionsList::Input(const InputEventPlus& input) const OptionRowHandler* pHandler = GetCurrentHandler(); - PlayerNumber pn = input.pn; + const PlayerNumber pn = input.pn; if (m_bStartIsDown) { if (input.MenuI == GAME_BUTTON_LEFT || input.MenuI == GAME_BUTTON_RIGHT) { @@ -392,18 +391,20 @@ OptionsList::Input(const InputEventPlus& input) const std::string& sCurrentRow = m_asMenuStack.back(); vector& bSelections = m_bSelections[sCurrentRow]; - if (m_iMenuStackSelection == (int)bSelections.size()) + if (m_iMenuStackSelection == static_cast(bSelections.size())) return false; - std::string sDest = pHandler->GetScreen(m_iMenuStackSelection); + const std::string sDest = + pHandler->GetScreen(m_iMenuStackSelection); if (m_setDirectRows.find(sDest) != m_setDirectRows.end() && - sDest.size()) { + !sDest.empty()) { const OptionRowHandler* pTarget = m_Rows[sDest]; vector& bTargetSelections = m_bSelections[sDest]; if (pTarget->m_Def.m_selectType == SELECT_ONE) { int iSelection = GetOneSelection(sDest); - int iDir = (input.MenuI == GAME_BUTTON_RIGHT ? +1 : -1); + const int iDir = + (input.MenuI == GAME_BUTTON_RIGHT ? +1 : -1); iSelection += iDir; wrap(iSelection, bTargetSelections.size()); SelectItem(sDest, iSelection); @@ -530,7 +531,7 @@ OptionsList::ImportRow(const std::string& sRow) vector aSelections; OptionRowHandler* pHandler = m_Rows[sRow]; aSelections.resize(pHandler->m_Def.m_vsChoices.size()); - pHandler->ImportOption(NULL, m_pn, aSelections); + pHandler->ImportOption(nullptr, m_pn, aSelections); m_bSelections[sRow] = aSelections; if (m_setTopMenus.find(sRow) != m_setTopMenus.end()) @@ -584,7 +585,7 @@ OptionsList::Pop() return; } - std::string sLastMenu = m_asMenuStack.back(); + const std::string sLastMenu = m_asMenuStack.back(); m_asMenuStack.pop_back(); @@ -593,7 +594,7 @@ OptionsList::Pop() /* If the old menu exists as a target from the new menu, switch to it. */ const OptionRowHandler* pHandler = GetCurrentHandler(); - int iIndex = FindScreenInHandler(pHandler, sLastMenu); + const int iIndex = FindScreenInHandler(pHandler, sLastMenu); if (iIndex != -1) m_iMenuStackSelection = iIndex; @@ -616,7 +617,7 @@ OptionsList::SelectItem(const std::string& sRowName, int iMenuItem) vector& bSelections = m_bSelections[sRowName]; if (pHandler->m_Def.m_selectType == SELECT_MULTIPLE) { - bool bSelected = !bSelections[iMenuItem]; + const bool bSelected = !bSelections[iMenuItem]; bSelections[iMenuItem] = bSelected; // if( bSelected ) @@ -639,7 +640,7 @@ OptionsList::SelectionsChanged(const std::string& sRowName) const OptionRowHandler* pHandler = m_Rows[sRowName]; vector& bSelections = m_bSelections[sRowName]; - if (pHandler->m_Def.m_bOneChoiceForAllPlayers && m_pLinked != NULL) { + if (pHandler->m_Def.m_bOneChoiceForAllPlayers && m_pLinked != nullptr) { vector& bLinkedSelections = m_pLinked->m_bSelections[sRowName]; bLinkedSelections = bSelections; @@ -667,7 +668,7 @@ OptionsList::Start() const OptionRowHandler* pHandler = GetCurrentHandler(); const std::string& sCurrentRow = m_asMenuStack.back(); vector& bSelections = m_bSelections[sCurrentRow]; - if (m_iMenuStackSelection == (int)bSelections.size()) { + if (m_iMenuStackSelection == static_cast(bSelections.size())) { Pop(); Message msg("OptionsListPop"); @@ -688,10 +689,9 @@ OptionsList::Start() GAMESTATE->ResetToDefaultSongOptions(ModsLevel_Preferred); /* Import options. */ - FOREACHM(std::string, OptionRowHandler*, m_Rows, hand) - { - ImportRow(hand->first); - SelectionsChanged(hand->first); + for (auto& hand : m_Rows) { + ImportRow(hand.first); + SelectionsChanged(hand.first); } UpdateMenuFromSelections(); @@ -704,8 +704,8 @@ OptionsList::Start() } } - std::string sDest = pHandler->GetScreen(m_iMenuStackSelection); - if (sDest.size()) { + const std::string sDest = pHandler->GetScreen(m_iMenuStackSelection); + if (!sDest.empty()) { Push(sDest); TweenOnCurrentRow(true); @@ -719,7 +719,7 @@ OptionsList::Start() SelectItem(GetCurrentRow(), m_iMenuStackSelection); /* Move to the exit row. */ - m_iMenuStackSelection = (int)bSelections.size(); + m_iMenuStackSelection = static_cast(bSelections.size()); PositionCursor(); Message msg("OptionsListStart"); diff --git a/src/Etterna/Actor/Menus/OptionsList.h b/src/Etterna/Actor/Menus/OptionsList.h index 9c06ca91d5..20f87df186 100644 --- a/src/Etterna/Actor/Menus/OptionsList.h +++ b/src/Etterna/Actor/Menus/OptionsList.h @@ -4,7 +4,6 @@ #include "Etterna/Actor/Base/BitmapText.h" #include "Etterna/Models/Misc/CodeSet.h" #include "Etterna/Models/Misc/OptionRowHandler.h" -#include "Etterna/Actor/Menus/OptionsCursor.h" #include "Etterna/Screen/Others/ScreenWithMenuElements.h" #include "Etterna/Models/Misc/ThemeMetric.h" @@ -25,9 +24,9 @@ class OptionListRow : public ActorFrame private: OptionsList* m_pOptions = nullptr; - vector m_Text; + std::vector m_Text; // underline for each ("self or child has selection") - vector m_Underlines; + std::vector m_Underlines; bool m_bItemsInTwoRows = false; @@ -54,7 +53,7 @@ class OptionsList : public ActorFrame void Close(); bool Input(const InputEventPlus& input); - bool IsOpened() const { return m_asMenuStack.size() > 0; } + bool IsOpened() const { return !m_asMenuStack.empty(); } bool Start(); // return true if the last menu was popped in response to this // press @@ -88,18 +87,19 @@ class OptionsList : public ActorFrame bool m_bStartIsDown; bool m_bAcceptStartRelease; - vector m_asLoadedRows; + std::vector m_asLoadedRows; map m_Rows; - map> m_bSelections; + map> m_bSelections; set m_setDirectRows; - set m_setTopMenus; // list of top-level menus, pointing to submenus + set + m_setTopMenus; // list of top-level menus, pointing to submenus PlayerNumber m_pn; AutoActor m_Cursor; OptionListRow m_Row[2]; int m_iCurrentRow; - vector m_asMenuStack; + std::vector m_asMenuStack; int m_iMenuStackSelection; }; diff --git a/src/Etterna/Actor/Menus/RoomInfoDisplay.cpp b/src/Etterna/Actor/Menus/RoomInfoDisplay.cpp index ad4265c13e..70a2d02946 100644 --- a/src/Etterna/Actor/Menus/RoomInfoDisplay.cpp +++ b/src/Etterna/Actor/Menus/RoomInfoDisplay.cpp @@ -171,7 +171,7 @@ RoomInfoDisplay::SetRoomInfo(const RoomInfo& info) m_playerList.resize(info.players.size()); } else if (m_playerList.size() < info.players.size()) { // add elements if our old list is smaller - int oldsize = m_playerList.size(); + const int oldsize = m_playerList.size(); m_playerList.resize(info.players.size()); for (size_t i = oldsize; i < m_playerList.size(); i++) { m_playerList[i] = new BitmapText; diff --git a/src/Etterna/Actor/Menus/ScrollBar.cpp b/src/Etterna/Actor/Menus/ScrollBar.cpp index 13be4a4e15..094222002b 100644 --- a/src/Etterna/Actor/Menus/ScrollBar.cpp +++ b/src/Etterna/Actor/Menus/ScrollBar.cpp @@ -5,7 +5,7 @@ ScrollBar::ScrollBar() { - std::string sMetricsGroup = "ScrollBar"; + const std::string sMetricsGroup = "ScrollBar"; m_sprMiddle.Load(THEME->GetPathG(sMetricsGroup, "middle")); this->AddChild(m_sprMiddle); @@ -21,10 +21,9 @@ ScrollBar::ScrollBar() m_sprScrollTickThumb.Load(THEME->GetPathG(sMetricsGroup, "TickThumb")); this->AddChild(m_sprScrollTickThumb); - for (unsigned i = 0; i < ARRAYLEN(m_sprScrollStretchThumb); i++) { - m_sprScrollStretchThumb[i].Load( - THEME->GetPathG(sMetricsGroup, "StretchThumb")); - this->AddChild(m_sprScrollStretchThumb[i]); + for (auto& i : m_sprScrollStretchThumb) { + i.Load(THEME->GetPathG(sMetricsGroup, "StretchThumb")); + this->AddChild(i); } SetBarHeight(100); diff --git a/src/Etterna/Actor/Menus/TextBanner.cpp b/src/Etterna/Actor/Menus/TextBanner.cpp index addb455fc5..83e11009e9 100644 --- a/src/Etterna/Actor/Menus/TextBanner.cpp +++ b/src/Etterna/Actor/Menus/TextBanner.cpp @@ -80,7 +80,7 @@ TextBanner::SetFromString(const string& sDisplayTitle, void TextBanner::SetFromSong(const Song* pSong) { - if (pSong == NULL) { + if (pSong == nullptr) { SetFromString("", "", "", "", "", ""); return; } diff --git a/src/Etterna/Actor/Menus/TextBanner.h b/src/Etterna/Actor/Menus/TextBanner.h index 10d6de0dc1..f58fbd08c9 100644 --- a/src/Etterna/Actor/Menus/TextBanner.h +++ b/src/Etterna/Actor/Menus/TextBanner.h @@ -8,12 +8,12 @@ #include "Etterna/Actor/Base/BitmapText.h" class Song; -class TextBanner : public ActorFrame +class TextBanner final : public ActorFrame { public: TextBanner(); TextBanner(const TextBanner& cpy); - TextBanner* Copy() const override; + [[nodiscard]] TextBanner* Copy() const override; void LoadFromNode(const XNode* pNode) override; void Load(const std::string& sMetricsGroup); // load metrics diff --git a/src/Etterna/Actor/Menus/WheelBase.cpp b/src/Etterna/Actor/Menus/WheelBase.cpp index d63f65c1e3..f3aead8f62 100644 --- a/src/Etterna/Actor/Menus/WheelBase.cpp +++ b/src/Etterna/Actor/Menus/WheelBase.cpp @@ -105,12 +105,12 @@ WheelBase::SetItemPosition(Actor& item, void WheelBase::UpdateScrollbar() { - int iTotalNumItems = m_CurWheelItemData.size(); - float fItemAt = m_iSelection - m_fPositionOffsetFromSelection; + const int iTotalNumItems = m_CurWheelItemData.size(); + const float fItemAt = m_iSelection - m_fPositionOffsetFromSelection; { float fSize = static_cast(NUM_WHEEL_ITEMS) / iTotalNumItems; - float fCenter = fItemAt / iTotalNumItems; + const float fCenter = fItemAt / iTotalNumItems; fSize *= 0.5f; m_ScrollBar.SetPercentage(fCenter, fSize); @@ -180,7 +180,7 @@ WheelBase::Update(float fDeltaTime) if (IsMoving() != 0) { // We're automatically moving. Move linearly, and don't clamp to the // selection. - float fSpinSpeed = m_SpinSpeed * m_Moving; + const float fSpinSpeed = m_SpinSpeed * m_Moving; m_fPositionOffsetFromSelection -= fSpinSpeed * fDeltaTime; /* Make sure that we don't go further than 1 away, in case the speed is @@ -205,7 +205,7 @@ WheelBase::Update(float fDeltaTime) } } else { // "rotate" wheel toward selected song - float fSpinSpeed = + const float fSpinSpeed = 0.2f + fabsf(m_fPositionOffsetFromSelection) / SWITCH_SECONDS; if (m_fPositionOffsetFromSelection > 0) { @@ -249,7 +249,7 @@ WheelBase::Select() // return true if this selection can end the screen m_LastSelection = m_CurWheelItemData[m_iSelection]; return true; case WheelItemDataType_Section: { - std::string sThisItemSectionName = + const std::string sThisItemSectionName = m_CurWheelItemData[m_iSelection]->m_sText; if (m_sExpandedSectionName == sThisItemSectionName) // already expanded @@ -326,7 +326,7 @@ WheelBase::ChangeMusicUnlessLocked(int n) { if (m_WheelState == STATE_LOCKED) { if (n != 0) { - int iSign = n / abs(n); + const int iSign = n / abs(n); m_fLockedWheelVelocity = iSign * LOCKED_INITIAL_VELOCITY; m_soundLocked.Play(true); } @@ -344,7 +344,7 @@ WheelBase::Move(int n) if (m_WheelState == STATE_LOCKED) { if (n != 0) { - int iSign = n / abs(n); + const int iSign = n / abs(n); m_fLockedWheelVelocity = iSign * LOCKED_INITIAL_VELOCITY; m_soundLocked.Play(true); } @@ -429,7 +429,7 @@ WheelBase::RebuildWheelItems(int iDist) // find the first wheel item shown iFirstVisibleIndex -= NUM_WHEEL_ITEMS / 2; - ASSERT(data.size() != 0); + ASSERT(!data.empty()); wrap(iFirstVisibleIndex, data.size()); // iIndex is now the index of the lowest WheelItem to draw @@ -505,7 +505,7 @@ class LunaWheelBase : public Luna } static int GetWheelItem(T* p, lua_State* L) { - int iItem = IArg(1); + const int iItem = IArg(1); WheelItemBase* pItem = p->GetWheelItem(iItem); if (pItem == nullptr) { diff --git a/src/Etterna/Actor/Menus/WheelBase.h b/src/Etterna/Actor/Menus/WheelBase.h index 487e31f465..bd678c5dd3 100644 --- a/src/Etterna/Actor/Menus/WheelBase.h +++ b/src/Etterna/Actor/Menus/WheelBase.h @@ -42,7 +42,7 @@ class WheelBase : public ActorFrame virtual void Move(int n); void ChangeMusicUnlessLocked(int n); /* +1 or -1 */ - virtual void ChangeMusic(int dist); /* +1 or -1 */ + virtual void ChangeMusic(int dist); /* +1 or -1 */ virtual void SetOpenSection(const std::string& group) {} // Return true if we're moving fast automatically. @@ -80,8 +80,8 @@ class WheelBase : public ActorFrame WheelItemBaseData* LastSelected(); WheelItemBase* GetWheelItem(int i) { - if (i < 0 || i >= (int)m_WheelBaseItems.size()) - return NULL; + if (i < 0 || i >= static_cast(m_WheelBaseItems.size())) + return nullptr; return m_WheelBaseItems[i]; } std::string GetExpandedSectionName() { return m_sExpandedSectionName; } diff --git a/src/Etterna/Actor/Menus/WheelItemBase.h b/src/Etterna/Actor/Menus/WheelItemBase.h index 70958e3c64..2ab30e5947 100644 --- a/src/Etterna/Actor/Menus/WheelItemBase.h +++ b/src/Etterna/Actor/Menus/WheelItemBase.h @@ -2,11 +2,12 @@ #define WHEEL_ITEM_BASE_H #include "Etterna/Actor/Base/ActorFrame.h" -#include "Etterna/Actor/Base/AutoActor.h" #include "Etterna/Actor/Base/BitmapText.h" #include "Etterna/Models/Misc/GameConstantsAndTypes.h" #include "Etterna/Models/Misc/ThemeMetric.h" +#include + struct WheelItemBaseData; /** @brief The different types of Wheel Items. */ enum WheelItemDataType @@ -58,20 +59,20 @@ class WheelItemBase : public ActorFrame const std::string GetText() { - ASSERT(m_pData != NULL); + assert(m_pData != nullptr); return m_pData->m_sText; } const RageColor GetColor() { - ASSERT(m_pData != NULL); + assert(m_pData != nullptr); return m_pData->m_color; } WheelItemDataType GetType() { - ASSERT(m_pData != NULL); + assert(m_pData != nullptr); return m_pData->m_Type; } - bool IsLoaded() { return m_pData != NULL; } + bool IsLoaded() { return m_pData != nullptr; } // Lua void PushSelf(lua_State* L) override; diff --git a/src/Etterna/Globals/global.h b/src/Etterna/Globals/global.h index 329121bc78..3f0587c7ef 100644 --- a/src/Etterna/Globals/global.h +++ b/src/Etterna/Globals/global.h @@ -9,6 +9,8 @@ #pragma warning(disable : 4251) #pragma warning(disable : 4275) #pragma warning(disable : 4996) +#pragma warning(disable : 4267) +#pragma warning(disable : 4244) /** @brief This macro is for INT8_MIN, etc. */ #define __STDC_LIMIT_MACROS /** @brief This macro is for INT64_C, etc. */ diff --git a/src/Etterna/Models/Misc/AutoKeysounds.h b/src/Etterna/Models/Misc/AutoKeysounds.h index 6585af8b3a..5d4f9cd0a3 100644 --- a/src/Etterna/Models/Misc/AutoKeysounds.h +++ b/src/Etterna/Models/Misc/AutoKeysounds.h @@ -18,11 +18,11 @@ class AutoKeysounds * any. */ void FinishLoading(); RageSound* GetSound() { return &m_sSound; } - RageSoundReader* GetSharedSound() { return m_pSharedSound; } - RageSoundReader* GetPlayerSound(PlayerNumber pn) + RageSoundReader* GetSharedSound() const { return m_pSharedSound; } + RageSoundReader* GetPlayerSound(PlayerNumber pn) const { if (pn == PLAYER_INVALID) - return NULL; + return nullptr; return m_pPlayerSounds; } diff --git a/src/Etterna/Models/Misc/BackgroundUtil.cpp b/src/Etterna/Models/Misc/BackgroundUtil.cpp index 13feea43bb..d113c8a7d5 100644 --- a/src/Etterna/Models/Misc/BackgroundUtil.cpp +++ b/src/Etterna/Models/Misc/BackgroundUtil.cpp @@ -271,7 +271,7 @@ GetFilterToFileNames(const std::string sBaseDir, } XNode* pSection = ini.GetChild(sSection); - if (pSection == NULL) { + if (pSection == nullptr) { ASSERT_M(0, ssprintf("File '%s' refers to a section '%s' that is missing.", sPath.c_str(), diff --git a/src/Etterna/Models/Misc/CryptHelpers.cpp b/src/Etterna/Models/Misc/CryptHelpers.cpp index 4c7aaab1d4..fbce6a36e1 100644 --- a/src/Etterna/Models/Misc/CryptHelpers.cpp +++ b/src/Etterna/Models/Misc/CryptHelpers.cpp @@ -6,7 +6,7 @@ PRNGWrapper::PRNGWrapper(const struct ltc_prng_descriptor* pPRNGDescriptor) m_iPRNG = register_prng(pPRNGDescriptor); ASSERT(m_iPRNG >= 0); - int iRet = rng_make_prng(128, m_iPRNG, &m_PRNG, NULL); + int iRet = rng_make_prng(128, m_iPRNG, &m_PRNG, nullptr); ASSERT_M(iRet == CRYPT_OK, error_to_string(iRet)); } @@ -31,7 +31,7 @@ void PRNGWrapper::AddRandomEntropy() { unsigned char buf[256]; - int iRet = rng_get_bytes(buf, sizeof(buf), NULL); + int iRet = rng_get_bytes(buf, sizeof(buf), nullptr); ASSERT(iRet == sizeof(buf)); AddEntropy(buf, sizeof(buf)); diff --git a/src/Etterna/Models/Misc/DateTime.cpp b/src/Etterna/Models/Misc/DateTime.cpp index 7845cb5ef7..0e7d841c8a 100644 --- a/src/Etterna/Models/Misc/DateTime.cpp +++ b/src/Etterna/Models/Misc/DateTime.cpp @@ -69,7 +69,7 @@ DateTime::operator>(const DateTime& other) const DateTime DateTime::GetNowDateTime() { - time_t now = time(NULL); + time_t now = time(nullptr); tm tNow; localtime_r(&now, &tNow); DateTime dtNow; diff --git a/src/Etterna/Models/Misc/Difficulty.h b/src/Etterna/Models/Misc/Difficulty.h index 55ebdf6f66..9330bff87e 100644 --- a/src/Etterna/Models/Misc/Difficulty.h +++ b/src/Etterna/Models/Misc/Difficulty.h @@ -3,6 +3,7 @@ #include "EnumHelper.h" #include "GameConstantsAndTypes.h" + class Song; class Steps; @@ -39,7 +40,7 @@ StepsToCustomDifficulty(const Steps* pSteps); struct Chart { - string key; + std::string key; std::string lastsong; std::string lastpack; Difficulty lastdiff = Difficulty_Invalid; @@ -50,7 +51,7 @@ struct Chart bool IsLoaded() { return loaded; } bool loaded = false; - void FromKey(const string& ck); + void FromKey(const std::string& ck); XNode* CreateNode(bool includerate) const; void LoadFromNode(const XNode* node); void PushSelf(lua_State* L); @@ -59,19 +60,18 @@ struct Chart struct Playlist { std::string name; - vector chartlist; + std::vector chartlist; void Add(Chart ch) { chartlist.emplace_back(ch); } - void AddChart(const string& ck); + void AddChart(const std::string& ck); void SwapPosition(); - void Create(); - vector> courseruns; + std::vector> courseruns; XNode* CreateNode() const; void LoadFromNode(const XNode* node); int GetNumCharts() { return chartlist.size(); } - vector GetKeys(); - string GetName() { return name; } + std::vector GetKeys(); + std::string GetName() { return name; } float GetAverageRating(); void DeleteChart(int i); @@ -80,16 +80,16 @@ struct Playlist struct CalcTest { - string ck; + std::string ck; float ev; float rate; - map version_history; + std::map version_history; }; struct CalcTestList { Skillset skillset; - map filemapping; + std::map filemapping; XNode* CreateNode() const; }; diff --git a/src/Etterna/Models/Misc/DisplaySpec.cpp b/src/Etterna/Models/Misc/DisplaySpec.cpp index bf2d2d8fbc..1ee47a8fad 100644 --- a/src/Etterna/Models/Misc/DisplaySpec.cpp +++ b/src/Etterna/Models/Misc/DisplaySpec.cpp @@ -36,7 +36,7 @@ class LunaDisplaySpec : public Luna } static int GetCurrentMode(T* p, lua_State* L) { - if (p->currentMode() != NULL) { + if (p->currentMode() != nullptr) { DisplayMode* m = const_cast(p->currentMode()); m->PushSelf(L); } else { @@ -124,13 +124,13 @@ const luaL_Reg DisplaySpecs_meta[] = { { "__gc", DisplaySpecs_gc }, { "__index", DisplaySpecs_get }, { "__len", DisplaySpecs_len }, { "__tostring", DisplaySpecs_tostring }, - { NULL, NULL } }; + { nullptr, NULL } }; void register_DisplaySpecs(lua_State* L) { luaL_newmetatable(L, DISPLAYSPECS); - luaL_openlib(L, 0, DisplaySpecs_meta, 0); + luaL_openlib(L, nullptr, DisplaySpecs_meta, 0); lua_pop(L, 1); } } diff --git a/src/Etterna/Models/Misc/EnumHelper.cpp b/src/Etterna/Models/Misc/EnumHelper.cpp index 6292f350ca..07f77d3d68 100644 --- a/src/Etterna/Models/Misc/EnumHelper.cpp +++ b/src/Etterna/Models/Misc/EnumHelper.cpp @@ -152,7 +152,7 @@ Reverse(lua_State* L) static const luaL_Reg EnumLib[] = { { "GetName", GetName }, { "Reverse", Reverse }, - { NULL, NULL } }; + { nullptr, NULL } }; static void PushEnumMethodTable(lua_State* L) diff --git a/src/Etterna/Models/Misc/EnumHelper.h b/src/Etterna/Models/Misc/EnumHelper.h index 5e7316b982..ad2efde0e4 100644 --- a/src/Etterna/Models/Misc/EnumHelper.h +++ b/src/Etterna/Models/Misc/EnumHelper.h @@ -43,13 +43,13 @@ Check(lua_State* L, bool bAllowInvalid = false, bool bAllowAnything = false) { - return (T)CheckEnum(L, - EnumTraits::StringToEnum, - iPos, - EnumTraits::Invalid, - EnumTraits::szName, - bAllowInvalid, - bAllowAnything); + return static_cast(CheckEnum(L, + EnumTraits::StringToEnum, + iPos, + EnumTraits::Invalid, + EnumTraits::szName, + bAllowInvalid, + bAllowAnything)); } template static void @@ -109,7 +109,7 @@ EnumToString(int iVal, \ { \ static unique_ptr g_##X##Name[NUM_##X]; \ - if (g_##X##Name[0].get() == NULL) { \ + if (g_##X##Name[0].get() == nullptr) { \ for (unsigned i = 0; i < NUM_##X; ++i) { \ unique_ptr ap( \ new LocalizedString(#X, X##ToString((X)i))); \ diff --git a/src/Etterna/Models/Misc/GameConstantsAndTypes.cpp b/src/Etterna/Models/Misc/GameConstantsAndTypes.cpp index 44d2ac8114..8b7631e33d 100644 --- a/src/Etterna/Models/Misc/GameConstantsAndTypes.cpp +++ b/src/Etterna/Models/Misc/GameConstantsAndTypes.cpp @@ -1,26 +1,15 @@ #include "Etterna/Globals/global.h" #include "EnumHelper.h" -#include "Foreach.h" #include "GameConstantsAndTypes.h" #include "Etterna/Singletons/GameManager.h" #include "LocalizedString.h" #include "Etterna/Singletons/LuaManager.h" -#include "PlayerNumber.h" #include "RageUtil/Utils/RageUtil.h" #include "ThemeMetric.h" std::string StepsTypeToString(StepsType st); -// This was formerly used to fill in RANKING_TO_FILL_IN_MARKER when it was a -// vector of RStrings. -poco -static vector -GenerateRankingToFillInMarker() -{ - vector vRankings; - vRankings.push_back(ssprintf("#P%d#", PLAYER_1 + 1)); - return vRankings; -} extern const std::string RANKING_TO_FILL_IN_MARKER("#P1#"); extern const std::string GROUP_ALL = "---Group All---"; @@ -42,8 +31,8 @@ StepsTypeToString(StepsType st) /* foo-bar -> Foo_Bar */ s_replace(s, "-", "_"); - bool bCapitalizeNextLetter = true; - for (int i = 0; i < static_cast(s.length()); i++) { + auto bCapitalizeNextLetter = true; + for (auto i = 0; i < static_cast(s.length()); i++) { if (bCapitalizeNextLetter) { s[i] = toupper(s[i]); bCapitalizeNextLetter = false; @@ -142,8 +131,7 @@ LuaXType(TapNoteScore); TapNoteScore StringToTapNoteScore(const std::string& s) { - std::map::iterator tns = - tns_converter.conversion_map.find(s); + auto tns = tns_converter.conversion_map.find(s); if (tns != tns_converter.conversion_map.end()) { return tns->second; } @@ -178,17 +166,17 @@ StringToHoldNoteScore(const std::string& s) // for backward compatibility if (s == "NG") return HNS_LetGo; - else if (s == "OK") + if (s == "OK") return HNS_Held; // new style - else if (s == "None") + if (s == "None") return HNS_None; - else if (s == "LetGo") + if (s == "LetGo") return HNS_LetGo; - else if (s == "Held") + if (s == "Held") return HNS_Held; - else if (s == "MissedHold") + if (s == "MissedHold") return HNS_Missed; return HoldNoteScore_Invalid; @@ -206,19 +194,19 @@ StringToSkillset(const std::string& s) { if (s == "Overall") return Skill_Overall; - else if (s == "Stream") + if (s == "Stream") return Skill_Stream; - else if (s == "Jumpstream") + if (s == "Jumpstream") return Skill_Jumpstream; - else if (s == "Handstream") + if (s == "Handstream") return Skill_Jumpstream; - else if (s == "Stamina") + if (s == "Stamina") return Skill_Stamina; - else if (s == "JackSpeed") + if (s == "JackSpeed") return Skill_JackSpeed; - else if (s == "Chordjack") + if (s == "Chordjack") return Skill_Chordjack; - else if (s == "Technical") + if (s == "Technical") return Skill_Technical; return Skill_Overall; @@ -358,16 +346,14 @@ DisplayBpms::Add(float f) float DisplayBpms::GetMin() const { - float fMin = FLT_MAX; - FOREACH_CONST(float, vfBpms, f) - { - if (*f != -1) - fMin = min(fMin, *f); + auto fMin = FLT_MAX; + for (const auto& f : vfBpms) { + if (f != -1.F) + fMin = min(fMin, f); } if (fMin == FLT_MAX) return 0; - else - return fMin; + return fMin; } float @@ -380,10 +366,9 @@ float DisplayBpms::GetMaxWithin(float highest) const { float fMax = 0; - FOREACH_CONST(float, vfBpms, f) - { - if (*f != -1) - fMax = clamp(max(fMax, *f), 0, highest); + for (const auto& f : vfBpms) { + if (f != -1.F) + fMax = clamp(max(fMax, f), 0, highest); } return fMax; } @@ -397,9 +382,8 @@ DisplayBpms::BpmIsConstant() const bool DisplayBpms::IsSecret() const { - FOREACH_CONST(float, vfBpms, f) - { - if (*f == -1) + for (const auto& f : vfBpms) { + if (f == -1.F) return true; } return false; diff --git a/src/Etterna/Models/Misc/GameConstantsAndTypes.h b/src/Etterna/Models/Misc/GameConstantsAndTypes.h index 9b5294df43..fd6b1489be 100644 --- a/src/Etterna/Models/Misc/GameConstantsAndTypes.h +++ b/src/Etterna/Models/Misc/GameConstantsAndTypes.h @@ -31,12 +31,9 @@ enum GameplayMode const std::string& SkillsetToString(Skillset ss); -const std::string& -CalcPatternModToString(CalcPatternMod); -const std::string& -CalcDiffValueToString(CalcDiffValue); -const std::string& -CalcDebugMiscToString(CalcDebugMisc); +const std::string& CalcPatternModToString(CalcPatternMod); +const std::string& CalcDiffValueToString(CalcDiffValue); +const std::string& CalcDebugMiscToString(CalcDebugMisc); enum NSScoreBoardColumn { @@ -165,7 +162,7 @@ LuaDeclareType(PlayMode); enum SortOrder { // song sorts - SORT_PREFERRED, /**< Sort by the user's preferred settings. */ + SORT_PREFERRED, /**< Sort by the user's preferred settings. */ SORT_GROUP, /**< Sort by the groups the Songs are in. */ SORT_TITLE, /**< Sort by the Song's title. */ SORT_BPM, /**< Sort by the Song's BPM. */ @@ -268,9 +265,9 @@ LuaDeclareType(TapNoteScore); /** @brief The list of hold note scores available during play. */ enum HoldNoteScore { - HNS_None, /**< The HoldNote was not scored yet. */ - HNS_LetGo, /**< The HoldNote has passed, but the player missed it. */ - HNS_Held, /**< The HoldNote has passed, and was successfully held all the + HNS_None, /**< The HoldNote was not scored yet. */ + HNS_LetGo, /**< The HoldNote has passed, but the player missed it. */ + HNS_Held, /**< The HoldNote has passed, and was successfully held all the way. */ HNS_Missed, /**< The HoldNote has passed, and was never initialized. */ NUM_HoldNoteScore, /**< The number of hold note scores. */ @@ -397,9 +394,9 @@ LuaDeclareType(PlayerController); enum HealthState { HealthState_Hot, /**< The health bar is very full. */ - HealthState_Alive, /**< The health bar is at a decent size. */ + HealthState_Alive, /**< The health bar is at a decent size. */ HealthState_Danger, /**< The health bar is about to run out. */ - HealthState_Dead, /**< The health bar is drained completely. */ + HealthState_Dead, /**< The health bar is drained completely. */ NUM_HealthState, HealthState_Invalid }; @@ -443,13 +440,13 @@ struct DisplayBpms /** * @brief The list of the BPMs for the song. */ - vector vfBpms; + std::vector vfBpms; }; /** @brief The various style types available. */ enum StyleType { - StyleType_OnePlayerOneSide, /**< Single style */ + StyleType_OnePlayerOneSide, /**< Single style */ StyleType_OnePlayerTwoSides, /**< Double style */ NUM_StyleType, StyleType_Invalid @@ -498,21 +495,21 @@ LuaDeclareType(SampleMusicPreviewMode); */ enum Stage { - Stage_1st, /**< The first stage. */ - Stage_2nd, /**< The second stage. */ - Stage_3rd, /**< The third stage. */ - Stage_4th, /**< The fourth stage. */ - Stage_5th, /**< The fifth stage. */ - Stage_6th, /**< The sixth stage. */ - Stage_Next, /**< Somewhere between the sixth and final stage. + Stage_1st, /**< The first stage. */ + Stage_2nd, /**< The second stage. */ + Stage_3rd, /**< The third stage. */ + Stage_4th, /**< The fourth stage. */ + Stage_5th, /**< The fifth stage. */ + Stage_6th, /**< The sixth stage. */ + Stage_Next, /**< Somewhere between the sixth and final stage. * This won't normally happen because 7 stages is the max in the * UI. */ Stage_Final, /**< The last stage. */ Stage_Extra1, /**< The first bonus stage, AKA the extra stage. */ Stage_Extra2, /**< The last bonus stage, AKA the encore extra stage. */ Stage_Event, /**< Playing in event mode. */ - Stage_Demo, /**< Playing the demonstration. */ - NUM_Stage, /**< The number of stage types. */ + Stage_Demo, /**< Playing the demonstration. */ + NUM_Stage, /**< The number of stage types. */ Stage_Invalid, }; const std::string& diff --git a/src/Etterna/Models/Misc/HighScore.cpp b/src/Etterna/Models/Misc/HighScore.cpp index cd4757c6ec..13917db72b 100644 --- a/src/Etterna/Models/Misc/HighScore.cpp +++ b/src/Etterna/Models/Misc/HighScore.cpp @@ -1,6 +1,5 @@ #include "Etterna/Globals/global.h" #include "Etterna/Singletons/CryptManager.h" -#include "Foreach.h" #include "GameConstantsAndTypes.h" #include "HighScore.h" #include "Etterna/Globals/picosha2.h" @@ -9,15 +8,16 @@ #include "RageUtil/Misc/RageLog.h" #include "Etterna/FileTypes/XmlFile.h" #include "NoteTypes.h" -#include -#include -#include #include "Etterna/Singletons/GameState.h" #include "Etterna/Models/NoteData/NoteData.h" #include "Etterna/Models/Misc/TimingData.h" #include "Etterna/Models/StepsAndStyles/Steps.h" #include "RageUtil/File/RageFileManager.h" +#include +#include +#include + const string BASIC_REPLAY_DIR = "Save/Replays/"; // contains only tap offset data for rescoring/plots -mina const string FULL_REPLAY_DIR = @@ -236,7 +236,7 @@ HighScoreImpl::HighScoreImpl() XNode* HighScoreImpl::CreateEttNode() const { - XNode* pNode = new XNode("Score"); + auto pNode = new XNode("Score"); if (ScoreKey == "") pNode->AppendAttr("Key", @@ -263,19 +263,19 @@ HighScoreImpl::CreateEttNode() const pNode->AppendChild("DateTime", dateTime.GetString()); pNode->AppendChild("TopScore", TopScore); if (!uploaded.empty()) { - XNode* pServerNode = pNode->AppendChild("Servs"); + auto pServerNode = pNode->AppendChild("Servs"); for (auto server : uploaded) pServerNode->AppendChild("server", server); } - XNode* pTapNoteScores = pNode->AppendChild("TapNoteScores"); + auto pTapNoteScores = pNode->AppendChild("TapNoteScores"); FOREACH_ENUM(TapNoteScore, tns) if (tns != TNS_None && tns != TNS_CheckpointMiss && tns != TNS_CheckpointHit) pTapNoteScores->AppendChild(TapNoteScoreToString(tns), iTapNoteScores[tns]); - XNode* pHoldNoteScores = pNode->AppendChild("HoldNoteScores"); + auto pHoldNoteScores = pNode->AppendChild("HoldNoteScores"); FOREACH_ENUM(HoldNoteScore, hns) if (hns != HNS_None) // HACK: don't save meaningless "none" count pHoldNoteScores->AppendChild(HoldNoteScoreToString(hns), @@ -284,13 +284,13 @@ HighScoreImpl::CreateEttNode() const // dont bother writing skillset ssrs for non-applicable scores if (fWifeScore > 0.f && grade != Grade_Failed && fSkillsetSSRs[Skill_Overall] > 0.f) { - XNode* pSkillsetSSRs = pNode->AppendChild("SkillsetSSRs"); + auto pSkillsetSSRs = pNode->AppendChild("SkillsetSSRs"); FOREACH_ENUM(Skillset, ss) pSkillsetSSRs->AppendChild( SkillsetToString(ss), FloatToString(fSkillsetSSRs[ss]).substr(0, 5)); } - XNode* pValidationKeys = pNode->AppendChild("ValidationKeys"); + auto pValidationKeys = pNode->AppendChild("ValidationKeys"); pValidationKeys->AppendChild(ValidationKeyToString(ValidationKey_Brittle), ValidationKeys[ValidationKey_Brittle]); pValidationKeys->AppendChild(ValidationKeyToString(ValidationKey_Weak), @@ -315,7 +315,7 @@ HighScoreImpl::LoadFromEttNode(const XNode* pNode) pNode->GetChildValue("JudgeScale", fJudgeScale); pNode->GetChildValue("NoChordCohesion", bNoChordCohesion); pNode->GetChildValue("EtternaValid", bEtternaValid); - const XNode* pUploadedServers = pNode->GetChild("Servs"); + auto pUploadedServers = pNode->GetChild("Servs"); if (pUploadedServers != nullptr) { FOREACH_CONST_Child(pUploadedServers, p) { @@ -335,27 +335,27 @@ HighScoreImpl::LoadFromEttNode(const XNode* pNode) if (pNode->GetChildValue("MachineGuid", s)) sMachineGuid = s; - const XNode* pTapNoteScores = pNode->GetChild("TapNoteScores"); + auto pTapNoteScores = pNode->GetChild("TapNoteScores"); if (pTapNoteScores) FOREACH_ENUM(TapNoteScore, tns) pTapNoteScores->GetChildValue(TapNoteScoreToString(tns), iTapNoteScores[tns]); - const XNode* pHoldNoteScores = pNode->GetChild("HoldNoteScores"); + auto pHoldNoteScores = pNode->GetChild("HoldNoteScores"); if (pHoldNoteScores) FOREACH_ENUM(HoldNoteScore, hns) pHoldNoteScores->GetChildValue(HoldNoteScoreToString(hns), iHoldNoteScores[hns]); if (fWifeScore > 0.f) { - const XNode* pSkillsetSSRs = pNode->GetChild("SkillsetSSRs"); + auto pSkillsetSSRs = pNode->GetChild("SkillsetSSRs"); if (pSkillsetSSRs) FOREACH_ENUM(Skillset, ss) pSkillsetSSRs->GetChildValue(SkillsetToString(ss), fSkillsetSSRs[ss]); } if (fWifeScore > 0.f) { - const XNode* pValidationKeys = pNode->GetChild("ValidationKeys"); + auto pValidationKeys = pNode->GetChild("ValidationKeys"); if (pValidationKeys != nullptr) { if (pValidationKeys->GetChildValue( ValidationKeyToString(ValidationKey_Brittle), s)) @@ -386,7 +386,7 @@ HighScoreImpl::WriteReplayData() // These two lines should probably be somewhere else if (!FILEMAN->IsADirectory(FULL_REPLAY_DIR)) FILEMAN->CreateDir(FULL_REPLAY_DIR); - string path = FULL_REPLAY_DIR + ScoreKey; + auto path = FULL_REPLAY_DIR + ScoreKey; ofstream fileStream(path, ios::binary); // check file @@ -428,7 +428,7 @@ HighScore::WriteInputData(const vector& oop) string append; string profiledir; - string path = FULL_REPLAY_DIR + m_Impl->ScoreKey; + auto path = FULL_REPLAY_DIR + m_Impl->ScoreKey; ofstream fileStream(path, ios::binary); // check file @@ -469,7 +469,7 @@ HighScore::LoadReplayDataBasic(string dir) string profiledir; vector vNoteRowVector; vector vOffsetVector; - string path = dir + m_Impl->ScoreKey; + auto path = dir + m_Impl->ScoreKey; std::ifstream fileStream(path, ios::binary); string line; @@ -550,7 +550,7 @@ HighScore::LoadReplayDataFull(string dir) vector vTrackVector; vector vTapNoteTypeVector; vector vHoldReplayDataVector; - string path = dir + m_Impl->ScoreKey; + auto path = dir + m_Impl->ScoreKey; std::ifstream fileStream(path, ios::binary); string line; @@ -598,7 +598,7 @@ HighScore::LoadReplayDataFull(string dir) continue; } - bool a = buffer == "1"; + auto a = buffer == "1"; a = buffer == "2" || a; a = buffer == "3" || a; a = buffer == "4" || a; @@ -665,8 +665,8 @@ HighScore::LoadReplayDataFull(string dir) bool HighScore::HasReplayData() { - std::string fullpath = FULL_REPLAY_DIR + m_Impl->ScoreKey; - std::string basicpath = BASIC_REPLAY_DIR + m_Impl->ScoreKey; + auto fullpath = FULL_REPLAY_DIR + m_Impl->ScoreKey; + auto basicpath = BASIC_REPLAY_DIR + m_Impl->ScoreKey; if (DoesFileExist(fullpath)) // check for full replays first then default to // basic replays -mina return true; @@ -1258,7 +1258,7 @@ HighScore::GetDisplayName() const XNode* Screenshot::CreateNode() const { - XNode* pNode = new XNode("Screenshot"); + auto pNode = new XNode("Screenshot"); // TRICKY: Don't write "name to fill in" markers. pNode->AppendChild("FileName", sFileName); @@ -1273,7 +1273,7 @@ Screenshot::LoadFromNode(const XNode* pNode) pNode->GetChildValue("FileName", sFileName); pNode->GetChildValue("MD5", sMD5); - const XNode* pHighScore = pNode->GetChild("HighScore"); + auto pHighScore = pNode->GetChild("HighScore"); } float @@ -1284,7 +1284,7 @@ HighScore::RescoreToWife2Judge(int x) const float tso[] = { 1.50f, 1.33f, 1.16f, 1.00f, 0.84f, 0.66f, 0.50f, 0.33f, 0.20f }; - float ts = tso[x - 1]; + auto ts = tso[x - 1]; float p = 0; // the typevector is only available for full replays @@ -1311,7 +1311,7 @@ HighScore::RescoreToWife2Judge(int x) p += m_Impl->iTapNoteScores[TNS_HitMine] * -8.f; // this is a bad assumption but im leaving it here - float pmax = static_cast(m_Impl->vOffsetVector.size() * 2); + auto pmax = static_cast(m_Impl->vOffsetVector.size() * 2); /* we don't want to have to access notedata when loading or rescording scores so we use the vector length of offset replay data to determine point @@ -1337,9 +1337,9 @@ HighScore::RescoreToWife3(float pmax) return false; // SSRNormPercent - float p4 = 0.f; + auto p4 = 0.f; // WifeScore for HighScore Judge - float pj = 0.f; + auto pj = 0.f; // the typevector is only available for full replays if (m_Impl->ReplayType == 2) { @@ -1361,10 +1361,10 @@ HighScore::RescoreToWife3(float pmax) } } - float holdpoints = (m_Impl->iHoldNoteScores[HNS_LetGo] + - m_Impl->iHoldNoteScores[HNS_Missed]) * - wife3_hold_drop_weight; - float minepoints = + auto holdpoints = (m_Impl->iHoldNoteScores[HNS_LetGo] + + m_Impl->iHoldNoteScores[HNS_Missed]) * + wife3_hold_drop_weight; + auto minepoints = m_Impl->iTapNoteScores[TNS_HitMine] * wife3_mine_hit_weight; p4 += holdpoints + minepoints; @@ -1383,19 +1383,18 @@ HighScore::RescoreToDPJudge(int x) { const float tso[] = { 1.50f, 1.33f, 1.16f, 1.00f, 0.84f, 0.66f, 0.50f, 0.33f, 0.20f }; - float ts = tso[x - 1]; + auto ts = tso[x - 1]; vector vRescoreJudgeVector; - int marv = 0; - int perf = 0; - int great = 0; - int good = 0; - int boo = 0; - int miss = 0; - int m2 = 0; - FOREACH_CONST(float, m_Impl->vOffsetVector, f) - { + auto marv = 0; + auto perf = 0; + auto great = 0; + auto good = 0; + auto boo = 0; + auto miss = 0; + auto m2 = 0; + for (auto& f : m_Impl->vOffsetVector) { m2 += 2; - float x = abs(*f * 1000.f); + auto x = abs(f * 1000.f); if (x <= ts * 22.5f) ++marv; else if (x <= ts * 45.f) @@ -1420,7 +1419,7 @@ HighScore::RescoreToDPJudge(int x) vRescoreJudgeVector.push_back(miss); SetRescoreJudgeVector(vRescoreJudgeVector); - int p = 0; + auto p = 0; p += (marv + perf) * 2; p += great * 1; p += boo * -4; @@ -1431,7 +1430,7 @@ HighScore::RescoreToDPJudge(int x) m_Impl->iHoldNoteScores[HNS_Missed]) * -6; - float m = static_cast(m_Impl->vOffsetVector.size() * 2); + auto m = static_cast(m_Impl->vOffsetVector.size() * 2); m += (m_Impl->radarValues[RadarCategory_Holds] + m_Impl->radarValues[RadarCategory_Rolls]) * 6; @@ -1473,9 +1472,9 @@ HighScore::ConvertDpToWife() if (m_Impl->grade == Grade_Failed) return 0.f; - float ts = 1.f; - float estpoints = 0.f; - float maxpoints = 0.f; + auto ts = 1.f; + auto estpoints = 0.f; + auto maxpoints = 0.f; estpoints += m_Impl->iTapNoteScores[TNS_W1] * wife3(.01125f, ts); estpoints += m_Impl->iTapNoteScores[TNS_W2] * wife3(.03375f, ts); estpoints += m_Impl->iTapNoteScores[TNS_W3] * wife3(.0675f, ts); @@ -1546,7 +1545,7 @@ class LunaHighScore : public Luna } static int IsFillInMarker(T* p, lua_State* L) { - bool bIsFillInMarker = false; + auto bIsFillInMarker = false; bIsFillInMarker |= p->GetName() == RANKING_TO_FILL_IN_MARKER; lua_pushboolean(L, static_cast(bIsFillInMarker)); return 1; @@ -1575,7 +1574,7 @@ class LunaHighScore : public Luna static int RescoreJudges(T* p, lua_State* L) { lua_newtable(L); - for (int i = 0; i < 6; ++i) { + for (auto i = 0; i < 6; ++i) { lua_pushnumber(L, p->GetRescoreJudgeVector(IArg(1))[i]); lua_rawseti(L, -2, i + 1); } @@ -1584,7 +1583,7 @@ class LunaHighScore : public Luna } static int GetRadarValues(T* p, lua_State* L) { - RadarValues& rv = const_cast(p->GetRadarValues()); + auto& rv = const_cast(p->GetRadarValues()); rv.PushSelf(L); return 1; } @@ -1606,7 +1605,7 @@ class LunaHighScore : public Luna static int GetOffsetVector(T* p, lua_State* L) { auto v = p->GetOffsetVector(); - bool loaded = v.size() > 0; + auto loaded = v.size() > 0; if (loaded || p->LoadReplayData()) { if (!loaded) v = p->GetOffsetVector(); @@ -1621,7 +1620,7 @@ class LunaHighScore : public Luna static int GetNoteRowVector(T* p, lua_State* L) { auto* v = &(p->GetNoteRowVector()); - bool loaded = v->size() > 0; + auto loaded = v->size() > 0; auto timestamps = p->GetCopyOfSetOnlineReplayTimestampVector(); @@ -1649,7 +1648,7 @@ class LunaHighScore : public Luna auto noterowfrombeat = BeatToNoteRow(timestamptobeat); noterows.emplace_back(noterowfrombeat); } - int noterowoffsetter = nerv[0] - noterows[0]; + auto noterowoffsetter = nerv[0] - noterows[0]; for (auto& noterowwithoffset : noterows) noterowwithoffset += noterowoffsetter; GAMESTATE->SetProcessedTimingData(nullptr); @@ -1668,7 +1667,7 @@ class LunaHighScore : public Luna static int GetTrackVector(T* p, lua_State* L) { auto* v = &(p->GetTrackVector()); - bool loaded = v->size() > 0; + auto loaded = v->size() > 0; if (loaded || p->LoadReplayData()) { if (!loaded) v = &(p->GetTrackVector()); @@ -1681,7 +1680,7 @@ class LunaHighScore : public Luna static int GetTapNoteTypeVector(T* p, lua_State* L) { auto* v = &(p->GetTapNoteTypeVector()); - bool loaded = v->size() > 0; + auto loaded = v->size() > 0; if (loaded || p->LoadReplayData()) { if (!loaded) v = &(p->GetTapNoteTypeVector()); @@ -1692,14 +1691,14 @@ class LunaHighScore : public Luna } static int GetJudgmentString(T* p, lua_State* L) { - std::string doot = ssprintf("%d I %d I %d I %d I %d I %d x%d", - p->GetTapNoteScore(TNS_W1), - p->GetTapNoteScore(TNS_W2), - p->GetTapNoteScore(TNS_W3), - p->GetTapNoteScore(TNS_W4), - p->GetTapNoteScore(TNS_W5), - p->GetTapNoteScore(TNS_Miss), - p->GetMaxCombo()); + auto doot = ssprintf("%d I %d I %d I %d I %d I %d x%d", + p->GetTapNoteScore(TNS_W1), + p->GetTapNoteScore(TNS_W2), + p->GetTapNoteScore(TNS_W3), + p->GetTapNoteScore(TNS_W4), + p->GetTapNoteScore(TNS_W5), + p->GetTapNoteScore(TNS_Miss), + p->GetMaxCombo()); lua_pushstring(L, doot.c_str()); return 1; } @@ -1721,7 +1720,7 @@ class LunaHighScore : public Luna } static int GetWifeVers(T* p, lua_State* L) { - int vers = p->GetWifeVersion(); + auto vers = p->GetWifeVersion(); if (vers != 3) vers = 2; lua_pushnumber(L, vers); diff --git a/src/Etterna/Models/Misc/HighScore.h b/src/Etterna/Models/Misc/HighScore.h index a57c9dfe90..0e745afdca 100644 --- a/src/Etterna/Models/Misc/HighScore.h +++ b/src/Etterna/Models/Misc/HighScore.h @@ -11,8 +11,6 @@ class XNode; struct RadarValues; struct lua_State; -using std::string; - struct HighScoreImpl; /** @brief The high score that is earned by a player. * @@ -24,78 +22,81 @@ struct HighScore /** * @brief Retrieve the name of the player that set the high score. * @return the name of the player. */ - const std::string& GetName() const; - const std::string& GetChartKey() const; - int GetSSRCalcVersion() const; + [[nodiscard]] const std::string& GetName() const; + [[nodiscard]] const std::string& GetChartKey() const; + [[nodiscard]] int GetSSRCalcVersion() const; /** * @brief Retrieve the grade earned from this score. * @return the grade. */ - Grade GetGrade() const; + [[nodiscard]] Grade GetGrade() const; /** * @brief Retrieve the score earned. * @return the score. */ - unsigned int GetScore() const; + [[nodiscard]] unsigned int GetScore() const; /** * @brief Determine if any judgments were tallied during this run. * @return true if no judgments were recorded, false otherwise. */ - bool IsEmpty() const; - Grade GetWifeGrade() const; + [[nodiscard]] bool IsEmpty() const; + [[nodiscard]] Grade GetWifeGrade() const; float ConvertDpToWife(); - float GetPercentDP() const; - float GetWifeScore() const; - float GetWifePoints() const; - float GetSSRNormPercent() const; - float GetMusicRate() const; - float GetJudgeScale() const; - bool GetChordCohesion() const; - bool GetEtternaValid() const; - bool IsUploadedToServer(const std::string& s) const; - vector timeStamps; - const vector& GetOffsetVector() const; - const vector& GetNoteRowVector() const; - const vector& GetTrackVector() const; - const vector& GetTapNoteTypeVector() const; - const vector& GetHoldReplayDataVector() const; - vector GetCopyOfOffsetVector() const; - vector GetCopyOfNoteRowVector() const; - vector GetCopyOfTrackVector() const; - vector GetCopyOfTapNoteTypeVector() const; - vector GetCopyOfHoldReplayDataVector() const; - vector GetCopyOfSetOnlineReplayTimestampVector() const; - const std::string& GetScoreKey() const; - int GetTopScore() const; - int GetReplayType() const; + [[nodiscard]] float GetPercentDP() const; + [[nodiscard]] float GetWifeScore() const; + [[nodiscard]] float GetWifePoints() const; + [[nodiscard]] float GetSSRNormPercent() const; + [[nodiscard]] float GetMusicRate() const; + [[nodiscard]] float GetJudgeScale() const; + [[nodiscard]] bool GetChordCohesion() const; + [[nodiscard]] bool GetEtternaValid() const; + [[nodiscard]] bool IsUploadedToServer(const std::string& s) const; + std::vector timeStamps; + [[nodiscard]] const std::vector& GetOffsetVector() const; + [[nodiscard]] const std::vector& GetNoteRowVector() const; + [[nodiscard]] const std::vector& GetTrackVector() const; + [[nodiscard]] const std::vector& GetTapNoteTypeVector() const; + [[nodiscard]] const std::vector& GetHoldReplayDataVector() + const; + [[nodiscard]] std::vector GetCopyOfOffsetVector() const; + [[nodiscard]] std::vector GetCopyOfNoteRowVector() const; + [[nodiscard]] std::vector GetCopyOfTrackVector() const; + [[nodiscard]] std::vector GetCopyOfTapNoteTypeVector() const; + [[nodiscard]] std::vector GetCopyOfHoldReplayDataVector() + const; + [[nodiscard]] std::vector GetCopyOfSetOnlineReplayTimestampVector() + const; + [[nodiscard]] const std::string& GetScoreKey() const; + [[nodiscard]] int GetTopScore() const; + [[nodiscard]] int GetReplayType() const; /** * @brief Determine how many seconds the player had left in Survival mode. * @return the number of seconds left. */ - float GetSurviveSeconds() const; - float GetSurvivalSeconds() const; - unsigned int GetMaxCombo() const; + [[nodiscard]] float GetSurviveSeconds() const; + [[nodiscard]] float GetSurvivalSeconds() const; + [[nodiscard]] unsigned int GetMaxCombo() const; /** * @brief Get the modifiers used for this run. * @return the modifiers. */ - const std::string& GetModifiers() const; - DateTime GetDateTime() const; - const std::string& GetPlayerGuid() const; - const std::string& GetMachineGuid() const; - const std::string& GetCountryCode() const; - int GetProductID() const; - int GetTapNoteScore(TapNoteScore tns) const; - int GetHoldNoteScore(HoldNoteScore tns) const; - const RadarValues& GetRadarValues() const; - float GetLifeRemainingSeconds() const; + [[nodiscard]] const std::string& GetModifiers() const; + [[nodiscard]] DateTime GetDateTime() const; + [[nodiscard]] const std::string& GetPlayerGuid() const; + [[nodiscard]] const std::string& GetMachineGuid() const; + [[nodiscard]] const std::string& GetCountryCode() const; + [[nodiscard]] int GetProductID() const; + [[nodiscard]] int GetTapNoteScore(TapNoteScore tns) const; + [[nodiscard]] int GetHoldNoteScore(HoldNoteScore tns) const; + [[nodiscard]] const RadarValues& GetRadarValues() const; + [[nodiscard]] float GetLifeRemainingSeconds() const; /** * @brief Determine if this score was from a situation that would cause * disqualification. * @return true if the score would be disqualified, false otherwise. */ - bool GetDisqualified() const; + [[nodiscard]] bool GetDisqualified() const; /** * @brief Set the name of the Player that earned the score. * @param sName the name of the Player. */ - void SetName(const string& sName); - void SetChartKey(const string& ck); + void SetName(const std::string& sName); + void SetChartKey(const std::string& ck); void SetSSRCalcVersion(int cv); void SetGrade(Grade g); void SetScore(unsigned int iScore); @@ -109,20 +110,20 @@ struct HighScore void SetChordCohesion(bool b); void SetEtternaValid(bool b); void AddUploadedServer(string s); - void SetOffsetVector(const vector& v); - void SetNoteRowVector(const vector& v); - void SetTrackVector(const vector& v); - void SetTapNoteTypeVector(const vector& v); - void SetHoldReplayDataVector(const vector& v); - void SetOnlineReplayTimestampVector(const vector& v); - void SetScoreKey(const string& ck); - void SetRescoreJudgeVector(const vector& v); + void SetOffsetVector(const std::vector& v); + void SetNoteRowVector(const std::vector& v); + void SetTrackVector(const std::vector& v); + void SetTapNoteTypeVector(const std::vector& v); + void SetHoldReplayDataVector(const std::vector& v); + void SetOnlineReplayTimestampVector(const std::vector& v); + void SetScoreKey(const std::string& ck); + void SetRescoreJudgeVector(const std::vector& v); void SetAliveSeconds(float f); void SetMaxCombo(unsigned int i); - void SetModifiers(const string& s); + void SetModifiers(const std::string& s); void SetDateTime(DateTime d); - void SetPlayerGuid(const string& s); - void SetMachineGuid(const string& s); + void SetPlayerGuid(const std::string& s); + void SetMachineGuid(const std::string& s); void SetProductID(int i); void SetTapNoteScore(TapNoteScore tns, int i); void SetHoldNoteScore(HoldNoteScore tns, int i); @@ -131,8 +132,9 @@ struct HighScore void SetDisqualified(bool b); void SetReplayType(int i); - string* GetNameMutable(); - const string* GetNameMutable() const + std::string* GetNameMutable(); + + [[nodiscard]] const std::string* GetNameMutable() const { return const_cast( const_cast(this)->GetNameMutable()); @@ -147,13 +149,13 @@ struct HighScore bool operator==(HighScore const& other) const; bool operator!=(HighScore const& other) const; - XNode* CreateNode() const; - XNode* CreateEttNode() const; + [[nodiscard]] XNode* CreateNode() const; + [[nodiscard]] XNode* CreateEttNode() const; void LoadFromNode(const XNode* pNode); void LoadFromEttNode(const XNode* pNode); bool WriteReplayData(); - bool WriteInputData(const vector& oop); + bool WriteInputData(const std::vector& oop); bool LoadReplayData(); bool LoadReplayDataBasic(string dir); bool LoadReplayDataFull(string dir); @@ -161,26 +163,26 @@ struct HighScore void UnloadReplayData(); void ResetSkillsets(); - const std::string& GetDisplayName() const; + [[nodiscard]] const std::string& GetDisplayName() const; // Mina stuff - Mina float RescoreToWife2Judge(int x); // update wifescore (judge the score was achieved on) and ssrnorm bool RescoreToWife3(float pmax); float RescoreToDPJudge(int x); - float GetSkillsetSSR(Skillset ss) const; - int GetWifeVersion() const; + [[nodiscard]] float GetSkillsetSSR(Skillset ss) const; + [[nodiscard]] int GetWifeVersion() const; void SetSkillsetSSR(Skillset ss, float ssr); - void SetValidationKey(ValidationKey vk, string k); + void SetValidationKey(ValidationKey vk, std::string k); void SetTopScore(int i); - string GenerateValidationKeys(); - const std::string& GetValidationKey(ValidationKey vk) const; - vector GetRescoreJudgeVector(int x); + std::string GenerateValidationKeys(); + [[nodiscard]] const std::string& GetValidationKey(ValidationKey vk) const; + std::vector GetRescoreJudgeVector(int x); // laazy - string scoreid; + std::string scoreid; int userid = -1; - string avatar; - string countryCode; + std::string avatar; + std::string countryCode; bool forceuploadedthissession = false; int norms = 0; int musics = 0; @@ -202,7 +204,7 @@ struct Screenshot /** @brief The actual high score in question. */ HighScore highScore; - XNode* CreateNode() const; + [[nodiscard]] XNode* CreateNode() const; void LoadFromNode(const XNode* pNode); bool operator<(Screenshot const& rhs) const { diff --git a/src/Etterna/Models/Misc/InputEventPlus.h b/src/Etterna/Models/Misc/InputEventPlus.h index 11f5315bc5..e3c0b8fd4e 100644 --- a/src/Etterna/Models/Misc/InputEventPlus.h +++ b/src/Etterna/Models/Misc/InputEventPlus.h @@ -1,4 +1,4 @@ -#ifndef INPUT_EVENT_PLUS_H +#ifndef INPUT_EVENT_PLUS_H #define INPUT_EVENT_PLUS_H #include "GameInput.h" @@ -9,12 +9,7 @@ class InputEventPlus { public: InputEventPlus() - : DeviceI() - , GameI() - , - - pn(PLAYER_INVALID) - , InputList() + : pn(PLAYER_INVALID) { } DeviceInput DeviceI; diff --git a/src/Etterna/Models/Misc/LocalizedString.cpp b/src/Etterna/Models/Misc/LocalizedString.cpp index e0b9119a24..871f13957d 100644 --- a/src/Etterna/Models/Misc/LocalizedString.cpp +++ b/src/Etterna/Models/Misc/LocalizedString.cpp @@ -46,7 +46,7 @@ LocalizedString::LocalizedString(const std::string& sGroup, m_sGroup = sGroup; m_sName = sName; - m_pImpl = NULL; + m_pImpl = nullptr; CreateImpl(); } @@ -57,7 +57,7 @@ LocalizedString::LocalizedString(LocalizedString const& other) m_sGroup = other.m_sGroup; m_sName = other.m_sName; - m_pImpl = NULL; + m_pImpl = nullptr; CreateImpl(); } diff --git a/src/Etterna/Models/Misc/ModsGroup.h b/src/Etterna/Models/Misc/ModsGroup.h index b24a7593e1..65bb6bdfc9 100644 --- a/src/Etterna/Models/Misc/ModsGroup.h +++ b/src/Etterna/Models/Misc/ModsGroup.h @@ -5,6 +5,8 @@ #include "RageUtil/Misc/RageTimer.h" #include "Etterna/Models/Songs/SongOptions.h" +#include + enum ModsLevel { ModsLevel_Preferred, // user-chosen player options. Does not include any @@ -54,7 +56,7 @@ class ModsGroup } template - inline void Assign(ModsLevel level, U T::*member, const U& val) + void Assign(ModsLevel level, U T::*member, const U& val) { if (level != ModsLevel_Song) m_[ModsLevel_Current].*member = val; @@ -63,12 +65,12 @@ class ModsGroup } template - inline void Assign_n(ModsLevel level, - U (T::*member)[n], - size_t index, - const U& val) + void Assign_n(ModsLevel level, + U (T::*member)[n], + size_t index, + const U& val) { - DEBUG_ASSERT(index < n); + assert(index < n); if (level != ModsLevel_Song) (m_[ModsLevel_Current].*member)[index] = val; for (; level < ModsLevel_Current; enum_add(level, 1)) diff --git a/src/Etterna/Models/Misc/NoteTypes.h b/src/Etterna/Models/Misc/NoteTypes.h index 55c4cca53a..3bad1a4dbe 100644 --- a/src/Etterna/Models/Misc/NoteTypes.h +++ b/src/Etterna/Models/Misc/NoteTypes.h @@ -31,7 +31,7 @@ struct TapNoteResult bool bHidden{ false }; // XML - XNode* CreateNode() const; + [[nodiscard]] XNode* CreateNode() const; void LoadFromNode(const XNode* pNode); // Lua @@ -41,7 +41,7 @@ struct TapNoteResult struct HoldNoteResult { HoldNoteResult() = default; - float GetLastHeldBeat() const; + [[nodiscard]] float GetLastHeldBeat() const; HoldNoteScore hns{ HNS_None }; @@ -81,7 +81,7 @@ struct HoldNoteResult bool bActive{ false }; // XML - XNode* CreateNode() const; + [[nodiscard]] XNode* CreateNode() const; void LoadFromNode(const XNode* pNode); // Lua @@ -165,23 +165,19 @@ struct TapNote HoldNoteResult HoldResult; // XML - XNode* CreateNode() const; + [[nodiscard]] XNode* CreateNode() const; void LoadFromNode(const XNode* pNode); // Lua void PushSelf(lua_State* L); // So I'm not repeatedly typing this out - Mina - bool IsNote() const + [[nodiscard]] bool IsNote() const { return type == TapNoteType_Tap || type == TapNoteType_HoldHead; } - TapNote() - : result() - , HoldResult() - { - } + TapNote() {} void Init() { type = TapNoteType_Empty; @@ -196,9 +192,7 @@ struct TapNote : type(type_) , subType(subType_) , source(source_) - , result() , iKeysoundIndex(iKeysoundIndex_) - , HoldResult() { if (type_ > TapNoteType_Fake) { LOG->Trace("Invalid tap note type %s (most likely) due to random " @@ -416,7 +410,7 @@ ToBeat(float beat) * @return T the scaled position */ template -inline T +T ScalePosition(T start, T length, T newLength, T position) { if (position < start) diff --git a/src/Etterna/Models/Misc/OptionRowHandler.cpp b/src/Etterna/Models/Misc/OptionRowHandler.cpp index 55ca0a1dbf..547192e8c8 100644 --- a/src/Etterna/Models/Misc/OptionRowHandler.cpp +++ b/src/Etterna/Models/Misc/OptionRowHandler.cpp @@ -1,7 +1,6 @@ #include "Etterna/Globals/global.h" #include "CommonMetrics.h" #include "Etterna/Models/Fonts/FontCharAliases.h" -#include "Foreach.h" #include "Etterna/Singletons/GameManager.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/LuaManager.h" diff --git a/src/Etterna/Models/Misc/OptionRowHandler.h b/src/Etterna/Models/Misc/OptionRowHandler.h index 3df45f72c9..9493360c4c 100644 --- a/src/Etterna/Models/Misc/OptionRowHandler.h +++ b/src/Etterna/Models/Misc/OptionRowHandler.h @@ -3,6 +3,7 @@ #include "GameCommand.h" #include "Etterna/Models/Lua/LuaReference.h" + #include struct MenuRowDef; @@ -63,8 +64,8 @@ struct OptionRowDefinition SelectType m_selectType{ SELECT_ONE }; LayoutType m_layoutType{ LAYOUT_SHOW_ALL_IN_ROW }; vector m_vsChoices; - set m_vEnabledForPlayers; // only players in this set may - // change focus to this row + std::set m_vEnabledForPlayers; // only players in this set may + // change focus to this row int m_iDefault{ -1 }; bool m_bExportOnChange{ false }; /** @@ -91,7 +92,7 @@ struct OptionRowDefinition * @brief Is this option enabled for the Player? * @param pn the Player the PlayerNumber represents. * @return true if the option is enabled, false otherwise. */ - bool IsEnabledForPlayer(PlayerNumber pn) const + [[nodiscard]] bool IsEnabledForPlayer(PlayerNumber pn) const { return m_vEnabledForPlayers.find(pn) != m_vEnabledForPlayers.end(); } @@ -99,8 +100,6 @@ struct OptionRowDefinition OptionRowDefinition() : m_sName("") , m_sExplanationName("") - , m_vsChoices() - , m_vEnabledForPlayers() { m_vEnabledForPlayers.insert(PLAYER_1); @@ -125,31 +124,29 @@ struct OptionRowDefinition OptionRowDefinition(const char* n, bool b, - const char* c0 = NULL, - const char* c1 = NULL, - const char* c2 = NULL, - const char* c3 = NULL, - const char* c4 = NULL, - const char* c5 = NULL, - const char* c6 = NULL, - const char* c7 = NULL, - const char* c8 = NULL, - const char* c9 = NULL, - const char* c10 = NULL, - const char* c11 = NULL, - const char* c12 = NULL, - const char* c13 = NULL, - const char* c14 = NULL, - const char* c15 = NULL, - const char* c16 = NULL, - const char* c17 = NULL, - const char* c18 = NULL, - const char* c19 = NULL) + const char* c0 = nullptr, + const char* c1 = nullptr, + const char* c2 = nullptr, + const char* c3 = nullptr, + const char* c4 = nullptr, + const char* c5 = nullptr, + const char* c6 = nullptr, + const char* c7 = nullptr, + const char* c8 = nullptr, + const char* c9 = nullptr, + const char* c10 = nullptr, + const char* c11 = nullptr, + const char* c12 = nullptr, + const char* c13 = nullptr, + const char* c14 = nullptr, + const char* c15 = nullptr, + const char* c16 = nullptr, + const char* c17 = nullptr, + const char* c18 = nullptr, + const char* c19 = nullptr) : m_sName(n) , m_sExplanationName("") , m_bOneChoiceForAllPlayers(b) - , m_vsChoices() - , m_vEnabledForPlayers() { m_vEnabledForPlayers.insert(PLAYER_1); @@ -186,14 +183,10 @@ class OptionRowHandler { public: OptionRowDefinition m_Def; - vector + std::vector m_vsReloadRowMessages; // refresh this row on on these messages - OptionRowHandler() - : m_Def() - , m_vsReloadRowMessages() - { - } + OptionRowHandler() {} virtual ~OptionRowHandler() = default; virtual void Init() { @@ -205,8 +198,9 @@ class OptionRowHandler Init(); return this->LoadInternal(cmds); } - std::string OptionTitle() const; - std::string GetThemedItemText(int iChoice) const; + + [[nodiscard]] std::string OptionTitle() const; + [[nodiscard]] std::string GetThemedItemText(int iChoice) const; virtual bool LoadInternal(const Commands&) { return true; } @@ -221,22 +215,26 @@ class OptionRowHandler * and nothing has changed, return RELOAD_CHANGED_NONE. */ virtual ReloadChanged Reload() { return RELOAD_CHANGED_NONE; } - virtual int GetDefaultOption() const { return -1; } + [[nodiscard]] virtual int GetDefaultOption() const { return -1; } virtual void ImportOption(OptionRow*, const PlayerNumber&, - vector& vbSelectedOut) const + std::vector& vbSelectedOut) const { } // Returns an OPT mask. - virtual int ExportOption(const PlayerNumber&, - const vector& vbSelected) const + [[nodiscard]] virtual int ExportOption(const PlayerNumber&, + const vector& vbSelected) const { return 0; } virtual void GetIconTextAndGameCommand(int iFirstSelection, std::string& sIconTextOut, GameCommand& gcOut) const; - virtual std::string GetScreen(int /* iChoice */) const { return std::string(); } + + [[nodiscard]] virtual std::string GetScreen(int /* iChoice */) const + { + return std::string(); + } // Exists so that a lua function can act on the selection. Returns true if // the choices should be reloaded. virtual bool NotifyOfSelection(PlayerNumber pn, int choice) diff --git a/src/Etterna/Models/Misc/PlayerInfo.cpp b/src/Etterna/Models/Misc/PlayerInfo.cpp index 9302813800..75309b504b 100644 --- a/src/Etterna/Models/Misc/PlayerInfo.cpp +++ b/src/Etterna/Models/Misc/PlayerInfo.cpp @@ -20,15 +20,12 @@ static ThemeMetric SCORE_KEEPER_CLASS("ScreenGameplay", PlayerInfo::PlayerInfo() : m_pn(PLAYER_INVALID) - , m_SoundEffectControl() - , m_vpStepsQueue() - , m_pLifeMeter(NULL) - , m_ptextStepsDescription(NULL) - , m_pPrimaryScoreKeeper(NULL) - , m_ptextPlayerOptions(NULL) - , m_NoteData() - , m_pPlayer(NULL) - , m_pStepsDisplay(NULL) + , m_pLifeMeter(nullptr) + , m_ptextStepsDescription(nullptr) + , m_pPrimaryScoreKeeper(nullptr) + , m_ptextPlayerOptions(nullptr) + , m_pPlayer(nullptr) + , m_pStepsDisplay(nullptr) { } @@ -44,8 +41,8 @@ PlayerInfo::Load(PlayerNumber pn, m_bPlayerEnabled = IsEnabled(); m_bIsDummy = false; m_iAddToDifficulty = iAddToDifficulty; - m_pLifeMeter = NULL; - m_ptextStepsDescription = NULL; + m_pLifeMeter = nullptr; + m_ptextStepsDescription = nullptr; if (!IsMultiPlayer()) { PlayMode mode = GAMESTATE->m_PlayMode; @@ -62,7 +59,7 @@ PlayerInfo::Load(PlayerNumber pn, m_pPrimaryScoreKeeper = ScoreKeeper::MakeScoreKeeper( SCORE_KEEPER_CLASS, pPlayerState, pPlayerStageStats); - m_ptextPlayerOptions = NULL; + m_ptextPlayerOptions = nullptr; if (mode == GameplayMode_Replay) { m_pPlayer = new PlayerReplay(m_NoteData, bShowNoteField); } else if (mode == GameplayMode_Practice) { @@ -71,7 +68,7 @@ PlayerInfo::Load(PlayerNumber pn, m_pPlayer = new Player(m_NoteData, bShowNoteField); } - m_pStepsDisplay = NULL; + m_pStepsDisplay = nullptr; if (IsMultiPlayer()) { pPlayerState->m_PlayerOptions = diff --git a/src/Etterna/Models/Misc/PlayerOptions.cpp b/src/Etterna/Models/Misc/PlayerOptions.cpp index 46797903af..32719b1c63 100644 --- a/src/Etterna/Models/Misc/PlayerOptions.cpp +++ b/src/Etterna/Models/Misc/PlayerOptions.cpp @@ -1,6 +1,5 @@ #include "Etterna/Globals/global.h" #include "CommonMetrics.h" -#include "Foreach.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/NoteSkinManager.h" #include "PlayerOptions.h" @@ -8,6 +7,7 @@ #include "Etterna/Models/Songs/Song.h" #include "Etterna/Models/StepsAndStyles/Steps.h" #include "Etterna/Models/StepsAndStyles/Style.h" + #include static const char* LifeTypeNames[] = { @@ -456,27 +456,26 @@ PlayerOptions::FromOneModString(const std::string& sOneMod, vector asParts; split(sBit, " ", asParts, true); - FOREACH_CONST(std::string, asParts, s) - { - if (*s == "no") { + for (auto& s : asParts) { + if (s == "no") { level = 0; - } else if (isdigit((*s)[0]) || (*s)[0] == '-') { + } else if (isdigit(s[0]) || s[0] == '-') { /* If the last character is a *, they probably said "123*" when * they meant "*123". */ - if (s->back() == '*') { + if (s.back() == '*') { // XXX: We know what they want, is there any reason not to // handle it? Yes. We should be strict in handling the format. // -Chris sErrorOut = ssprintf("Invalid player options \"%s\"; did you mean '*%d'?", - s->c_str(), - StringToInt(*s)); + s.c_str(), + StringToInt(s)); return false; } else { - level = StringToFloat(*s) / 100.0f; + level = StringToFloat(s) / 100.0f; } - } else if ((*s)[0] == '*') { - sscanf((*s).c_str(), "*%f", &speed); + } else if (s[0] == '*') { + sscanf(s.c_str(), "*%f", &speed); if (!isfinite(speed)) speed = 1.0f; } @@ -1144,9 +1143,8 @@ PlayerOptions::GetLocalizedMods(vector& AddTo) const { vector vMods; GetMods(vMods); - FOREACH_CONST(std::string, vMods, s) - { - const std::string& sOneMod = *s; + for (auto& s : vMods) { + const std::string& sOneMod = s; ASSERT(!sOneMod.empty()); diff --git a/src/Etterna/Models/Misc/PlayerOptions.h b/src/Etterna/Models/Misc/PlayerOptions.h index e67b47a768..5805999340 100644 --- a/src/Etterna/Models/Misc/PlayerOptions.h +++ b/src/Etterna/Models/Misc/PlayerOptions.h @@ -68,8 +68,8 @@ class PlayerOptions }; void Init(); void Approach(const PlayerOptions& other, float fDeltaSeconds); - std::string GetString(bool bForceNoteSkin = false) const; - std::string GetSavedPrefsString() + [[nodiscard]] std::string GetString(bool bForceNoteSkin = false) const; + [[nodiscard]] std::string GetSavedPrefsString() const; // only the basic options that players would want for every song enum ResetPrefsType { @@ -77,22 +77,23 @@ class PlayerOptions }; void ResetPrefs(ResetPrefsType type); void ResetSavedPrefs() { ResetPrefs(saved_prefs); }; - void GetMods(vector& AddTo, bool bForceNoteSkin = false) const; - void GetTurnMods(vector& AddTo); - void ResetModsToStringVector(vector mods); + void GetMods(std::vector& AddTo, + bool bForceNoteSkin = false) const; + void GetTurnMods(std::vector& AddTo); + void ResetModsToStringVector(std::vector mods); void ResetToggleableMods(); - void GetLocalizedMods(vector& AddTo) const; + void GetLocalizedMods(std::vector& AddTo) const; void FromString(const std::string& sMultipleMods); bool FromOneModString(const std::string& sOneMod, - std::string& sErrorDetailOut); // On error, return false - // and optionally set - // sErrorDetailOut + std::string& sErrorDetailOut); // On error, return + // false and optionally + // set sErrorDetailOut void ChooseRandomModifiers(); // Returns true for modifiers that should invalidate a score or otherwise // make it impossible to calculate Replay info - bool ContainsTransformOrTurn() const; + [[nodiscard]] bool ContainsTransformOrTurn() const; - vector GetInvalidatingModifiers() const; + [[nodiscard]] std::vector GetInvalidatingModifiers() const; // Lua void PushSelf(lua_State* L); @@ -161,7 +162,7 @@ class PlayerOptions TURN_RIGHT, /**< The arrows are turned 90 degress to the right. */ TURN_SHUFFLE, /**< Some of the arrow columns are changed throughout the whole song. */ - TURN_SOFT_SHUFFLE, /**< Only shuffle arrow columns on an axis of + TURN_SOFT_SHUFFLE, /**< Only shuffle arrow columns on an axis of symmetry. */ TURN_SUPER_SHUFFLE, /**< Every arrow is placed on a random column. */ NUM_TURNS @@ -206,7 +207,7 @@ class PlayerOptions NUM_SCROLLS }; - float GetReversePercentForColumn( + [[nodiscard]] float GetReversePercentForColumn( int iCol) const; // accounts for all Directions PlayerNumber m_pn{ PLAYER_1 }; // Needed for fetching the style. diff --git a/src/Etterna/Models/Misc/PlayerStageStats.cpp b/src/Etterna/Models/Misc/PlayerStageStats.cpp index 8cb979e06c..92dd270a5a 100644 --- a/src/Etterna/Models/Misc/PlayerStageStats.cpp +++ b/src/Etterna/Models/Misc/PlayerStageStats.cpp @@ -1,6 +1,5 @@ #include "Etterna/Globals/global.h" #include "CommonMetrics.h" -#include "Foreach.h" #include "Etterna/Singletons/GameState.h" #include "Etterna/Singletons/LuaManager.h" #include "Etterna/Globals/MinaCalc.h" @@ -114,8 +113,8 @@ PlayerStageStats::AddStats(const PlayerStageStats& other) { m_pStyle = other.m_pStyle; m_bJoined = other.m_bJoined; - FOREACH_CONST(Steps*, other.m_vpPossibleSteps, s) - m_vpPossibleSteps.push_back(*s); + for (auto& s : other.m_vpPossibleSteps) + m_vpPossibleSteps.push_back(s); m_iStepsPlayed += other.m_iStepsPlayed; m_fAliveSeconds += other.m_fAliveSeconds; m_bFailed |= static_cast(other.m_bFailed); @@ -158,9 +157,7 @@ PlayerStageStats::AddStats(const PlayerStageStats& other) m_fLifeRecord[fOtherFirstSecond + pos] = life; } - for (unsigned i = 0; i < other.m_ComboList.size(); ++i) { - const Combo_t& combo = other.m_ComboList[i]; - + for (auto combo : other.m_ComboList) { Combo_t newcombo(combo); newcombo.m_fStartSecond += fOtherFirstSecond; m_ComboList.push_back(newcombo); @@ -481,9 +478,8 @@ PlayerStageStats::GetLessonScoreNeeded() const { float fScore = 0; - FOREACH_CONST(Steps*, m_vpPossibleSteps, steps) - { - fScore += (*steps)->GetRadarValues()[RadarCategory_TapsAndHolds]; + for (auto& steps : m_vpPossibleSteps) { + fScore += steps->GetRadarValues()[RadarCategory_TapsAndHolds]; } return lround(fScore * LESSON_PASS_THRESHOLD); @@ -987,8 +983,8 @@ LuaFunction(GetGradeFromPercent, GetGradeFromPercent(FArg(1))) doot.emplace_back(offs[i] * 1000); } else { // But type is empty if the replay is old :( - for (size_t i = 0; i < offs.size(); ++i) - doot.emplace_back(offs[i] * 1000); + for (float off : offs) + doot.emplace_back(off * 1000); } LuaHelpers::CreateTableFromArray(doot, L); return 1; diff --git a/src/Etterna/Models/Misc/PlayerState.cpp b/src/Etterna/Models/Misc/PlayerState.cpp index 95e183df41..ca838731d8 100644 --- a/src/Etterna/Models/Misc/PlayerState.cpp +++ b/src/Etterna/Models/Misc/PlayerState.cpp @@ -69,7 +69,7 @@ const TimingData& PlayerState::GetDisplayedTiming() const { Steps* steps = GAMESTATE->m_pCurSteps; - if (steps == NULL) + if (steps == nullptr) return GAMESTATE->m_pCurSong->m_SongTiming; return *steps->GetTimingData(); } diff --git a/src/Etterna/Models/Misc/PlayerState.h b/src/Etterna/Models/Misc/PlayerState.h index 5cbecf7c5b..3795f1bcba 100644 --- a/src/Etterna/Models/Misc/PlayerState.h +++ b/src/Etterna/Models/Misc/PlayerState.h @@ -69,14 +69,14 @@ class PlayerState * Player::Load() be used a lot in ArrowEffects to determine the * target beat in O(log N). */ - vector m_CacheDisplayedBeat; + std::vector m_CacheDisplayedBeat; /** * @brief Holds a vector sorted by beat, the cumulative number of notes from * the start of the song. This will be used by [insert more * description here] */ - vector m_CacheNoteStat; + std::vector m_CacheNoteStat; /** * @brief Change the PlayerOptions to their default. diff --git a/src/Etterna/Models/Misc/Preference.h b/src/Etterna/Models/Misc/Preference.h index 16b43575c1..7b83ce354b 100644 --- a/src/Etterna/Models/Misc/Preference.h +++ b/src/Etterna/Models/Misc/Preference.h @@ -22,13 +22,13 @@ class IPreference virtual void LoadDefault() = 0; virtual void SetDefaultFromString(const std::string& s) = 0; - virtual std::string ToString() const = 0; + [[nodiscard]] virtual std::string ToString() const = 0; virtual void FromString(const std::string& s) = 0; virtual void SetFromStack(lua_State* L); virtual void PushValue(lua_State* L) const; - const std::string& GetName() const { return m_sName; } + [[nodiscard]] const std::string& GetName() const { return m_sName; } static IPreference* GetPreferenceByName(const std::string& sName); static void LoadAllDefaults(); @@ -54,7 +54,7 @@ class Preference : public IPreference public: Preference(const std::string& sName, const T& defaultValue, - void(pfnValidate)(T& val) = NULL) + void(pfnValidate)(T& val) = nullptr) : IPreference(sName) , m_currentValue(defaultValue) , m_defaultValue(defaultValue) @@ -63,7 +63,7 @@ class Preference : public IPreference LoadDefault(); } - std::string ToString() const override + [[nodiscard]] std::string ToString() const override { return StringConversion::ToString(m_currentValue); } @@ -133,7 +133,7 @@ class Preference1D { public: using PreferenceT = Preference; - vector m_v; + std::vector m_v; Preference1D(void pfn(size_t i, std::string& sNameOut, T& defaultValueOut), size_t N) @@ -148,8 +148,8 @@ class Preference1D ~Preference1D() { - for (size_t i = 0; i < m_v.size(); ++i) - SAFE_DELETE(m_v[i]); + for (auto& v : m_v) + SAFE_DELETE(v); } const Preference& operator[](size_t i) const { return *m_v[i]; } Preference& operator[](size_t i) { return *m_v[i]; } diff --git a/src/Etterna/Models/Misc/Profile.cpp b/src/Etterna/Models/Misc/Profile.cpp index 7d42e99cf0..80e5f3236b 100644 --- a/src/Etterna/Models/Misc/Profile.cpp +++ b/src/Etterna/Models/Misc/Profile.cpp @@ -19,11 +19,12 @@ #include "Etterna/Singletons/ThemeManager.h" #include "Etterna/Singletons/CryptManager.h" #include "Etterna/Models/Misc/Game.h" -#include #include "Etterna/Models/Misc/XMLProfile.h" #include "Etterna/Models/Songs/SongOptions.h" #include "Etterna/Singletons/DownloadManager.h" +#include + /** @brief The filename for where one can edit their personal profile * information. */ const std::string EDITABLE_INI = "Editable.ini"; @@ -38,16 +39,6 @@ const std::string RIVAL_SUBDIR = "Rivals/"; #define GUID_SIZE_BYTES 8 -#define MAX_EDITABLE_INI_SIZE_BYTES (2 * 1024) // 2KB -#define MAX_PLAYER_STATS_XML_SIZE_BYTES \ - (400 /* Songs */ \ - * 5 /* Steps per Song */ \ - * 5 /* HighScores per Steps */ \ - * 1024) /* size in bytes of a HighScores XNode */ - -const int DEFAULT_WEIGHT_POUNDS = 120; -const float DEFAULT_BIRTH_YEAR = 1995; - #if defined(_MSC_VER) #pragma warning(disable : 4706) // assignment within conditional expression #endif @@ -63,7 +54,7 @@ void Profile::ClearStats() { // don't reset the Guid - std::string sGuid = m_sGuid; + const auto sGuid = m_sGuid; InitAll(); m_sGuid = sGuid; } @@ -71,12 +62,12 @@ Profile::ClearStats() std::string Profile::MakeGuid() { - string s; + std::string s; s.reserve(GUID_SIZE_BYTES * 2); unsigned char buf[GUID_SIZE_BYTES]; CryptManager::GetRandomBytes(buf, GUID_SIZE_BYTES); - for (unsigned i = 0; i < GUID_SIZE_BYTES; i++) - s += ssprintf("%02x", buf[i]); + for (auto i : buf) + s += ssprintf("%02x", i); return s; } @@ -113,8 +104,8 @@ Profile::InitGeneralData() m_iNumSongsPlayedByStyle.clear(); FOREACH_ENUM(Difficulty, i) m_iNumSongsPlayedByDifficulty[i] = 0; - for (int i = 0; i < MAX_METER + 1; i++) - m_iNumSongsPlayedByMeter[i] = 0; + for (auto& i : m_iNumSongsPlayedByMeter) + i = 0; m_iNumTotalSongsPlayed = 0; ZERO(m_iNumStagesPassedByPlayMode); ZERO(m_iNumStagesPassedByGrade); @@ -134,10 +125,9 @@ Profile::GetDisplayNameOrHighScoreName() const { if (!m_sDisplayName.empty()) return m_sDisplayName; - else if (!m_sLastUsedHighScoreName.empty()) + if (!m_sLastUsedHighScoreName.empty()) return m_sLastUsedHighScoreName; - else - return std::string(); + return std::string(); } /* @@ -166,7 +156,7 @@ void Profile::SetDefaultModifiers(const Game* pGameType, const std::string& sModifiers) { - if (sModifiers == "") + if (sModifiers.empty()) m_sDefaultModifiers.erase(pGameType->m_szName); else m_sDefaultModifiers[pGameType->m_szName] = sModifiers; @@ -175,15 +165,16 @@ Profile::SetDefaultModifiers(const Game* pGameType, Grade Profile::GetBestGrade(const Song* pSong, StepsType st) const { - Grade gradeBest = Grade_Invalid; + auto gradeBest = Grade_Invalid; if (pSong != nullptr) { - bool hasCurrentStyleSteps = false; + auto hasCurrentStyleSteps = false; FOREACH_ENUM_N(Difficulty, 6, i) { - Steps* pSteps = SongUtil::GetStepsByDifficulty(pSong, st, i); - if (pSteps != NULL) { + auto* pSteps = SongUtil::GetStepsByDifficulty(pSong, st, i); + if (pSteps != nullptr) { hasCurrentStyleSteps = true; - Grade dcg = SCOREMAN->GetBestGradeFor(pSteps->GetChartKey()); + const auto dcg = + SCOREMAN->GetBestGradeFor(pSteps->GetChartKey()); if (gradeBest >= dcg) { gradeBest = dcg; } @@ -192,12 +183,13 @@ Profile::GetBestGrade(const Song* pSong, StepsType st) const // If no grade was found for the current style/stepstype if (!hasCurrentStyleSteps) { // Get the best grade among all steps - auto& allSteps = pSong->GetAllSteps(); - for (auto& stepsPtr : allSteps) { + const auto& allSteps = pSong->GetAllSteps(); + for (const auto& stepsPtr : allSteps) { if (stepsPtr->m_StepsType == st) // Skip already checked steps of type st continue; - Grade dcg = SCOREMAN->GetBestGradeFor(stepsPtr->GetChartKey()); + const auto dcg = + SCOREMAN->GetBestGradeFor(stepsPtr->GetChartKey()); if (gradeBest >= dcg) { gradeBest = dcg; } @@ -264,8 +256,8 @@ Profile::LoadCustomFunction(const std::string& sDir) * [Profile] * CustomLoadFunction=function(profile, profileDir) ... end */ - Lua* L = LUA->Get(); - LuaReference customLoadFunc = + auto* L = LUA->Get(); + const auto customLoadFunc = THEME->GetMetricR("Profile", "CustomLoadFunction"); customLoadFunc.PushSelf(L); ASSERT_M(!lua_isnil(L, -1), "CustomLoadFunction not defined"); @@ -287,22 +279,22 @@ Profile::HandleStatsPrefixChange(std::string dir, bool require_signature) // Temp variables to preserve stuff across the reload. // Some stuff intentionally left out because the original reason for the // stats prefix was to allow scores from different game types to coexist. - std::string display_name = m_sDisplayName; - std::string last_high_score_name = m_sLastUsedHighScoreName; - int priority = m_ListPriority; - std::string guid = m_sGuid; - map default_mods = m_sDefaultModifiers; - SortOrder sort_order = m_SortOrder; - Difficulty last_diff = m_LastDifficulty; - StepsType last_stepstype = m_LastStepsType; - SongID last_song = m_lastSong; - int total_sessions = m_iTotalSessions; - int total_session_seconds = m_iTotalSessionSeconds; - int total_gameplay_seconds = m_iTotalGameplaySeconds; - LuaTable user_table = m_UserTable; - bool need_to_create_file = false; + const auto display_name = m_sDisplayName; + const auto last_high_score_name = m_sLastUsedHighScoreName; + const auto priority = m_ListPriority; + const auto guid = m_sGuid; + const auto default_mods = m_sDefaultModifiers; + const auto sort_order = m_SortOrder; + const auto last_diff = m_LastDifficulty; + const auto last_stepstype = m_LastStepsType; + const auto last_song = m_lastSong; + const auto total_sessions = m_iTotalSessions; + const auto total_session_seconds = m_iTotalSessionSeconds; + const auto total_gameplay_seconds = m_iTotalGameplaySeconds; + const auto user_table = m_UserTable; + auto need_to_create_file = false; if (IsAFile(dir + PROFILEMAN->GetStatsPrefix() + ETT_XML)) { - LoadAllFromDir(dir, require_signature, NULL); + LoadAllFromDir(dir, require_signature, nullptr); } else { ClearStats(); need_to_create_file = true; @@ -339,7 +331,7 @@ Profile::LoadAllFromDir(const std::string& sDir, LoadTypeFromDir(sDir); DBProf.SetLoadingProfile(this); XMLProf.SetLoadingProfile(this); - ProfileLoadResult ret = XMLProf.LoadEttFromDir(sDir); + const auto ret = XMLProf.LoadEttFromDir(sDir); if (ret != ProfileLoadResult_Success) return ret; @@ -355,12 +347,12 @@ void Profile::LoadTypeFromDir(const std::string& dir) { m_ListPriority = 0; - std::string fn = dir + TYPE_INI; + const auto fn = dir + TYPE_INI; if (FILEMAN->DoesFileExist(fn)) { IniFile ini; if (ini.ReadFile(fn)) { XNode const* data = ini.GetChild("ListPosition"); - if (data != NULL) { + if (data != nullptr) { data->GetAttrValue("Priority", m_ListPriority); } } @@ -371,14 +363,13 @@ void Profile::CalculateStatsFromScores(LoadingWindow* ld) { LOG->Trace("Calculating stats from scores"); - const vector& all = SCOREMAN->GetAllProfileScores(m_sProfileID); - float TotalGameplaySeconds = 0.f; + const auto& all = SCOREMAN->GetAllProfileScores(m_sProfileID); + auto TotalGameplaySeconds = 0.f; m_iTotalTapsAndHolds = 0; m_iTotalHolds = 0; m_iTotalMines = 0; - for (size_t i = 0; i < all.size(); ++i) { - HighScore* hs = all[i]; + for (auto* hs : all) { TotalGameplaySeconds += hs->GetSurvivalSeconds(); m_iTotalTapsAndHolds += hs->GetTapNoteScore(TNS_W1); m_iTotalTapsAndHolds += hs->GetTapNoteScore(TNS_W2); @@ -415,7 +406,7 @@ Profile::SaveAllToDir(const std::string& sDir, bool bSignData) const GAMESTATE->SaveCurrentSettingsToProfile(PLAYER_1); - bool bSaved = XMLProf.SaveEttXmlToDir(sDir, this); + const auto bSaved = XMLProf.SaveEttXmlToDir(sDir, this); SaveStatsWebPageToDir(sDir); // Empty directories if none exist. @@ -446,16 +437,10 @@ Profile::SaveEditableDataToDir(const std::string& sDir) const ProfileLoadResult Profile::LoadEditableDataFromDir(const std::string& sDir) { - std::string fn = sDir + EDITABLE_INI; + const auto fn = sDir + EDITABLE_INI; // Don't load unreasonably large editable.xml files. - int iBytes = FILEMAN->GetFileSizeInBytes(fn); - if (iBytes > MAX_EDITABLE_INI_SIZE_BYTES) { - LuaHelpers::ReportScriptErrorFmt( - "The file '%s' is unreasonably large. It won't be loaded.", - fn.c_str()); - return ProfileLoadResult_FailedTampered; - } + auto iBytes = FILEMAN->GetFileSizeInBytes(fn); if (!IsAFile(fn)) return ProfileLoadResult_FailedNoProfile; @@ -467,7 +452,7 @@ Profile::LoadEditableDataFromDir(const std::string& sDir) ini.GetValue("Editable", "LastUsedHighScoreName", m_sLastUsedHighScoreName); // This is data that the user can change, so we have to validate it. - wstring wstr = RStringToWstring(m_sDisplayName); + auto wstr = RStringToWstring(m_sDisplayName); if (wstr.size() > PROFILE_MAX_DISPLAY_NAME_LENGTH) wstr = wstr.substr(0, PROFILE_MAX_DISPLAY_NAME_LENGTH); m_sDisplayName = WStringToRString(wstr); @@ -546,7 +531,7 @@ Profile::FillGoalTable() XNode* ScoreGoal::CreateNode() const { - XNode* pNode = new XNode("ScoreGoal"); + auto* pNode = new XNode("ScoreGoal"); pNode->AppendChild("Rate", rate); pNode->AppendChild("Percent", percent); @@ -597,7 +582,7 @@ ScoreGoal::GetPBUpTo() const void ScoreGoal::CheckVacuity() { - auto pb = SCOREMAN->GetChartPBAt(chartkey, rate); + auto* const pb = SCOREMAN->GetChartPBAt(chartkey, rate); if (pb && pb->GetWifeScore() >= percent) vacuous = true; @@ -608,7 +593,7 @@ ScoreGoal::CheckVacuity() void ScoreGoal::UploadIfNotVacuous() { - if (!vacuous || timeachieved.GetString() != "") + if (!vacuous || !timeachieved.GetString().empty()) DLMAN->UpdateGoal( chartkey, percent, rate, achieved, timeassigned, timeachieved); } @@ -618,10 +603,10 @@ ScoreGoal& Profile::GetLowestGoalForRate(const string& ck, float rate) { auto& sgv = goalmap[ck].Get(); - float lowest = 100.f; - int lowestidx = 0; + auto lowest = 100.f; + auto lowestidx = 0; for (size_t i = 0; i < sgv.size(); ++i) { - ScoreGoal& tmp = sgv[i]; + auto& tmp = sgv[i]; if (tmp.rate == rate) { if (tmp.percent > lowest) { lowest = tmp.percent; @@ -643,8 +628,7 @@ Profile::SetAnyAchievedGoals(const string& ck, return; auto& sgv = goalmap[ck].Get(); - for (size_t i = 0; i < sgv.size(); ++i) { - ScoreGoal& tmp = sgv[i]; + for (auto& tmp : sgv) { if (lround(tmp.rate * 10000.f) == lround(rate * 10000.f) && !tmp.achieved && tmp.percent < pscore.GetWifeScore()) { tmp.achieved = true; @@ -675,7 +659,7 @@ Profile::RemoveGoal(const string& ck, DateTime assigned) void Profile::SaveStatsWebPageToDir(const std::string& sDir) const { - ASSERT(PROFILEMAN != NULL); + ASSERT(PROFILEMAN != nullptr); } void @@ -713,7 +697,7 @@ Profile::MakeUniqueFileNameNoExtension(const std::string& sDir, GetDirListing(sDir + sFileNameBeginning + "*", files, false, false); sort(files.begin(), files.end()); - int iIndex = 0; + auto iIndex = 0; for (int i = files.size() - 1; i >= 0; --i) { static Regex re("^" + sFileNameBeginning + "([0-9]{5})\\....$"); @@ -745,8 +729,8 @@ class LunaProfile : public Luna public: static int AddScreenshot(T* p, lua_State* L) { - HighScore* hs = Luna::check(L, 1); - std::string filename = SArg(2); + auto* hs = Luna::check(L, 1); + const std::string filename = SArg(2); Screenshot screenshot; screenshot.sFileName = filename; screenshot.sMD5 = BinaryToHex(CRYPTMAN->GetMD5ForFile(filename)); @@ -842,7 +826,7 @@ class LunaProfile : public Luna static int GetSongNumTimesPlayed(T* p, lua_State* L) { ASSERT(!lua_isnil(L, 1)); - Song* pS = Luna::check(L, 1); + auto* pS = Luna::check(L, 1); lua_pushnumber(L, 0); return 1; } @@ -850,7 +834,7 @@ class LunaProfile : public Luna static int HasPassedAnyStepsInSong(T* p, lua_State* L) { ASSERT(!lua_isnil(L, 1)); - Song* pS = Luna::check(L, 1); + auto* pS = Luna::check(L, 1); lua_pushboolean(L, false); return 1; } @@ -907,7 +891,7 @@ class LunaProfile : public Luna } static int GetLastPlayedSong(T* p, lua_State* L) { - Song* pS = p->m_lastSong.ToSong(); + auto* pS = p->m_lastSong.ToSong(); if (pS != nullptr) pS->PushSelf(L); else @@ -916,7 +900,7 @@ class LunaProfile : public Luna } static int GetPlayerSkillsetRating(T* p, lua_State* L) { - Skillset ss = Enum::Check(L, 1); + const auto ss = Enum::Check(L, 1); lua_pushnumber(L, p->m_fPlayerSkillsets[ss]); return 1; } @@ -1093,10 +1077,10 @@ class LunaProfile : public Luna static int IsCurrentChartPermamirror(T* p, lua_State* L) { - bool o = false; + auto o = false; if (GAMESTATE->m_pCurSteps) { - const string& ck = GAMESTATE->m_pCurSteps->GetChartKey(); + const auto& ck = GAMESTATE->m_pCurSteps->GetChartKey(); if (p->PermaMirrorCharts.count(ck)) o = true; @@ -1109,15 +1093,15 @@ class LunaProfile : public Luna // ok i should probably handle this better -mina static int GetEasiestGoalForChartAndRate(T* p, lua_State* L) { - string ck = SArg(1); + const string ck = SArg(1); if (!p->goalmap.count(ck)) { lua_pushnil(L); return 1; } auto& sgv = p->goalmap[ck].goals; - bool herp = false; - int ez = 0; + auto herp = false; + auto ez = 0; for (size_t i = 0; i < sgv.size(); ++i) if (lround(sgv[i].rate * 10000.f) == lround(FArg(2) * 10000.f) && !sgv[i].achieved && sgv[i].percent <= sgv[ez].percent) { @@ -1136,7 +1120,7 @@ class LunaProfile : public Luna p->m_sDisplayName = SArg(1); // roundabout way to force id to be a dir // sometimes its a dir and sometimes it a number - std::string dir = + const auto dir = "/Save/LocalProfiles/" + Basename(p->m_sProfileID) + "/"; p->SaveEditableDataToDir(dir); return 1; @@ -1233,7 +1217,7 @@ class LunaScoreGoal : public Luna static int SetRate(T* p, lua_State* L) { if (!p->achieved) { - float newrate = FArg(1); + auto newrate = FArg(1); CLAMP(newrate, 0.7f, 3.0f); p->rate = newrate; p->CheckVacuity(); @@ -1245,7 +1229,7 @@ class LunaScoreGoal : public Luna static int SetPercent(T* p, lua_State* L) { if (!p->achieved) { - float newpercent = FArg(1); + auto newpercent = FArg(1); CLAMP(newpercent, .8f, 1.f); if (p->percent < 0.995f && newpercent > 0.995f) @@ -1263,7 +1247,7 @@ class LunaScoreGoal : public Luna static int SetPriority(T* p, lua_State* L) { if (!p->achieved) { - int newpriority = IArg(1); + auto newpriority = IArg(1); CLAMP(newpriority, 0, 100); p->priority = newpriority; p->UploadIfNotVacuous(); diff --git a/src/Etterna/Models/Misc/Profile.h b/src/Etterna/Models/Misc/Profile.h index 7cc4841494..ceba1e4dcb 100644 --- a/src/Etterna/Models/Misc/Profile.h +++ b/src/Etterna/Models/Misc/Profile.h @@ -12,6 +12,7 @@ #include "Etterna/Models/Misc/XMLProfile.h" #include "Etterna/Models/Misc/DBProfile.h" #include "arch/LoadingWindow/LoadingWindow.h" + #include #include @@ -23,7 +24,7 @@ struct lua_State; struct Playlist; // Current file versions -extern const string ETT_XML; +extern const std::string ETT_XML; /** * @brief The filename where one can edit their personal profile data. @@ -44,7 +45,7 @@ extern const std::string EDITABLE_INI; * to their own profile for use in the game unless they also have the "don't * share" file. DontShare contains a piece of information that we can * construct using STATS_XML but the user can't construct using STATS_XML. */ -extern const string DONT_SHARE_SIG; +extern const std::string DONT_SHARE_SIG; extern const std::string PUBLIC_KEY_FILE; extern const std::string SCREENSHOTS_SUBDIR; @@ -101,8 +102,8 @@ struct GoalsForChart { public: void Add(ScoreGoal& sg) { goals.emplace_back(sg); } - vector& Get() { return goals; } - vector goals; + std::vector& Get() { return goals; } + std::vector goals; XNode* CreateNode() const; void LoadFromNode(const XNode* pNode); @@ -130,13 +131,7 @@ class Profile m_sDisplayName("") , m_sLastUsedHighScoreName("") , m_sGuid(MakeGuid()) - , m_sDefaultModifiers() - , m_lastSong() , m_sLastPlayedMachineGuid("") - , m_LastPlayedDate() - , m_iNumSongsPlayedByStyle() - , m_UserTable() - , m_vScreenshots() , profiledir("") { m_lastSong.Unset(); @@ -162,7 +157,8 @@ class Profile std::string GetDisplayNameOrHighScoreName() const; bool GetDefaultModifiers(const Game* pGameType, std::string& sModifiersOut) const; - void SetDefaultModifiers(const Game* pGameType, const std::string& sModifiers); + void SetDefaultModifiers(const Game* pGameType, + const std::string& sModifiers); void AddStepTotals(int iNumTapsAndHolds, int iNumJumps, @@ -175,7 +171,7 @@ class Profile // Profiles of the same type and priority are sorted by dir name. int m_ListPriority{ 0 }; // Profile Playlists - map allplaylists; + std::map allplaylists; // Editable data std::string m_sDisplayName; @@ -192,7 +188,7 @@ class Profile static std::string MakeGuid(); std::string* GetGuid() { return &m_sGuid; } std::string m_sGuid; - map m_sDefaultModifiers; + std::map m_sDefaultModifiers; SortOrder m_SortOrder{ SortOrder_Invalid }; Difficulty m_LastDifficulty{ Difficulty_Invalid }; StepsType m_LastStepsType{ StepsType_Invalid }; @@ -232,7 +228,7 @@ class Profile * playing; that's the only approach that makes sense for ByDifficulty and * ByMeter. */ int m_iNumSongsPlayedByPlayMode[NUM_PlayMode]; - map m_iNumSongsPlayedByStyle; + std::map m_iNumSongsPlayedByStyle; int m_iNumSongsPlayedByDifficulty[NUM_Difficulty]; int m_iNumSongsPlayedByMeter[MAX_METER + 1]; /** @@ -245,27 +241,30 @@ class Profile // if anymore of these are added they should be enum'd to reduce copy pasta // -mina and also should be sets - void AddToFavorites(const string& ck) { FavoritedCharts.emplace(ck); } - void AddToPermaMirror(const string& ck) { PermaMirrorCharts.emplace(ck); } - void RemoveFromFavorites(const string& ck); - void RemoveFromPermaMirror(const string& ck); - set FavoritedCharts; - set PermaMirrorCharts; + void AddToFavorites(const std::string& ck) { FavoritedCharts.emplace(ck); } + void AddToPermaMirror(const std::string& ck) + { + PermaMirrorCharts.emplace(ck); + } + void RemoveFromFavorites(const std::string& ck); + void RemoveFromPermaMirror(const std::string& ck); + std::set FavoritedCharts; + std::set PermaMirrorCharts; // more future goalman stuff -mina - void AddGoal(const string& ck); - void RemoveGoal(const string& ck, DateTime assigned); - unordered_map goalmap; + void AddGoal(const std::string& ck); + void RemoveGoal(const std::string& ck, DateTime assigned); + std::unordered_map goalmap; void FillGoalTable(); - vector goaltable; + std::vector goaltable; int sortmode = 1; // 1=date 2=rate 3=name 4=priority 5=diff, init to name // because that's the default- mina int filtermode = 1; // 1=all, 2=completed, 3=uncompleted bool asc = false; - bool HasGoal(const string& ck) { return goalmap.count(ck) == 1; } - ScoreGoal& GetLowestGoalForRate(const string& ck, float rate); - void SetAnyAchievedGoals(const string& ck, + bool HasGoal(const std::string& ck) { return goalmap.count(ck) == 1; } + ScoreGoal& GetLowestGoalForRate(const std::string& ck, float rate); + void SetAnyAchievedGoals(const std::string& ck, float& rate, const HighScore& pscore); @@ -276,7 +275,7 @@ class Profile Grade GetBestGrade(const Song* pSong, StepsType st) const; // Screenshot Data - vector m_vScreenshots; + std::vector m_vScreenshots; void AddScreenshot(const Screenshot& screenshot); int GetNextScreenshotIndex() { return m_vScreenshots.size(); } @@ -315,12 +314,14 @@ class Profile void SaveStatsWebPageToDir(const std::string& sDir) const; void SaveMachinePublicKeyToDir(const std::string& sDir) const; - static void MoveBackupToDir(const std::string& sFromDir, const std::string& sToDir); + static void MoveBackupToDir(const std::string& sFromDir, + const std::string& sToDir); static std::string MakeUniqueFileNameNoExtension( const std::string& sDir, const std::string& sFileNameBeginning); - static std::string MakeFileNameNoExtension(const std::string& sFileNameBeginning, - int iIndex); + static std::string MakeFileNameNoExtension( + const std::string& sFileNameBeginning, + int iIndex); // Lua void PushSelf(lua_State* L); diff --git a/src/Etterna/Models/Misc/RoomWheel.cpp b/src/Etterna/Models/Misc/RoomWheel.cpp index 056bee4f0f..6fdb01e469 100644 --- a/src/Etterna/Models/Misc/RoomWheel.cpp +++ b/src/Etterna/Models/Misc/RoomWheel.cpp @@ -147,7 +147,7 @@ RoomWheel::RemoveItem(int index) // If this item's data happened to be last selected, make it NULL. if (m_LastSelection == *i) - m_LastSelection = NULL; + m_LastSelection = nullptr; SAFE_DELETE(*i); m_CurWheelItemData.erase(i); @@ -171,7 +171,7 @@ RoomWheel::Select() if (m_iSelection == 0) { // Since this is not actually an option outside of this wheel, NULL is a // good idea. - m_LastSelection = NULL; + m_LastSelection = nullptr; ScreenTextEntry::TextEntry( SM_BackFromRoomName, ENTER_ROOM_NAME, "", 255); } @@ -203,7 +203,7 @@ RoomWheel::Move(int n) { if (n == 0 && m_iSelection >= m_offset) { const RoomWheelItemData* data = GetItem(m_iSelection - m_offset); - if (data != NULL) + if (data != nullptr) SCREENMAN->PostMessageToTopScreen(SM_RoomInfoDeploy, 0); } else { SCREENMAN->PostMessageToTopScreen(SM_RoomInfoRetract, 0); @@ -286,14 +286,14 @@ RoomWheel::FilterBySearch() void RoomWheel::BuildFromRoomDatas() { - if (allRooms == NULL) + if (allRooms == nullptr) return; if (searching) FilterBySearch(); else roomsInWheel = (*allRooms); int difference = 0; - RoomWheelItemData* itemData = NULL; + RoomWheelItemData* itemData = nullptr; difference = GetNumItems() - roomsInWheel.size(); diff --git a/src/Etterna/Models/Misc/RoomWheel.h b/src/Etterna/Models/Misc/RoomWheel.h index ff1fac9c2b..2fb74421d1 100644 --- a/src/Etterna/Models/Misc/RoomWheel.h +++ b/src/Etterna/Models/Misc/RoomWheel.h @@ -1,4 +1,4 @@ -/* RoomWheel - A wheel containing data about rooms. */ +/* RoomWheel - A wheel containing data about rooms. */ #ifndef ROOM_WHEEL_H #define ROOM_WHEEL_H @@ -15,11 +15,11 @@ class RoomData void SetState(unsigned int state) { m_state = state; } void SetFlags(unsigned int iFlags) { m_iFlags = iFlags; } void SetHasPassword(bool pass) { hasPassword = pass; } - inline std::string Name() const { return m_name; } - inline std::string Description() const { return m_description; } - inline unsigned int State() const { return m_state; } - inline bool HasPassword() const { return hasPassword; } - inline unsigned int GetFlags() const { return m_iFlags; } + std::string Name() const { return m_name; } + std::string Description() const { return m_description; } + unsigned int State() const { return m_state; } + bool HasPassword() const { return hasPassword; } + unsigned int GetFlags() const { return m_iFlags; } RoomData() { m_name = ""; @@ -47,7 +47,6 @@ struct RoomWheelItemData : public WheelItemBaseData const bool hasPass = false) : WheelItemBaseData(type, sTitle, color) , m_sDesc(sDesc) - , m_iFlags(0) , hasPassword(hasPass){}; std::string m_sDesc; @@ -111,7 +110,7 @@ class RoomWheel : public WheelBase bool Select() override; void Move(int n) override; - inline RoomWheelItemData* GetItem(unsigned int i) + RoomWheelItemData* GetItem(unsigned int i) { return dynamic_cast( WheelBase::GetItem(i + m_offset)); diff --git a/src/Etterna/Models/Misc/SampleHistory.h b/src/Etterna/Models/Misc/SampleHistory.h index 8dbd3b1621..0e765daea2 100644 --- a/src/Etterna/Models/Misc/SampleHistory.h +++ b/src/Etterna/Models/Misc/SampleHistory.h @@ -7,12 +7,12 @@ class SampleHistory public: SampleHistory(); void AddSample(float fSample, float fDeltaTime); - float GetSample(float fSecondsAgo) const; + [[nodiscard]] float GetSample(float fSecondsAgo) const; private: - float GetSampleNum(float fSamplesAgo) const; + [[nodiscard]] float GetSampleNum(float fSamplesAgo) const; - vector m_afHistory; + std::vector m_afHistory; int m_iLastHistory; int m_iHistorySamplesPerSecond; float m_fHistorySeconds; diff --git a/src/Etterna/Models/Misc/SubscriptionManager.h b/src/Etterna/Models/Misc/SubscriptionManager.h index 94da028a19..b0b6ee3ba5 100644 --- a/src/Etterna/Models/Misc/SubscriptionManager.h +++ b/src/Etterna/Models/Misc/SubscriptionManager.h @@ -4,6 +4,7 @@ #define SubscriptionManager_H #include +#include // Since this class has only POD types and no constructor, there's no // initialize order problem. @@ -18,21 +19,21 @@ class SubscriptionManager // collection ourself on first use. SubscriptionHandler itself is // a POD type, so a static SubscriptionHandler will always have // m_pSubscribers == NULL (before any static constructors are called). - set* m_pSubscribers; + std::set* m_pSubscribers; // Use this to access m_pSubscribers, so you don't have to worry about // it being NULL. - set& Get() + std::set& Get() { - if (m_pSubscribers == NULL) - m_pSubscribers = new set; + if (m_pSubscribers == nullptr) + m_pSubscribers = new std::set; return *m_pSubscribers; } void Subscribe(T* p) { - if (m_pSubscribers == NULL) - m_pSubscribers = new set; + if (m_pSubscribers == nullptr) + m_pSubscribers = new std::set; #ifdef DEBUG typename set::iterator iter = m_pSubscribers->find(p); ASSERT_M(iter == m_pSubscribers->end(), "already subscribed"); @@ -42,8 +43,8 @@ class SubscriptionManager void Unsubscribe(T* p) { - typename set::iterator iter = m_pSubscribers->find(p); - ASSERT(iter != m_pSubscribers->end()); + auto iter = m_pSubscribers->find(p); + assert(iter != m_pSubscribers->end()); m_pSubscribers->erase(iter); } }; diff --git a/src/Etterna/Models/Misc/ThemeMetric.h b/src/Etterna/Models/Misc/ThemeMetric.h index 898022f73a..13919fa36d 100644 --- a/src/Etterna/Models/Misc/ThemeMetric.h +++ b/src/Etterna/Models/Misc/ThemeMetric.h @@ -4,6 +4,7 @@ #define THEME_METRIC_H #include "Etterna/Singletons/ThemeManager.h" + #include /** @brief The general interface for reading ThemeMetrics. */ @@ -69,7 +70,6 @@ class ThemeMetric : public IThemeMetric ThemeMetric(const std::string& sGroup = "", const std::string& sName = "") : m_sGroup(sGroup) , m_sName(sName) - , m_Value() , m_currentValue(T()) , m_bCallEachTime(false) { @@ -196,7 +196,7 @@ class ThemeMetric1D : public IThemeMetric { Load(sGroup, pfn, N); } - ThemeMetric1D() { Load(std::string(), NULL, 0); } + ThemeMetric1D() { Load(std::string(), nullptr, 0); } void Load(const std::string& sGroup, MetricName1D pfn, size_t N) { m_metric.resize(N); @@ -269,9 +269,10 @@ class ThemeMetricMap : public IThemeMetric map m_metric; public: - ThemeMetricMap(const std::string& sGroup = "", - MetricNameMap pfn = nullptr, - const vector& vsValueNames = vector()) + ThemeMetricMap( + const std::string& sGroup = "", + MetricNameMap pfn = nullptr, + const vector& vsValueNames = vector()) { Load(sGroup, pfn, vsValueNames); } diff --git a/src/Etterna/Models/Misc/TimingData.cpp b/src/Etterna/Models/Misc/TimingData.cpp index ac17f081c3..b4aead0369 100644 --- a/src/Etterna/Models/Misc/TimingData.cpp +++ b/src/Etterna/Models/Misc/TimingData.cpp @@ -32,8 +32,8 @@ TimingData::Copy(const TimingData& cpy) { const vector& vpSegs = cpy.m_avpTimingSegments[tst]; - for (unsigned i = 0; i < vpSegs.size(); ++i) - AddSegment(vpSegs[i]); + for (auto vpSeg : vpSegs) + AddSegment(vpSeg); } } @@ -181,11 +181,10 @@ TimingData::CopyRange(int start_row, { if (seg_type == copy_type || copy_type == TimingSegmentType_Invalid) { const vector& segs = GetTimingSegments(seg_type); - for (size_t i = 0; i < segs.size(); ++i) { - if (segs[i]->GetRow() >= start_row && - segs[i]->GetRow() <= end_row) { - TimingSegment* copy = segs[i]->Copy(); - copy->SetRow(segs[i]->GetRow() + row_offset); + for (auto seg : segs) { + if (seg->GetRow() >= start_row && seg->GetRow() <= end_row) { + TimingSegment* copy = seg->Copy(); + copy->SetRow(seg->GetRow() + row_offset); dest.AddSegment(copy); // TimingSegment::Copy creates a new segment with new, and // AddSegment copies it again, so delete the temp. -Kyz @@ -295,8 +294,8 @@ TimingData::GetActualBPM(float& fMinBPMOut, fMaxBPMOut = 0; const vector& bpms = GetTimingSegments(SEGMENT_BPM); - for (unsigned i = 0; i < bpms.size(); i++) { - const float fBPM = ToBPM(bpms[i])->GetBPM(); + for (auto bpm : bpms) { + const float fBPM = ToBPM(bpm)->GetBPM(); fMaxBPMOut = clamp(max(fBPM, fMaxBPMOut), 0, highest); fMinBPMOut = min(fBPM, fMinBPMOut); } @@ -306,11 +305,11 @@ float TimingData::GetNextSegmentBeatAtRow(TimingSegmentType tst, int row) const { const vector segs = GetTimingSegments(tst); - for (unsigned i = 0; i < segs.size(); i++) { - if (segs[i]->GetRow() <= row) { + for (auto seg : segs) { + if (seg->GetRow() <= row) { continue; } - return segs[i]->GetBeat(); + return seg->GetBeat(); } return NoteRowToBeat(row); } @@ -320,11 +319,11 @@ TimingData::GetPreviousSegmentBeatAtRow(TimingSegmentType tst, int row) const { float backup = -1; const vector segs = GetTimingSegments(tst); - for (unsigned i = 0; i < segs.size(); i++) { - if (segs[i]->GetRow() >= row) { + for (auto seg : segs) { + if (seg->GetRow() >= row) { break; } - backup = segs[i]->GetBeat(); + backup = seg->GetBeat(); } return (backup > -1) ? backup : NoteRowToBeat(row); } @@ -465,10 +464,10 @@ TimingData::IsFakeAtRow(int iNoteRow) const * because they should never need to be used; we always have at least one such * segment in the TimingData, and if not, we'll crash anyway. -- vyhd */ static const TimingSegment* DummySegments[NUM_TimingSegmentType] = { - NULL, // BPMSegment + nullptr, // BPMSegment new StopSegment, new DelaySegment, - NULL, // TimeSignatureSegment + nullptr, // TimeSignatureSegment new WarpSegment, NULL, // LabelSegment NULL, // TickcountSegment @@ -599,22 +598,20 @@ TimingData::AddSegment(const TimingSegment* seg) EraseSegment(vSegs, index, cur); } return; - } else { - // Move the next segment's start back to this row. - next->SetRow(seg->GetRow()); - if (prev != cur) { - EraseSegment(vSegs, index, cur); - } - return; } - } else { - // if true, this is redundant segment change - if ((*prev) == (*seg)) { - if (prev != cur) { - EraseSegment(vSegs, index, cur); - } - return; + // Move the next segment's start back to this row. + next->SetRow(seg->GetRow()); + if (prev != cur) { + EraseSegment(vSegs, index, cur); + } + return; + } + // if true, this is redundant segment change + if ((*prev) == (*seg)) { + if (prev != cur) { + EraseSegment(vSegs, index, cur); } + return; } } else { // if true, this is redundant segment change @@ -659,8 +656,8 @@ bool TimingData::DoesLabelExist(const std::string& sLabel) const { const vector& labels = GetTimingSegments(SEGMENT_LABEL); - for (unsigned i = 0; i < labels.size(); i++) { - if (ToLabel(labels[i])->GetLabel() == sLabel) + for (auto label : labels) { + if (ToLabel(label)->GetLabel() == sLabel) return true; } return false; @@ -971,10 +968,8 @@ TimingData::ScaleRegion(float fScale, int length = iEndIndex - iStartIndex; int newLength = lround(fScale * length); - FOREACH_TimingSegmentType(tst) for (unsigned j = 0; - j < m_avpTimingSegments[tst].size(); - j++) m_avpTimingSegments[tst][j] - ->Scale(iStartIndex, length, newLength); + FOREACH_TimingSegmentType(tst) for (auto& j : m_avpTimingSegments[tst]) + j->Scale(iStartIndex, length, newLength); // adjust BPM changes to preserve timing if (bAdjustBPM) { @@ -983,15 +978,14 @@ TimingData::ScaleRegion(float fScale, vector& bpms = m_avpTimingSegments[SEGMENT_BPM]; // adjust BPM changes "between" iStartIndex and iNewEndIndex - for (unsigned i = 0; i < bpms.size(); i++) { - BPMSegment* bpm = ToBPM(bpms[i]); + for (auto& i : bpms) { + BPMSegment* bpm = ToBPM(i); const int iSegStart = bpm->GetRow(); if (iSegStart <= iStartIndex) continue; - else if (iSegStart >= iNewEndIndex) + if (iSegStart >= iNewEndIndex) continue; - else - bpm->SetBPM(bpm->GetBPM() * fScale); + bpm->SetBPM(bpm->GetBPM() * fScale); } // set BPM at iStartIndex and iNewEndIndex. @@ -1006,8 +1000,7 @@ TimingData::InsertRows(int iStartRow, int iRowsToAdd) FOREACH_TimingSegmentType(tst) { vector& segs = m_avpTimingSegments[tst]; - for (unsigned j = 0; j < segs.size(); j++) { - TimingSegment* seg = segs[j]; + for (auto seg : segs) { if (seg->GetRow() < iStartRow) continue; seg->SetRow(seg->GetRow() + iRowsToAdd); @@ -1033,7 +1026,7 @@ TimingData::DeleteRows(int iStartRow, int iRowsToDelete) // Don't delete the indefinite segments that are still in effect // at the end row; rather, shift them so they start there. TimingSegment* tsEnd = GetSegmentAtRow(iStartRow + iRowsToDelete, tst); - if (tsEnd != NULL && + if (tsEnd != nullptr && tsEnd->GetEffectType() == SegmentEffectType_Indefinite && iStartRow <= tsEnd->GetRow() && tsEnd->GetRow() < iStartRow + iRowsToDelete) { @@ -1223,14 +1216,13 @@ TimingData::NoteRowToMeasureAndBeat(int iNoteRow, iBeatIndexOut = iNumRowsThisSegment / iRowsPerMeasureThisSegment; iRowsRemainder = iNumRowsThisSegment % iRowsPerMeasureThisSegment; return; - } else { - // iNoteRow lands after this segment - int iNumRowsThisSegment = iSegmentEndRow - curSig->GetRow(); - int iNumMeasuresThisSegment = - (iNumRowsThisSegment + iRowsPerMeasureThisSegment - 1) / - iRowsPerMeasureThisSegment; // round up - iMeasureIndexOut += iNumMeasuresThisSegment; } + // iNoteRow lands after this segment + int iNumRowsThisSegment = iSegmentEndRow - curSig->GetRow(); + int iNumMeasuresThisSegment = + (iNumRowsThisSegment + iRowsPerMeasureThisSegment - 1) / + iRowsPerMeasureThisSegment; // round up + iMeasureIndexOut += iNumMeasuresThisSegment; } FAIL_M("Failed to get measure and beat for note row"); @@ -1242,8 +1234,8 @@ TimingData::ToVectorString(TimingSegmentType tst, int dec) const const vector segs = GetTimingSegments(tst); vector ret; - for (unsigned i = 0; i < segs.size(); i++) { - ret.push_back(segs[i]->ToString(dec)); + for (auto seg : segs) { + ret.push_back(seg->ToString(dec)); } return ret; } @@ -1515,8 +1507,8 @@ class LunaTimingData : public Luna if (lua_toboolean(L, 1)) { \ TimingSegmentSetToLuaTable(p, segment_name, L); \ } else { \ - LuaHelpers::CreateTableFromArray( \ - p->ToVectorString(segment_name), L); \ + LuaHelpers::CreateTableFromArray(p->ToVectorString(segment_name), \ + L); \ } \ return 1; \ } @@ -1538,8 +1530,8 @@ class LunaTimingData : public Luna vector vBPMs; const vector& bpms = p->GetTimingSegments(SEGMENT_BPM); - for (unsigned i = 0; i < bpms.size(); i++) - vBPMs.push_back(ToBPM(bpms[i])->GetBPM()); + for (auto bpm : bpms) + vBPMs.push_back(ToBPM(bpm)->GetBPM()); LuaHelpers::CreateTableFromArray(vBPMs, L); return 1; diff --git a/src/Etterna/Models/Misc/TimingData.h b/src/Etterna/Models/Misc/TimingData.h index d4ff2a0ae1..847730de17 100644 --- a/src/Etterna/Models/Misc/TimingData.h +++ b/src/Etterna/Models/Misc/TimingData.h @@ -3,7 +3,9 @@ #include "NoteTypes.h" #include "TimingSegments.h" + #include // max float + struct lua_State; /** @brief Compare a TimingData segment's properties with one another. */ @@ -13,28 +15,18 @@ struct lua_State; /* convenience functions to handle static casting */ template -inline T +T ToDerived(const TimingSegment* t, TimingSegmentType tst) { - ASSERT_M(t && tst == t->GetType(), - ssprintf("type mismatch (expected %s, got %s)", - TimingSegmentTypeToString(tst).c_str(), - TimingSegmentTypeToString(t->GetType()).c_str())); - return static_cast(t); } #define TimingSegmentToXWithName(Seg, SegName, SegType) \ inline const Seg* To##SegName(const TimingSegment* t) \ { \ - ASSERT(t->GetType() == SegType); \ return static_cast(t); \ } \ - inline Seg* To##SegName(TimingSegment* t) \ - { \ - ASSERT(t->GetType() == SegType); \ - return static_cast(t); \ - } + inline Seg* To##SegName(TimingSegment* t) { return static_cast(t); } #define TimingSegmentToX(Seg, SegType) \ TimingSegmentToXWithName(Seg##Segment, Seg, SEGMENT_##SegType) @@ -128,9 +120,8 @@ class TimingData // functions would return the wrong entry. // In a map with three entries, [-1]= 3, [6]= 1, [8]= 2, // lower_bound(0) and upper_bound(0) both returned the entry at [6]= 1. - // So the lookup table is a vector of entries and FindEntryInLookup does a - // binary search. - // -Kyz + // So the lookup table is a std::vector of entries and FindEntryInLookup + // does a binary search. -Kyz struct lookup_item_t { float first; @@ -141,32 +132,41 @@ class TimingData { } }; - typedef vector beat_start_lookup_t; + typedef std::vector beat_start_lookup_t; beat_start_lookup_t m_beat_start_lookup; beat_start_lookup_t m_time_start_lookup; void PrepareLookup(); void ReleaseLookup(); - int GetSegmentIndexAtRow(TimingSegmentType tst, int row) const; - int GetSegmentIndexAtBeat(TimingSegmentType tst, float beat) const + [[nodiscard]] int GetSegmentIndexAtRow(TimingSegmentType tst, + int row) const; + + [[nodiscard]] int GetSegmentIndexAtBeat(TimingSegmentType tst, + float beat) const { return GetSegmentIndexAtRow(tst, BeatToNoteRow(beat)); } - float GetNextSegmentBeatAtRow(TimingSegmentType tst, int row) const; - float GetNextSegmentBeatAtBeat(TimingSegmentType tst, float beat) const + [[nodiscard]] float GetNextSegmentBeatAtRow(TimingSegmentType tst, + int row) const; + + [[nodiscard]] float GetNextSegmentBeatAtBeat(TimingSegmentType tst, + float beat) const { return GetNextSegmentBeatAtRow(tst, BeatToNoteRow(beat)); } - float GetPreviousSegmentBeatAtRow(TimingSegmentType tst, int row) const; - float GetPreviousSegmentBeatAtBeat(TimingSegmentType tst, float beat) const + [[nodiscard]] float GetPreviousSegmentBeatAtRow(TimingSegmentType tst, + int row) const; + + [[nodiscard]] float GetPreviousSegmentBeatAtBeat(TimingSegmentType tst, + float beat) const { return GetPreviousSegmentBeatAtRow(tst, BeatToNoteRow(beat)); } - bool empty() const; + [[nodiscard]] bool empty() const; void CopyRange(int start_row, int end_row, @@ -197,8 +197,9 @@ class TimingData * @param tst the TimingSegmentType requested. * @return the segment in question. */ - const TimingSegment* GetSegmentAtRow(int iNoteRow, - TimingSegmentType tst) const; + [[nodiscard]] const TimingSegment* GetSegmentAtRow( + int iNoteRow, + TimingSegmentType tst) const; TimingSegment* GetSegmentAtRow(int iNoteRow, TimingSegmentType tst); /** @@ -207,8 +208,9 @@ class TimingData * @param tst the TimingSegmentType requested. * @return the segment in question. */ - const TimingSegment* GetSegmentAtBeat(float fBeat, - TimingSegmentType tst) const + [[nodiscard]] const TimingSegment* GetSegmentAtBeat( + float fBeat, + TimingSegmentType tst) const { return GetSegmentAtRow(BeatToNoteRow(fBeat), tst); } @@ -258,11 +260,12 @@ class TimingData #undef DefineSegment /* convenience aliases (Set functions are deprecated) */ - float GetBPMAtRow(int iNoteRow) const + [[nodiscard]] float GetBPMAtRow(int iNoteRow) const { return GetBPMSegmentAtRow(iNoteRow)->GetBPM(); } - float GetBPMAtBeat(float fBeat) const + + [[nodiscard]] float GetBPMAtBeat(float fBeat) const { return GetBPMAtRow(BeatToNoteRow(fBeat)); } @@ -275,11 +278,12 @@ class TimingData SetBPMAtRow(BeatToNoteRow(fBeat), fBPM); } - float GetStopAtRow(int iNoteRow) const + [[nodiscard]] float GetStopAtRow(int iNoteRow) const { return GetStopSegmentAtRow(iNoteRow)->GetPause(); } - float GetStopAtBeat(float fBeat) const + + [[nodiscard]] float GetStopAtBeat(float fBeat) const { return GetStopAtRow(BeatToNoteRow(fBeat)); } @@ -292,11 +296,12 @@ class TimingData SetStopAtRow(BeatToNoteRow(fBeat), fSeconds); } - float GetDelayAtRow(int iNoteRow) const + [[nodiscard]] float GetDelayAtRow(int iNoteRow) const { return GetDelaySegmentAtRow(iNoteRow)->GetPause(); } - float GetDelayAtBeat(float fBeat) const + + [[nodiscard]] float GetDelayAtBeat(float fBeat) const { return GetDelayAtRow(BeatToNoteRow(fBeat)); } @@ -319,11 +324,12 @@ class TimingData SetTimeSignatureAtRow(BeatToNoteRow(fBeat), iNum, iDen); } - float GetWarpAtRow(int iNoteRow) const + [[nodiscard]] float GetWarpAtRow(int iNoteRow) const { return GetWarpSegmentAtRow(iNoteRow)->GetLength(); } - float GetWarpAtBeat(float fBeat) const + + [[nodiscard]] float GetWarpAtBeat(float fBeat) const { return GetWarpAtRow(BeatToNoteRow(fBeat)); } @@ -337,11 +343,12 @@ class TimingData AddSegment(WarpSegment(BeatToNoteRow(fBeat), fLength)); } - int GetTickcountAtRow(int iNoteRow) const + [[nodiscard]] int GetTickcountAtRow(int iNoteRow) const { return GetTickcountSegmentAtRow(iNoteRow)->GetTicks(); } - int GetTickcountAtBeat(float fBeat) const + + [[nodiscard]] int GetTickcountAtBeat(float fBeat) const { return GetTickcountAtRow(BeatToNoteRow(fBeat)); } @@ -354,28 +361,32 @@ class TimingData SetTickcountAtRow(BeatToNoteRow(fBeat), iTicks); } - int GetComboAtRow(int iNoteRow) const + [[nodiscard]] int GetComboAtRow(int iNoteRow) const { return GetComboSegmentAtRow(iNoteRow)->GetCombo(); } - int GetComboAtBeat(float fBeat) const + + [[nodiscard]] int GetComboAtBeat(float fBeat) const { return GetComboAtRow(BeatToNoteRow(fBeat)); } - int GetMissComboAtRow(int iNoteRow) const + + [[nodiscard]] int GetMissComboAtRow(int iNoteRow) const { return GetComboSegmentAtRow(iNoteRow)->GetMissCombo(); } - int GetMissComboAtBeat(float fBeat) const + + [[nodiscard]] int GetMissComboAtBeat(float fBeat) const { return GetMissComboAtRow(BeatToNoteRow(fBeat)); } - const std::string& GetLabelAtRow(int iNoteRow) const + [[nodiscard]] const std::string& GetLabelAtRow(int iNoteRow) const { return GetLabelSegmentAtRow(iNoteRow)->GetLabel(); } - const std::string& GetLabelAtBeat(float fBeat) const + + [[nodiscard]] const std::string& GetLabelAtBeat(float fBeat) const { return GetLabelAtRow(BeatToNoteRow(fBeat)); } @@ -387,32 +398,36 @@ class TimingData { SetLabelAtRow(BeatToNoteRow(fBeat), sLabel); } - bool DoesLabelExist(const std::string& sLabel) const; - float GetSpeedPercentAtRow(int iNoteRow) const + [[nodiscard]] bool DoesLabelExist(const std::string& sLabel) const; + + [[nodiscard]] float GetSpeedPercentAtRow(int iNoteRow) const { return GetSpeedSegmentAtRow(iNoteRow)->GetRatio(); } - float GetSpeedPercentAtBeat(float fBeat) const + + [[nodiscard]] float GetSpeedPercentAtBeat(float fBeat) const { return GetSpeedPercentAtRow(BeatToNoteRow(fBeat)); } - float GetSpeedWaitAtRow(int iNoteRow) const + [[nodiscard]] float GetSpeedWaitAtRow(int iNoteRow) const { return GetSpeedSegmentAtRow(iNoteRow)->GetDelay(); } - float GetSpeedWaitAtBeat(float fBeat) const + + [[nodiscard]] float GetSpeedWaitAtBeat(float fBeat) const { return GetSpeedWaitAtRow(BeatToNoteRow(fBeat)); } // XXX: is there any point to having specific unit types? - SpeedSegment::BaseUnit GetSpeedModeAtRow(int iNoteRow) const + [[nodiscard]] SpeedSegment::BaseUnit GetSpeedModeAtRow(int iNoteRow) const { return GetSpeedSegmentAtRow(iNoteRow)->GetUnit(); } - SpeedSegment::BaseUnit GetSpeedModeAtBeat(float fBeat) + + [[nodiscard]] SpeedSegment::BaseUnit GetSpeedModeAtBeat(float fBeat) const { return GetSpeedModeAtRow(BeatToNoteRow(fBeat)); } @@ -464,13 +479,15 @@ class TimingData SetSpeedModeAtRow(BeatToNoteRow(fBeat), unit); } - float GetDisplayedSpeedPercent(float fBeat, float fMusicSeconds) const; + [[nodiscard]] float GetDisplayedSpeedPercent(float fBeat, + float fMusicSeconds) const; - float GetScrollAtRow(int iNoteRow) const + [[nodiscard]] float GetScrollAtRow(int iNoteRow) const { return GetScrollSegmentAtRow(iNoteRow)->GetRatio(); } - float GetScrollAtBeat(float fBeat) + + [[nodiscard]] float GetScrollAtBeat(float fBeat) const { return GetScrollAtRow(BeatToNoteRow(fBeat)); } @@ -484,22 +501,26 @@ class TimingData SetScrollAtRow(BeatToNoteRow(fBeat), fPercent); } - float GetFakeAtRow(int iRow) const + [[nodiscard]] float GetFakeAtRow(int iRow) const { return GetFakeSegmentAtRow(iRow)->GetLength(); } - float GetFakeAtBeat(float fBeat) const + + [[nodiscard]] float GetFakeAtBeat(float fBeat) const { return GetFakeAtRow(BeatToNoteRow(fBeat)); } - bool IsWarpAtRow(int iRow) const; - bool IsWarpAtBeat(float fBeat) const + [[nodiscard]] bool IsWarpAtRow(int iRow) const; + + [[nodiscard]] bool IsWarpAtBeat(float fBeat) const { return IsWarpAtRow(BeatToNoteRow(fBeat)); } - bool IsFakeAtRow(int iRow) const; - bool IsFakeAtBeat(float fBeat) const + + [[nodiscard]] bool IsFakeAtRow(int iRow) const; + + [[nodiscard]] bool IsFakeAtBeat(float fBeat) const { return IsFakeAtRow(BeatToNoteRow(fBeat)); } @@ -508,11 +529,12 @@ class TimingData * @brief Determine if this notes on this row can be judged. * @param row the row to focus on. * @return true if the row can be judged, false otherwise. */ - bool IsJudgableAtRow(int row) const + [[nodiscard]] bool IsJudgableAtRow(int row) const { return !IsWarpAtRow(row) && !IsFakeAtRow(row); } - bool IsJudgableAtBeat(float beat) const + + [[nodiscard]] bool IsJudgableAtBeat(float beat) const { return IsJudgableAtRow(BeatToNoteRow(beat)); } @@ -531,7 +553,8 @@ class TimingData float beat, unsigned int max_segment) const; void GetBeatAndBPSFromElapsedTime(GetBeatArgs& args) const; - float GetBeatFromElapsedTime(float elapsed_time) + + [[nodiscard]] float GetBeatFromElapsedTime(float elapsed_time) const // shortcut for places that care only about the beat { GetBeatArgs args; @@ -539,10 +562,12 @@ class TimingData GetBeatAndBPSFromElapsedTime(args); return args.beat; } - float GetElapsedTimeFromBeat(float fBeat) const; + + [[nodiscard]] float GetElapsedTimeFromBeat(float fBeat) const; void GetBeatAndBPSFromElapsedTimeNoOffset(GetBeatArgs& args) const; - float GetBeatFromElapsedTimeNoOffset(float elapsed_time) + + [[nodiscard]] float GetBeatFromElapsedTimeNoOffset(float elapsed_time) const // shortcut for places that care only about the beat { GetBeatArgs args; @@ -550,34 +575,49 @@ class TimingData GetBeatAndBPSFromElapsedTimeNoOffset(args); return args.beat; } - float GetElapsedTimeFromBeatNoOffset(float fBeat) const; - float GetDisplayedBeat(float fBeat) const; - bool HasBpmChanges() const + [[nodiscard]] float GetElapsedTimeFromBeatNoOffset(float fBeat) const; + [[nodiscard]] float GetDisplayedBeat(float fBeat) const; + + [[nodiscard]] bool HasBpmChanges() const { return GetTimingSegments(SEGMENT_BPM).size() > 1; } - bool HasStops() const { return !GetTimingSegments(SEGMENT_STOP).empty(); } - bool HasDelays() const { return !GetTimingSegments(SEGMENT_DELAY).empty(); } - bool HasWarps() const { return !GetTimingSegments(SEGMENT_WARP).empty(); } - bool HasFakes() const { return !GetTimingSegments(SEGMENT_FAKE).empty(); } - bool HasSpeedChanges() const; - bool HasScrollChanges() const; + [[nodiscard]] bool HasStops() const + { + return !GetTimingSegments(SEGMENT_STOP).empty(); + } + [[nodiscard]] bool HasDelays() const + { + return !GetTimingSegments(SEGMENT_DELAY).empty(); + } + [[nodiscard]] bool HasWarps() const + { + return !GetTimingSegments(SEGMENT_WARP).empty(); + } + [[nodiscard]] bool HasFakes() const + { + return !GetTimingSegments(SEGMENT_FAKE).empty(); + } + + [[nodiscard]] bool HasSpeedChanges() const; + [[nodiscard]] bool HasScrollChanges() const; /** * @brief Compare two sets of timing data to see if they are equal. * @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) { - const vector& us = m_avpTimingSegments[tst]; - const vector& them = other.m_avpTimingSegments[tst]; + const std::vector& us = m_avpTimingSegments[tst]; + const std::vector& them = + other.m_avpTimingSegments[tst]; - // optimization: check vector sizes before contents + // optimization: check std::vector sizes before contents if (us.size() != them.size()) return false; @@ -601,7 +641,10 @@ class TimingData * @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, @@ -612,11 +655,12 @@ class TimingData void SortSegments(TimingSegmentType tst); - const vector& GetTimingSegments(TimingSegmentType tst) const + [[nodiscard]] const std::vector& GetTimingSegments( + TimingSegmentType tst) const { return const_cast(this)->GetTimingSegments(tst); } - vector& GetTimingSegments(TimingSegmentType tst) + std::vector& GetTimingSegments(TimingSegmentType tst) { return m_avpTimingSegments[tst]; } @@ -643,28 +687,32 @@ class TimingData float m_fBeat0OffsetInSeconds; // XXX: this breaks encapsulation. get rid of it ASAP - vector ToVectorString(TimingSegmentType tst, - int dec = 6) const; + [[nodiscard]] std::vector ToVectorString(TimingSegmentType tst, + int dec = 6) const; /* Wow it's almost like this should have been done a decade ago. Essentially what's happening here is the results of getelapsedtimeat(row) - are pre-calculated and stored in a vector that can be simply subset rather - than values being recalculated millions of times per file. This only applies - however to files for which there can be made an assumption of sequential - execution I don't actually know for sure if any of negative bpms/stops/warps - do this, or if mod maps have the power to fundamentally change timing data. - If they don't then I suppose all of these checks aren't needed at all :/. - Not my responsibility to investigate, though. - Mina.*/ - - vector ElapsedTimesAtAllRows; - vector ElapsedTimesAtNonEmptyRows; - const vector& BuildAndGetEtaner(const vector& nerv); - const vector& BuildAndGetEtar(int lastrow); - void SetElapsedTimesAtAllRows(vector& etar) + are pre-calculated and stored in a std::vector that can be simply subset + rather than values being recalculated millions of times per file. This only + applies however to files for which there can be made an assumption of + sequential execution I don't actually know for sure if any of negative + bpms/stops/warps do this, or if mod maps have the power to fundamentally + change timing data. If they don't then I suppose all of these checks aren't + needed at all :/. Not my responsibility to investigate, though. - Mina.*/ + + std::vector ElapsedTimesAtAllRows; + std::vector ElapsedTimesAtNonEmptyRows; + const std::vector& BuildAndGetEtaner(const std::vector& nerv); + const std::vector& BuildAndGetEtar(int lastrow); + void SetElapsedTimesAtAllRows(std::vector& etar) { ElapsedTimesAtAllRows = etar; } - vector GetElapsedTimesAtAllRows() { return ElapsedTimesAtAllRows; } + + [[nodiscard]] std::vector GetElapsedTimesAtAllRows() const + { + return ElapsedTimesAtAllRows; + } void UnsetElapsedTimesAtAllRows() { ElapsedTimesAtAllRows.clear(); @@ -675,18 +723,24 @@ class TimingData ElapsedTimesAtNonEmptyRows.clear(); ElapsedTimesAtNonEmptyRows.shrink_to_fit(); } - float WhereUAtBro(float beat) const; + + [[nodiscard]] float WhereUAtBro(float beat) const; float WhereUAtBro(float beat); - float WhereUAtBroNoOffset(float beat) const; + [[nodiscard]] float WhereUAtBroNoOffset(float beat) const; float WhereUAtBroNoOffset(float beat); float WhereUAtBro(int row); - vector ConvertReplayNoteRowsToTimestamps(const vector& nrv, - float rate); + std::vector ConvertReplayNoteRowsToTimestamps( + const std::vector& nrv, + float rate); bool ValidSequentialAssumption = true; void InvalidateSequentialAssmption() { ValidSequentialAssumption = false; } - bool IsSequentialAssumptionValid() { return ValidSequentialAssumption; } + + [[nodiscard]] bool IsSequentialAssumptionValid() const + { + return ValidSequentialAssumption; + } void NegStopAndBPMCheck() { @@ -695,11 +749,11 @@ class TimingData return; } - vector& bpms = m_avpTimingSegments[SEGMENT_BPM]; - vector& stops = m_avpTimingSegments[SEGMENT_STOP]; + std::vector& bpms = m_avpTimingSegments[SEGMENT_BPM]; + std::vector& stops = m_avpTimingSegments[SEGMENT_STOP]; - for (size_t i = 0, l = bpms.size(); i < l; ++i) { - BPMSegment* bpm = ToBPM(bpms[i]); + for (auto& i : bpms) { + BPMSegment* bpm = ToBPM(i); if (0 > bpm->GetBPM()) { LOG->Warn("Sequential Assumption Invalidated."); ValidSequentialAssumption = false; @@ -707,8 +761,8 @@ class TimingData } } - for (size_t i = 0, l = stops.size(); i < l; ++i) { - StopSegment* s = ToStop(stops[i]); + for (auto& stop : stops) { + StopSegment* s = ToStop(stop); if (0 > s->GetPause()) { LOG->Warn("Sequential Assumption Invalidated."); ValidSequentialAssumption = false; @@ -723,7 +777,7 @@ class TimingData void AddSegment(const TimingSegment* seg); // All of the following vectors must be sorted before gameplay. - vector m_avpTimingSegments[NUM_TimingSegmentType]; + std::vector m_avpTimingSegments[NUM_TimingSegmentType]; }; #undef COMPARE diff --git a/src/Etterna/Models/Misc/TimingSegments.h b/src/Etterna/Models/Misc/TimingSegments.h index 196b80cd37..205798eb77 100644 --- a/src/Etterna/Models/Misc/TimingSegments.h +++ b/src/Etterna/Models/Misc/TimingSegments.h @@ -51,17 +51,19 @@ const int ROW_INVALID = -1; */ struct TimingSegment { - virtual TimingSegmentType GetType() const + [[nodiscard]] virtual TimingSegmentType GetType() const { return TimingSegmentType_Invalid; } - virtual SegmentEffectType GetEffectType() const + + [[nodiscard]] virtual SegmentEffectType GetEffectType() const { return SegmentEffectType_Invalid; } - virtual TimingSegment* Copy() const = 0; - virtual bool IsNotable() const = 0; + [[nodiscard]] virtual TimingSegment* Copy() const = 0; + + [[nodiscard]] virtual bool IsNotable() const = 0; virtual void DebugPrint() const; // don't allow base TimingSegments to be instantiated directly @@ -92,18 +94,21 @@ struct TimingSegment */ virtual void Scale(int start, int length, int newLength); - int GetRow() const { return m_iStartRow; } + [[nodiscard]] int GetRow() const { return m_iStartRow; } void SetRow(int iRow) { m_iStartRow = iRow; } - float GetBeat() const { return NoteRowToBeat(m_iStartRow); } + [[nodiscard]] float GetBeat() const { return NoteRowToBeat(m_iStartRow); } void SetBeat(float fBeat) { SetRow(BeatToNoteRow(fBeat)); } - virtual std::string ToString(int /* dec */) const + [[nodiscard]] virtual std::string ToString(int /* dec */) const { return FloatToString(GetBeat()); } - virtual vector GetValues() const { return vector(0); } + [[nodiscard]] virtual std::vector GetValues() const + { + return std::vector(0); + } bool operator<(const TimingSegment& other) const { @@ -140,15 +145,22 @@ struct TimingSegment * These were inspired by the Pump It Up series. */ struct FakeSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_FAKE; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_FAKE; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Range; } - TimingSegment* Copy() const override { return new FakeSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new FakeSegment(*this); + } - bool IsNotable() const override { return m_iLengthRows > 0; } + [[nodiscard]] bool IsNotable() const override { return m_iLengthRows > 0; } void DebugPrint() const override; FakeSegment() @@ -175,19 +187,23 @@ struct FakeSegment : public TimingSegment { } - int GetLengthRows() const { return m_iLengthRows; } - float GetLengthBeats() const { return ToBeat(m_iLengthRows); } - float GetLength() const { return GetLengthBeats(); } // compatibility + [[nodiscard]] int GetLengthRows() const { return m_iLengthRows; } + [[nodiscard]] float GetLengthBeats() const { return ToBeat(m_iLengthRows); } + [[nodiscard]] float GetLength() const + { + return GetLengthBeats(); + } // compatibility void SetLength(int iRows) { m_iLengthRows = ToNoteRow(iRows); } void SetLength(float fBeats) { m_iLengthRows = ToNoteRow(fBeats); } void Scale(int start, int length, int newLength) override; - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetLength()); + return std::vector(1, GetLength()); } bool operator==(const FakeSegment& other) const @@ -218,14 +234,22 @@ struct FakeSegment : public TimingSegment * (Technically they're both rows though.) */ struct WarpSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_WARP; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_WARP; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Range; } - TimingSegment* Copy() const override { return new WarpSegment(*this); } - bool IsNotable() const override { return m_iLengthRows > 0; } + [[nodiscard]] TimingSegment* Copy() const override + { + return new WarpSegment(*this); + } + + [[nodiscard]] bool IsNotable() const override { return m_iLengthRows > 0; } void DebugPrint() const override; WarpSegment() @@ -252,18 +276,22 @@ struct WarpSegment : public TimingSegment { } - int GetLengthRows() const { return m_iLengthRows; } - float GetLengthBeats() const { return ToBeat(m_iLengthRows); } - float GetLength() const { return GetLengthBeats(); } // compatibility + [[nodiscard]] int GetLengthRows() const { return m_iLengthRows; } + [[nodiscard]] float GetLengthBeats() const { return ToBeat(m_iLengthRows); } + [[nodiscard]] float GetLength() const + { + return GetLengthBeats(); + } // compatibility void SetLength(int iRows) { m_iLengthRows = ToNoteRow(iRows); } void SetLength(float fBeats) { m_iLengthRows = ToNoteRow(fBeats); } void Scale(int start, int length, int newLength) override; - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetLength()); + return std::vector(1, GetLength()); } bool operator==(const WarpSegment& other) const @@ -299,19 +327,26 @@ struct TickcountSegment : public TimingSegment /** @brief The default amount of ticks per beat. */ static const unsigned DEFAULT_TICK_COUNT = 4; - TimingSegmentType GetType() const override { return SEGMENT_TICKCOUNT; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_TICKCOUNT; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new TickcountSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new TickcountSegment(*this); + } TickcountSegment(int iStartRow = ROW_INVALID, int iTicks = DEFAULT_TICK_COUNT) @@ -326,13 +361,14 @@ struct TickcountSegment : public TimingSegment { } - int GetTicks() const { return m_iTicksPerBeat; } + [[nodiscard]] int GetTicks() const { return m_iTicksPerBeat; } void SetTicks(int iTicks) { m_iTicksPerBeat = iTicks; } - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetTicks() * 1.f); + return std::vector(1, GetTicks() * 1.f); } bool operator==(const TickcountSegment& other) const @@ -362,19 +398,26 @@ struct TickcountSegment : public TimingSegment */ struct ComboSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_COMBO; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_COMBO; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new ComboSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new ComboSegment(*this); + } ComboSegment(int iStartRow = ROW_INVALID, int iCombo = 1, @@ -392,14 +435,14 @@ struct ComboSegment : public TimingSegment { } - int GetCombo() const { return m_iCombo; } - int GetMissCombo() const { return m_iMissCombo; } + [[nodiscard]] int GetCombo() const { return m_iCombo; } + [[nodiscard]] int GetMissCombo() const { return m_iMissCombo; } void SetCombo(int iCombo) { m_iCombo = iCombo; } void SetMissCombo(int iCombo) { m_iMissCombo = iCombo; } - std::string ToString(int dec) const override; - vector GetValues() const override; + [[nodiscard]] std::string ToString(int dec) const override; + [[nodiscard]] std::vector GetValues() const override; bool operator==(const ComboSegment& other) const { @@ -432,19 +475,26 @@ struct ComboSegment : public TimingSegment */ struct LabelSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_LABEL; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_LABEL; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new LabelSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new LabelSegment(*this); + } LabelSegment(int iStartRow = ROW_INVALID, const std::string& sLabel = std::string()) @@ -459,10 +509,10 @@ struct LabelSegment : public TimingSegment { } - const std::string& GetLabel() const { return m_sLabel; } + [[nodiscard]] const std::string& GetLabel() const { return m_sLabel; } void SetLabel(const std::string& sLabel) { m_sLabel.assign(sLabel); } - std::string ToString(int dec) const override; + [[nodiscard]] std::string ToString(int dec) const override; // Use the default definition for GetValues because the value for a // LabelSegment is not a float or set of floats. TimingSegmentSetToLuaTable // in TimingData.cpp has a special case for labels to handle this. @@ -491,19 +541,26 @@ struct LabelSegment : public TimingSegment */ struct BPMSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_BPM; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_BPM; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new BPMSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new BPMSegment(*this); + } // note that this takes a BPM, not a BPS (compatibility) BPMSegment(int iStartRow = ROW_INVALID, float fBPM = 0.0f) @@ -518,16 +575,17 @@ struct BPMSegment : public TimingSegment { } - float GetBPS() const { return m_fBPS; } - float GetBPM() const { return m_fBPS * 60.0f; } + [[nodiscard]] float GetBPS() const { return m_fBPS; } + [[nodiscard]] float GetBPM() const { return m_fBPS * 60.0f; } void SetBPS(float fBPS) { m_fBPS = fBPS; } void SetBPM(float fBPM) { m_fBPS = fBPM / 60.0f; } - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetBPM()); + return std::vector(1, GetBPM()); } bool operator==(const BPMSegment& other) const @@ -558,19 +616,23 @@ struct BPMSegment : public TimingSegment * (denominator here) is the note value representing one beat. */ struct TimeSignatureSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_TIME_SIG; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_TIME_SIG; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override + [[nodiscard]] TimingSegment* Copy() const override { return new TimeSignatureSegment(*this); } @@ -591,10 +653,10 @@ struct TimeSignatureSegment : public TimingSegment { } - int GetNum() const { return m_iNumerator; } + [[nodiscard]] int GetNum() const { return m_iNumerator; } void SetNum(int num) { m_iNumerator = num; } - int GetDen() const { return m_iDenominator; } + [[nodiscard]] int GetDen() const { return m_iDenominator; } void SetDen(int den) { m_iDenominator = den; } void Set(int num, int den) @@ -603,8 +665,8 @@ struct TimeSignatureSegment : public TimingSegment m_iDenominator = den; } - std::string ToString(int dec) const override; - vector GetValues() const override; + [[nodiscard]] std::string ToString(int dec) const override; + [[nodiscard]] std::vector GetValues() const override; /** * @brief Retrieve the number of note rows per measure within the @@ -618,7 +680,7 @@ struct TimeSignatureSegment : public TimingSegment * beat. Multiplying by m_iNumerator gives rows per measure. * @returns the number of note rows per measure. */ - int GetNoteRowsPerMeasure() const + [[nodiscard]] int GetNoteRowsPerMeasure() const { return BeatToNoteRow(1) * 4 * m_iNumerator / m_iDenominator; } @@ -654,19 +716,26 @@ struct TimeSignatureSegment : public TimingSegment * These were inspired by the Pump It Up series. */ struct SpeedSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_SPEED; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_SPEED; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new SpeedSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new SpeedSegment(*this); + } /** @brief The type of unit used for segment scaling. */ enum BaseUnit @@ -694,19 +763,19 @@ struct SpeedSegment : public TimingSegment { } - float GetRatio() const { return m_fRatio; } + [[nodiscard]] float GetRatio() const { return m_fRatio; } void SetRatio(float fRatio) { m_fRatio = fRatio; } - float GetDelay() const { return m_fDelay; } + [[nodiscard]] float GetDelay() const { return m_fDelay; } void SetDelay(float fDelay) { m_fDelay = fDelay; } - BaseUnit GetUnit() const { return m_Unit; } + [[nodiscard]] BaseUnit GetUnit() const { return m_Unit; } void SetUnit(BaseUnit unit) { m_Unit = unit; } void Scale(int start, int length, int newLength) override; - std::string ToString(int dec) const override; - vector GetValues() const override; + [[nodiscard]] std::string ToString(int dec) const override; + [[nodiscard]] std::vector GetValues() const override; bool operator==(const SpeedSegment& other) const { @@ -747,19 +816,26 @@ struct SpeedSegment : public TimingSegment * These were inspired by the Pump It Up series. */ struct ScrollSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_SCROLL; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_SCROLL; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Indefinite; } - bool IsNotable() const override + [[nodiscard]] bool IsNotable() const override { return true; } // indefinite segments are always true void DebugPrint() const override; - TimingSegment* Copy() const override { return new ScrollSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new ScrollSegment(*this); + } ScrollSegment(int iStartRow = ROW_INVALID, float fRatio = 1.0f) : TimingSegment(iStartRow) @@ -773,13 +849,14 @@ struct ScrollSegment : public TimingSegment { } - float GetRatio() const { return m_fRatio; } + [[nodiscard]] float GetRatio() const { return m_fRatio; } void SetRatio(float fRatio) { m_fRatio = fRatio; } - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetRatio()); + return std::vector(1, GetRatio()); } bool operator==(const ScrollSegment& other) const @@ -806,16 +883,23 @@ struct ScrollSegment : public TimingSegment */ struct StopSegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_STOP; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_STOP; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Row; } - bool IsNotable() const override { return m_fSeconds > 0; } + [[nodiscard]] bool IsNotable() const override { return m_fSeconds > 0; } void DebugPrint() const override; - TimingSegment* Copy() const override { return new StopSegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new StopSegment(*this); + } StopSegment(int iStartRow = ROW_INVALID, float fSeconds = 0.0f) : TimingSegment(iStartRow) @@ -829,13 +913,14 @@ struct StopSegment : public TimingSegment { } - float GetPause() const { return m_fSeconds; } + [[nodiscard]] float GetPause() const { return m_fSeconds; } void SetPause(float fSeconds) { m_fSeconds = fSeconds; } - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetPause()); + return std::vector(1, GetPause()); } bool operator==(const StopSegment& other) const @@ -862,16 +947,23 @@ struct StopSegment : public TimingSegment */ struct DelaySegment : public TimingSegment { - TimingSegmentType GetType() const override { return SEGMENT_DELAY; } - SegmentEffectType GetEffectType() const override + [[nodiscard]] TimingSegmentType GetType() const override + { + return SEGMENT_DELAY; + } + + [[nodiscard]] SegmentEffectType GetEffectType() const override { return SegmentEffectType_Row; } - bool IsNotable() const override { return m_fSeconds > 0; } + [[nodiscard]] bool IsNotable() const override { return m_fSeconds > 0; } void DebugPrint() const override; - TimingSegment* Copy() const override { return new DelaySegment(*this); } + [[nodiscard]] TimingSegment* Copy() const override + { + return new DelaySegment(*this); + } DelaySegment(int iStartRow = ROW_INVALID, float fSeconds = 0) : TimingSegment(iStartRow) @@ -885,13 +977,14 @@ struct DelaySegment : public TimingSegment { } - float GetPause() const { return m_fSeconds; } + [[nodiscard]] float GetPause() const { return m_fSeconds; } void SetPause(float fSeconds) { m_fSeconds = fSeconds; } - std::string ToString(int dec) const override; - vector GetValues() const override + [[nodiscard]] std::string ToString(int dec) const override; + + [[nodiscard]] std::vector GetValues() const override { - return vector(1, GetPause()); + return std::vector(1, GetPause()); } bool operator==(const DelaySegment& other) const diff --git a/src/Etterna/Models/Misc/TitleSubstitution.cpp b/src/Etterna/Models/Misc/TitleSubstitution.cpp index 090d03cae6..a583aaff71 100644 --- a/src/Etterna/Models/Misc/TitleSubstitution.cpp +++ b/src/Etterna/Models/Misc/TitleSubstitution.cpp @@ -175,7 +175,7 @@ TitleSubst::Load(const std::string& filename, const std::string& section) } XNode* pGroup = xml.GetChild(section); - if (pGroup == NULL) + if (pGroup == nullptr) return; FOREACH_CONST_Child(pGroup, child) { @@ -190,6 +190,6 @@ TitleSubst::Load(const std::string& filename, const std::string& section) TitleSubst::~TitleSubst() { - for (unsigned i = 0; i < ttab.size(); ++i) - delete ttab[i]; + for (auto& i : ttab) + delete i; } diff --git a/src/Etterna/Models/Misc/XMLProfile.cpp b/src/Etterna/Models/Misc/XMLProfile.cpp index 7a24cf0672..8581c24e44 100644 --- a/src/Etterna/Models/Misc/XMLProfile.cpp +++ b/src/Etterna/Models/Misc/XMLProfile.cpp @@ -83,7 +83,7 @@ XMLProfile::LoadEttFromDir(string dir) int iError; unique_ptr pFile(FILEMAN->Open(fn, RageFile::READ, iError)); - if (pFile.get() == NULL) { + if (pFile.get() == nullptr) { LOG->Trace("Error opening %s: %s", fn.c_str(), strerror(iError)); return ProfileLoadResult_FailedTampered; } diff --git a/src/Etterna/Models/Songs/SongOptions.h b/src/Etterna/Models/Songs/SongOptions.h index 90440727a4..735dddc5d3 100644 --- a/src/Etterna/Models/Songs/SongOptions.h +++ b/src/Etterna/Models/Songs/SongOptions.h @@ -53,8 +53,8 @@ class SongOptions SongOptions() = default; void Init(); void Approach(const SongOptions& other, float fDeltaSeconds); - void GetMods(vector& AddTo) const; - void GetLocalizedMods(vector& AddTo) const; + void GetMods(std::vector& AddTo) const; + void GetLocalizedMods(std::vector& AddTo) const; std::string GetString() const; std::string GetLocalizedString() const; void FromString(const std::string& sOptions); diff --git a/src/Etterna/Models/StepsAndStyles/Style.h b/src/Etterna/Models/StepsAndStyles/Style.h index d28865bae2..dc95fc31c8 100644 --- a/src/Etterna/Models/StepsAndStyles/Style.h +++ b/src/Etterna/Models/StepsAndStyles/Style.h @@ -89,7 +89,7 @@ class Style void StyleInputToGameInput(int iCol, PlayerNumber pn, - vector& ret) const; + std::vector& ret) const; /** * @brief Retrieve the column based on the game input. * @param GameI the game input. diff --git a/src/Etterna/Singletons/GameState.h b/src/Etterna/Singletons/GameState.h index 3ca3cfc668..482cab1d05 100644 --- a/src/Etterna/Singletons/GameState.h +++ b/src/Etterna/Singletons/GameState.h @@ -155,7 +155,7 @@ class GameState /** * @brief Set the master player number. * @param p the master player number. */ - void SetMasterPlayerNumber(const PlayerNumber p); + void SetMasterPlayerNumber(PlayerNumber p); /** * @brief Retrieve the present timing data being processed. @@ -212,16 +212,16 @@ class GameState bool m_bLoadingNextSong; int GetLoadingCourseSongIndex() const; - std::string GetEtternaVersion() { return "0.70.1"; } + static std::string GetEtternaVersion() { return "0.70.1"; } /* is this the best place for this? it's not exactly a pref, and we * shouldn't be copying and pasting these values everywhere as needed j1-j4 * are now all 1.f to remove j1-3 without having to mess with expected array * sizes in other areas yes i know this is lazy */ - vector timingscales = { 1.00f, 1.00f, 1.00f, 1.00f, 0.84f, - 0.66f, 0.50f, 0.33f, 0.20f }; + std::vector timingscales = { 1.00f, 1.00f, 1.00f, 1.00f, 0.84f, + 0.66f, 0.50f, 0.33f, 0.20f }; bool isplaylistcourse = false; - bool IsPlaylistCourse() { return isplaylistcourse; } + bool IsPlaylistCourse() const { return isplaylistcourse; } bool CountNotesSeparately(); // State Info used during gameplay @@ -239,14 +239,14 @@ class GameState BroadcastOnChange m_bGameplayLeadIn; // if re-adding noteskin changes in courses, add functions and such here -aj - void GetAllUsedNoteSkins(vector& out) const; + void GetAllUsedNoteSkins(std::vector& out) const; static const float MUSIC_SECONDS_INVALID; void ResetMusicStatistics(); // Call this when it's time to play a new song. // Clears the values above. void SetPaused(bool p) { m_paused = p; } - bool GetPaused() { return m_paused; } + bool GetPaused() const { return m_paused; } void UpdateSongPosition(float fPositionSeconds, const TimingData& timing, const RageTimer& timestamp = RageZeroTimer); @@ -278,7 +278,6 @@ class GameState void ApplyPreferredModifiers(PlayerNumber pn, const std::string& sModifiers); void ApplyStageModifiers(PlayerNumber pn, const std::string& sModifiers); - void ResetOptions(); bool CurrentOptionsDisqualifyPlayer(PlayerNumber pn); bool PlayerIsUsingModifier(PlayerNumber pn, const std::string& sModifier); @@ -315,7 +314,7 @@ class GameState // Current mode of Gameplay BroadcastOnChange m_gameplayMode; - GameplayMode GetGameplayMode() { return m_gameplayMode; } + GameplayMode GetGameplayMode() const { return m_gameplayMode; } void TogglePracticeModeSafe(bool set); void TogglePracticeMode(bool set); bool IsPracticeMode(); @@ -328,7 +327,7 @@ class GameState void updateDiscordPresence(const std::string& largeImageText, const std::string& details, const std::string& state, - const int64_t endTime); + int64_t endTime); void updateDiscordPresenceMenu(const std::string& largeImageText); // Lua diff --git a/src/Etterna/Singletons/InputMapper.h b/src/Etterna/Singletons/InputMapper.h index a53bb88cb5..3ea3f161b1 100644 --- a/src/Etterna/Singletons/InputMapper.h +++ b/src/Etterna/Singletons/InputMapper.h @@ -22,7 +22,8 @@ struct AutoMappingEntry { } AutoMappingEntry() = default; - bool IsEmpty() const + + [[nodiscard]] bool IsEmpty() const { return m_deviceButton == DeviceButton_Invalid && m_gb == GameButton_Invalid; @@ -90,7 +91,6 @@ struct AutoMappings : m_sGame(s1) , m_sDriverRegex(s2) , m_sControllerName(s3) - , m_vMaps() { #define PUSH(im) \ if (!im.IsEmpty()) \ @@ -143,7 +143,7 @@ struct AutoMappings std::string m_sDriverRegex; // reported by InputHandler std::string m_sControllerName; // the product name of the controller - vector m_vMaps; + std::vector m_vMaps; }; class InputScheme @@ -161,15 +161,16 @@ class InputScheme GameButtonInfo m_GameButtonInfo[NUM_GameButton]; const AutoMappings* m_pAutoMappings; - GameButton ButtonNameToIndex(const std::string& sButtonName) const; - GameButton GameButtonToMenuButton(GameButton gb) const; + [[nodiscard]] GameButton ButtonNameToIndex( + const std::string& sButtonName) const; + [[nodiscard]] GameButton GameButtonToMenuButton(GameButton gb) const; void MenuButtonToGameInputs(GameButton MenuI, PlayerNumber pn, - vector& GameIout) const; + std::vector& GameIout) const; void MenuButtonToGameButtons(GameButton MenuI, - vector& aGameButtons) const; - const GameButtonInfo* GetGameButtonInfo(GameButton gb) const; - const char* GetGameButtonName(GameButton gb) const; + std::vector& aGameButtons) const; + [[nodiscard]] const GameButtonInfo* GetGameButtonInfo(GameButton gb) const; + [[nodiscard]] const char* GetGameButtonName(GameButton gb) const; }; /** @brief A special foreach loop to handle the various GameButtons. */ #define FOREACH_GameButtonInScheme(s, var) \ @@ -209,16 +210,16 @@ class InputMapper ~InputMapper(); void SetInputScheme(const InputScheme* pInputScheme); - const InputScheme* GetInputScheme() const; + [[nodiscard]] const InputScheme* GetInputScheme() const; void SetJoinControllers(PlayerNumber pn); void ReadMappingsFromDisk(); void SaveMappingsToDisk(); void ResetMappingsToDefault(); void CheckButtonAndAddToReason(GameButton menu, - vector& full_reason, + std::vector& full_reason, std::string const& sub_reason); - void SanityCheckMappings(vector& reason); + void SanityCheckMappings(std::vector& reason); void ClearAllMappings(); @@ -232,7 +233,7 @@ class InputMapper void AutoMapJoysticksForCurrentGame(); bool CheckForChangedInputDevicesAndRemap(std::string& sMessageOut); - bool IsMapped(const DeviceInput& DeviceI) const; + [[nodiscard]] bool IsMapped(const DeviceInput& DeviceI) const; bool DeviceToGame(const DeviceInput& DeviceI, GameInput& GameI) const; // return true if there is a mapping from device to pad @@ -241,21 +242,22 @@ class InputMapper DeviceInput& DeviceI) const; // return true if there is a mapping from pad to device - GameButton GameButtonToMenuButton(GameButton gb) const; + [[nodiscard]] GameButton GameButtonToMenuButton(GameButton gb) const; void MenuToGame(GameButton MenuI, PlayerNumber pn, - vector& GameIout) const; - PlayerNumber ControllerToPlayerNumber(GameController controller) const; + std::vector& GameIout) const; + [[nodiscard]] PlayerNumber ControllerToPlayerNumber( + GameController controller) const; - float GetSecsHeld(const GameInput& GameI, - MultiPlayer mp = MultiPlayer_Invalid) const; - float GetSecsHeld(GameButton MenuI, PlayerNumber pn) const; + [[nodiscard]] float GetSecsHeld(const GameInput& GameI, + MultiPlayer mp = MultiPlayer_Invalid) const; + [[nodiscard]] float GetSecsHeld(GameButton MenuI, PlayerNumber pn) const; bool IsBeingPressed(const GameInput& GameI, MultiPlayer mp = MultiPlayer_Invalid, const DeviceInputList* pButtonState = nullptr) const; - bool IsBeingPressed(GameButton MenuI, PlayerNumber pn) const; - bool IsBeingPressed(const vector& GameI, + [[nodiscard]] bool IsBeingPressed(GameButton MenuI, PlayerNumber pn) const; + bool IsBeingPressed(const std::vector& GameI, MultiPlayer mp = MultiPlayer_Invalid, const DeviceInputList* pButtonState = nullptr) const; @@ -265,14 +267,14 @@ class InputMapper void RepeatStopKey(const GameInput& GameI); void RepeatStopKey(GameButton MenuI, PlayerNumber pn); - float GetLevel(const GameInput& GameI) const; - float GetLevel(GameButton MenuI, PlayerNumber pn) const; + [[nodiscard]] float GetLevel(const GameInput& GameI) const; + [[nodiscard]] float GetLevel(GameButton MenuI, PlayerNumber pn) const; static InputDevice MultiPlayerToInputDevice(MultiPlayer mp); static MultiPlayer InputDeviceToMultiPlayer(InputDevice id); void Unmap(InputDevice device); - void ApplyMapping(const vector& vMmaps, + void ApplyMapping(const std::vector& vMmaps, GameController gc, InputDevice id); diff --git a/src/Etterna/Singletons/InputQueue.h b/src/Etterna/Singletons/InputQueue.h index a9fbcd3824..4f0b8174a0 100644 --- a/src/Etterna/Singletons/InputQueue.h +++ b/src/Etterna/Singletons/InputQueue.h @@ -3,6 +3,7 @@ #include "Etterna/Models/Misc/GameInput.h" #include "InputFilter.h" + #include class InputEventPlus; @@ -20,46 +21,41 @@ class InputQueue GameButton button, const std::chrono::steady_clock::time_point& OldestTimeAllowed, InputEventPlus* pIEP = nullptr); - const vector& GetQueue(GameController c) const + + [[nodiscard]] const std::vector& GetQueue( + GameController c) const { return m_aQueue[c]; } void ClearQueue(GameController c); protected: - vector m_aQueue[NUM_GameController]; + std::vector m_aQueue[NUM_GameController]; }; struct InputQueueCode { - public: bool Load(std::string sButtonsNames); - bool EnteredCode(GameController controller) const; + [[nodiscard]] bool EnteredCode(GameController controller) const; - InputQueueCode() - : m_aPresses() - { - } + InputQueueCode() {} private: struct ButtonPress { ButtonPress() - : m_aButtonsToHold() - , m_aButtonsToNotHold() - , m_aButtonsToPress() { memset(m_InputTypes, 0, sizeof(m_InputTypes)); m_InputTypes[IET_FIRST_PRESS] = true; } - vector m_aButtonsToHold; - vector m_aButtonsToNotHold; - vector m_aButtonsToPress; + std::vector m_aButtonsToHold; + std::vector m_aButtonsToNotHold; + std::vector m_aButtonsToPress; - bool m_InputTypes[NUM_InputEventType]; + bool m_InputTypes[NUM_InputEventType]{}; bool m_bAllowIntermediatePresses{ false }; }; - vector m_aPresses; + std::vector m_aPresses; float m_fMaxSecondsBack = 0.f; }; diff --git a/src/Etterna/Singletons/MessageManager.h b/src/Etterna/Singletons/MessageManager.h index da516ec20b..a5cfde1855 100644 --- a/src/Etterna/Singletons/MessageManager.h +++ b/src/Etterna/Singletons/MessageManager.h @@ -127,7 +127,7 @@ struct Message } template - void SetParam(const std::string& sName, const vector& val) + void SetParam(const std::string& sName, const std::vector& val) { Lua* L = LUA->Get(); LuaHelpers::CreateTableFromArray(val, L); @@ -171,10 +171,7 @@ class IMessageSubscriber class MessageSubscriber : public IMessageSubscriber { public: - MessageSubscriber() - : m_vsSubscribedTo() - { - } + MessageSubscriber() {} MessageSubscriber(const MessageSubscriber& cpy); MessageSubscriber& operator=(const MessageSubscriber& cpy); @@ -189,7 +186,7 @@ class MessageSubscriber : public IMessageSubscriber void UnsubscribeAll(); private: - vector m_vsSubscribedTo; + std::vector m_vsSubscribedTo; }; /** @brief Deliver messages to any part of the program as needed. */ @@ -210,8 +207,9 @@ class MessageManager void Broadcast(MessageID m) const; bool IsSubscribedToMessage(IMessageSubscriber* pSubscriber, const std::string& sMessage) const; - inline bool IsSubscribedToMessage(IMessageSubscriber* pSubscriber, - MessageID message) const + + bool IsSubscribedToMessage(IMessageSubscriber* pSubscriber, + MessageID message) const { return IsSubscribedToMessage(pSubscriber, MessageIDToString(message)); } @@ -265,7 +263,7 @@ class BroadcastOnChange1D { private: using MyType = BroadcastOnChange; - vector val; + std::vector val; public: explicit BroadcastOnChange1D(MessageID m) @@ -310,7 +308,7 @@ class BroadcastOnChangePtr1D { private: using MyType = BroadcastOnChangePtr; - vector val; + std::vector val; public: explicit BroadcastOnChangePtr1D(MessageID m) diff --git a/src/Etterna/Singletons/NoteSkinManager.h b/src/Etterna/Singletons/NoteSkinManager.h index 07534e215f..1fc1343eb8 100644 --- a/src/Etterna/Singletons/NoteSkinManager.h +++ b/src/Etterna/Singletons/NoteSkinManager.h @@ -5,6 +5,8 @@ #include "Etterna/Models/Misc/GameInput.h" #include "Etterna/Models/Misc/PlayerNumber.h" +#include + struct Game; struct NoteSkinData; @@ -16,11 +18,11 @@ class NoteSkinManager ~NoteSkinManager(); void RefreshNoteSkinData(const Game* game); - void GetNoteSkinNames(const Game* game, vector& AddTo); - void GetNoteSkinNames( - vector& AddTo); // looks up current const Game* in GAMESTATE + void GetNoteSkinNames(const Game* game, std::vector& AddTo); + void GetNoteSkinNames(std::vector& + AddTo); // looks up current const Game* in GAMESTATE bool NoteSkinNameInList(const std::string& name, - const vector& name_list); + const std::vector& name_list); bool DoesNoteSkinExist( const std::string& sNoteSkin); // looks up current const Game* in GAMESTATE @@ -34,10 +36,10 @@ class NoteSkinManager { m_sCurrentNoteSkin = sNoteSkin; } - const std::string& GetCurrentNoteSkin() { return m_sCurrentNoteSkin; } + const std::string& GetCurrentNoteSkin() const { return m_sCurrentNoteSkin; } - void SetLastSeenColor(std::string Color) { LastColor = Color; } - const std::string& GetLastSeenColor() { return LastColor; } + void SetLastSeenColor(std::string Color) { LastColor = std::move(Color); } + const std::string& GetLastSeenColor() const { return LastColor; } void SetPlayerNumber(PlayerNumber pn) { m_PlayerNumber = pn; } void SetGameController(GameController gc) { m_GameController = gc; } @@ -72,7 +74,7 @@ class NoteSkinManager std::string GetPathFromDirAndFile(const std::string& sDir, const std::string& sFileName); void GetAllNoteSkinNamesForGame(const Game* pGame, - vector& AddTo); + std::vector& AddTo); bool LoadNoteSkinData(const std::string& sNoteSkinName, NoteSkinData& data_out); @@ -93,9 +95,8 @@ extern NoteSkinManager* class LockNoteSkin { public: - LockNoteSkin(std::string sNoteSkin, PlayerNumber pn) + LockNoteSkin(const std::string& sNoteSkin, PlayerNumber pn) { - ASSERT(NOTESKIN->GetCurrentNoteSkin().empty()); NOTESKIN->SetCurrentNoteSkin(sNoteSkin); } ~LockNoteSkin() { NOTESKIN->SetCurrentNoteSkin(""); } diff --git a/src/Etterna/Singletons/PrefsManager.cpp b/src/Etterna/Singletons/PrefsManager.cpp index 5a711c6d00..69e812ffa5 100644 --- a/src/Etterna/Singletons/PrefsManager.cpp +++ b/src/Etterna/Singletons/PrefsManager.cpp @@ -1,5 +1,4 @@ #include "Etterna/Globals/global.h" -#include "Etterna/Models/Misc/Foreach.h" #include "Etterna/FileTypes/IniFile.h" #include "LuaManager.h" #include "Etterna/Models/Misc/Preference.h" @@ -290,7 +289,7 @@ PrefsManager::RestoreGamePrefs() // load prefs GamePrefs gp; - map::const_iterator iter = + const map::const_iterator iter = m_mapGameNameToGamePrefs.find(m_sCurrentGame); if (iter != m_mapGameNameToGamePrefs.end()) gp = iter->second; @@ -368,16 +367,6 @@ PrefsManager::ReadPrefsFromIni(const IniFile& ini, } s_iDepth--; - /* - IPreference *pPref = PREFSMAN->GetPreferenceByName( *sName ); - if( pPref == NULL ) - { - LOG->Warn( "Unknown preference in [%s]: %s", sClassName.c_str(), - sName->c_str() ); continue; - } - pPref->FromString( sVal ); - */ - const XNode* pChild = ini.GetChild(sSection); if (pChild != nullptr) IPreference::ReadAllPrefsFromNode(pChild, bIsStatic); @@ -450,15 +439,14 @@ PrefsManager::SavePrefsToIni(IniFile& ini) pNode = ini.AppendChild("Options"); IPreference::SavePrefsToNode(pNode); - FOREACHM_CONST(std::string, GamePrefs, m_mapGameNameToGamePrefs, iter) - { - std::string sSection = "Game-" + std::string(iter->first); + for (auto& iter : m_mapGameNameToGamePrefs) { + std::string sSection = "Game-" + std::string(iter.first); // todo: write more values here? -aj - ini.SetValue(sSection, "Announcer", iter->second.m_sAnnouncer); - ini.SetValue(sSection, "Theme", iter->second.m_sTheme); + ini.SetValue(sSection, "Announcer", iter.second.m_sAnnouncer); + ini.SetValue(sSection, "Theme", iter.second.m_sTheme); ini.SetValue( - sSection, "DefaultModifiers", iter->second.m_sDefaultModifiers); + sSection, "DefaultModifiers", iter.second.m_sDefaultModifiers); } } @@ -486,7 +474,7 @@ class LunaPrefsManager : public Luna public: static int GetPreference(T* p, lua_State* L) { - std::string sName = SArg(1); + const std::string sName = SArg(1); IPreference* pPref = IPreference::GetPreferenceByName(sName); if (pPref == nullptr) { LuaHelpers::ReportScriptErrorFmt( @@ -500,7 +488,7 @@ class LunaPrefsManager : public Luna } static int SetPreference(T* p, lua_State* L) { - std::string sName = SArg(1); + const std::string sName = SArg(1); IPreference* pPref = IPreference::GetPreferenceByName(sName); if (pPref == nullptr) { @@ -515,7 +503,7 @@ class LunaPrefsManager : public Luna } static int SetPreferenceToDefault(T* p, lua_State* L) { - std::string sName = SArg(1); + const std::string sName = SArg(1); IPreference* pPref = IPreference::GetPreferenceByName(sName); if (pPref == nullptr) { @@ -533,7 +521,7 @@ class LunaPrefsManager : public Luna } static int PreferenceExists(T* p, lua_State* L) { - std::string sName = SArg(1); + const std::string sName = SArg(1); IPreference* pPref = IPreference::GetPreferenceByName(sName); if (pPref == nullptr) { diff --git a/src/Etterna/Singletons/PrefsManager.h b/src/Etterna/Singletons/PrefsManager.h index fecc03bdc1..2ae10c6d06 100644 --- a/src/Etterna/Singletons/PrefsManager.h +++ b/src/Etterna/Singletons/PrefsManager.h @@ -122,7 +122,7 @@ class PrefsManager std::string m_sTheme; std::string m_sDefaultModifiers; }; - map m_mapGameNameToGamePrefs; + std::map m_mapGameNameToGamePrefs; public: Preference m_bWindowed; @@ -204,7 +204,7 @@ class PrefsManager Preference m_fPadStickSeconds; // Useful for non 4:3 displays and resolutions < 640x480 where texels don't - // map directly to pixels. + // std::map directly to pixels. Preference m_bForceMipMaps; Preference m_bTrilinearFiltering; // has no effect without mipmaps on Preference m_bAnisotropicFiltering; // has no effect without mipmaps diff --git a/src/Etterna/Singletons/ScoreManager.h b/src/Etterna/Singletons/ScoreManager.h index 423d673c32..883f73d02b 100644 --- a/src/Etterna/Singletons/ScoreManager.h +++ b/src/Etterna/Singletons/ScoreManager.h @@ -90,12 +90,12 @@ struct ScoresForChart to approach things in the reverse -mina */ map> ScoresByRate; - [[nodiscard]] static inline auto RateToKey(float rate) -> int + [[nodiscard]] static auto RateToKey(float rate) -> int { return lround(rate * 10000.f); } - [[nodiscard]] static inline auto KeyToRate(int key) -> float + [[nodiscard]] static auto KeyToRate(int key) -> float { return static_cast(key) / 10000.f; } diff --git a/src/Etterna/Singletons/ThemeManager.h b/src/Etterna/Singletons/ThemeManager.h index 5cf9960f54..b6afca0449 100644 --- a/src/Etterna/Singletons/ThemeManager.h +++ b/src/Etterna/Singletons/ThemeManager.h @@ -3,6 +3,7 @@ #include "Etterna/Models/Lua/LuaReference.h" #include "RageUtil/Misc/RageTypes.h" + #include class IThemeMetric; @@ -34,15 +35,15 @@ class ThemeManager ThemeManager(); ~ThemeManager(); - void GetThemeNames(vector& AddTo); - void GetSelectableThemeNames(vector& AddTo); + void GetThemeNames(std::vector& AddTo); + void GetSelectableThemeNames(std::vector& AddTo); int GetNumSelectableThemes(); bool DoesThemeExist(const std::string& sThemeName); bool IsThemeSelectable(std::string const& name); bool IsThemeNameValid(std::string const& name); std::string GetThemeDisplayName(const std::string& sThemeName); std::string GetThemeAuthor(const std::string& sThemeName); - void GetLanguages(vector& AddTo); + void GetLanguages(std::vector& AddTo); bool DoesLanguageExist(const std::string& sLanguage); void SwitchThemeAndLanguage(const std::string& sThemeName, const std::string& sLanguage, @@ -62,7 +63,7 @@ class ThemeManager void ReloadMetrics(); void ReloadSubscribers(); void ClearSubscribers(); - void GetOptionNames(vector& AddTo); + void GetOptionNames(std::vector& AddTo); static void EvaluateString(std::string& sText); @@ -79,49 +80,54 @@ class ThemeManager const std::string& sElement, bool bOptional = false); std::string GetPath(ElementCategory category, - const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false); + const std::string& sMetricsGroup, + const std::string& sElement, + bool bOptional = false); std::string GetPathB(const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false) + const std::string& sElement, + bool bOptional = false) { return GetPath(EC_BGANIMATIONS, sMetricsGroup, sElement, bOptional); }; std::string GetPathF(const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false) + const std::string& sElement, + bool bOptional = false) { return GetPath(EC_FONTS, sMetricsGroup, sElement, bOptional); }; std::string GetPathG(const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false) + const std::string& sElement, + bool bOptional = false) { return GetPath(EC_GRAPHICS, sMetricsGroup, sElement, bOptional); }; std::string GetPathS(const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false) + const std::string& sElement, + bool bOptional = false) { return GetPath(EC_SOUNDS, sMetricsGroup, sElement, bOptional); }; std::string GetPathO(const std::string& sMetricsGroup, - const std::string& sElement, - bool bOptional = false) + const std::string& sElement, + bool bOptional = false) { return GetPath(EC_OTHER, sMetricsGroup, sElement, bOptional); }; void ClearThemePathCache(); - bool HasMetric(const std::string& sMetricsGroup, const std::string& sValueName); + bool HasMetric(const std::string& sMetricsGroup, + const std::string& sValueName); void PushMetric(Lua* L, const std::string& sMetricsGroup, const std::string& sValueName); - std::string GetMetric(const std::string& sMetricsGroup, const std::string& sValueName); - int GetMetricI(const std::string& sMetricsGroup, const std::string& sValueName); - float GetMetricF(const std::string& sMetricsGroup, const std::string& sValueName); - bool GetMetricB(const std::string& sMetricsGroup, const std::string& sValueName); + std::string GetMetric(const std::string& sMetricsGroup, + const std::string& sValueName); + int GetMetricI(const std::string& sMetricsGroup, + const std::string& sValueName); + float GetMetricF(const std::string& sMetricsGroup, + const std::string& sValueName); + bool GetMetricB(const std::string& sMetricsGroup, + const std::string& sValueName); RageColor GetMetricC(const std::string& sMetricsGroup, const std::string& sValueName); LuaReference GetMetricR(const std::string& sMetricsGroup, @@ -136,19 +142,21 @@ class ThemeManager LuaReference& valueOut); // Languages - bool HasString(const std::string& sMetricsGroup, const std::string& sValueName); - std::string GetString(const std::string& sMetricsGroup, const std::string& sValueName); + bool HasString(const std::string& sMetricsGroup, + const std::string& sValueName); + std::string GetString(const std::string& sMetricsGroup, + const std::string& sValueName); void GetString(const std::string& sMetricsGroup, const std::string& sValueName, std::string& valueOut) { valueOut = GetString(sMetricsGroup, sValueName); } - void FilterFileLanguages(vector& asElementPaths); + void FilterFileLanguages(std::vector& asElementPaths); void GetMetricsThatBeginWith(const std::string& sMetricsGroup, const std::string& sValueName, - set& vsValueNamesOut); + std::set& vsValueNamesOut); std::string GetMetricsGroupFallback(const std::string& sMetricsGroup); @@ -165,10 +173,11 @@ class ThemeManager void PushSelf(lua_State* L); protected: - void LoadThemeMetrics(const std::string& sThemeName, const std::string& sLanguage_); + void LoadThemeMetrics(const std::string& sThemeName, + const std::string& sLanguage_); std::string GetMetricRaw(const IniFile& ini, - const std::string& sMetricsGroup, - const std::string& sValueName); + const std::string& sMetricsGroup, + const std::string& sValueName); bool GetMetricRawRecursive(const IniFile& ini, const std::string& sMetricsGroup, const std::string& sValueName, @@ -187,10 +196,10 @@ class ThemeManager std::string GetElementDir(const std::string& sThemeName); static std::string GetMetricsIniPath(const std::string& sThemeName); static void GetLanguagesForTheme(const std::string& sThemeName, - vector& asLanguagesOut); + std::vector& asLanguagesOut); static std::string GetLanguageIniPath(const std::string& sThemeName, - const std::string& sLanguage); - void GetOptionalLanguageIniPaths(vector& vsPathsOut, + const std::string& sLanguage); + void GetOptionalLanguageIniPaths(std::vector& vsPathsOut, const std::string& sThemeName, const std::string& sLanguage); std::string GetDefaultLanguage(); diff --git a/src/RageUtil/Misc/RageLog.cpp b/src/RageUtil/Misc/RageLog.cpp index 240cc4076d..a53d0bd392 100644 --- a/src/RageUtil/Misc/RageLog.cpp +++ b/src/RageUtil/Misc/RageLog.cpp @@ -51,7 +51,7 @@ RageLog* LOG; // global and accessible from anywhere in the program * * The identifier is never displayed, so we can use a simple local object to * map/unmap, using any mechanism to generate unique IDs. */ -static map LogMaps; +static std::map LogMaps; #define LOG_PATH "/Logs/log.txt" #define INFO_PATH "/Logs/info.txt" @@ -102,7 +102,7 @@ RageLog::~RageLog() { /* Add the mapped log data to info.txt. */ const std::string AdditionalLog = GetAdditionalLog(); - vector AdditionalLogLines; + std::vector AdditionalLogLines; split(AdditionalLog, "\n", AdditionalLogLines); for (auto& AdditionalLogLine : AdditionalLogLines) { Trim(AdditionalLogLine); @@ -282,7 +282,7 @@ RageLog::Write(int where, const std::string& sLine) const char* const sWarningSeparator = "/////////////////////////////////////////"; - vector asLines; + std::vector asLines; split(sLine, "\n", asLines, false); if (where & WRITE_LOUD) { if (m_bLogToDisk && g_fileLog->IsOpen()) diff --git a/src/RageUtil/Misc/RageLog.h b/src/RageUtil/Misc/RageLog.h index 0ded74bf08..a8f1a2c83e 100644 --- a/src/RageUtil/Misc/RageLog.h +++ b/src/RageUtil/Misc/RageLog.h @@ -3,6 +3,8 @@ #ifndef RAGE_LOG_H #define RAGE_LOG_H +#include + class RageLog { public: diff --git a/src/RageUtil/Utils/RageUtil.cpp b/src/RageUtil/Utils/RageUtil.cpp index 299adbb277..20e9b64817 100644 --- a/src/RageUtil/Utils/RageUtil.cpp +++ b/src/RageUtil/Utils/RageUtil.cpp @@ -531,7 +531,7 @@ FillCharBuffer(char** eBuf, const char* szFormat, va_list argList) if (_resetstkoflw()) sm_crash("Unrecoverable Stack Overflow"); } - iUsed = vsnprintf(pBuf, iChars - 1, szFormat, argList); + iUsed = _vsnprintf(pBuf, iChars - 1, szFormat, argList); ++iTry; } while (iUsed < 0); @@ -1320,13 +1320,13 @@ DirectoryIsEmpty(const std::string& sDir) bool CompareRStringsAsc(const std::string& a, const std::string& b) { - return make_lower(a).c_str() > make_lower(b).c_str(); + return CompareNoCase(a, b) > 0; } bool CompareRStringsDesc(const std::string& a, const std::string& b) { - return make_lower(a).c_str() < make_lower(b).c_str(); + return CompareNoCase(b, a) > 0; } void